Exemple #1
0
 def connect(self, addr):
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     gobject.io_add_watch(
         self.sock,
         gobject.IO_IN | gobject.IO_HUP,
         self.recv)
     print 'connect()', self.sock.connect(addr) # host, port
	def listener(self, sock, *args):
		'''Asynchronous connection listener. Starts a handler for each connection.'''
		conn, addr = sock.accept()
		loggy.log( "Connected from " + str(conn.getsockname()))
		gobject.io_add_watch(conn, gobject.IO_IN, self.handler)
		conn.send('OK MPD 0.16.0\n')
		return True
Exemple #3
0
def start(name):
    global logfilename, logfile, gui
    logfilename = name
    logfile = file(logfilename, "w")
    gobject.io_add_watch(sys.stdin, gobject.IO_IN, inputhandler)
    gui = GUI()
    gtk.main()
    def run(self, args, input_data, auto_close, pickle=False):
        self.response_active = False
        self.auto_close = auto_close
        self.error_lines = []
        self.pickle = pickle

        for button in self.buttons:
            button.set_sensitive(False)

        #print >> sys.stderr, "ZEOBUILDER, spawn process"
        self.process = subprocess.Popen(
            args, bufsize=0, stdin=subprocess.PIPE,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        if self.pickle:
            cPickle.dump(input_data, self.process.stdin, -1)
        else:
            self.process.stdin.write(input_data)
        self.process.stdin.close()

        #print >> sys.stderr, "ZEOBUILDER, add io_watch"
        self.event_sources = [
            gobject.io_add_watch(self.process.stdout, gobject.IO_IN, self._on_receive_out, priority=200),
            gobject.io_add_watch(self.process.stdout, gobject.IO_HUP, self._on_done, priority=200),
            gobject.io_add_watch(self.process.stderr, gobject.IO_IN, self._on_receive_err, priority=200),
        ]

        self.dialog.set_transient_for(context.parent_window)
        result = self.response_loop()
        self.dialog.hide()

        #print >> sys.stderr, "result", result
        return result
Exemple #5
0
 def notify_read(self, func):
     """ This function can be called when the callsite must know when data
     is coming from the serial port.   It is necessary that a gobject main
     loop is already running before calling this method.
     """
     gobject.io_add_watch(self.get_port().fd, gobject.IO_IN,
                          lambda fd, cond: func(self, cond))
 def fetch():
     if not url.endswith('css'):
         fd = urllib.urlopen(url)
         gobject.io_add_watch(fd.fp, gobject.IO_IN, self.readable, stream)
     else:
         if stream:
             stream.close()
    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address,
                                        RequestHandlerClass)
        self.socket.setblocking(0)  # Set nonblocking

        # Watch the listener socket for data
        gobject.io_add_watch(self.socket, gobject.IO_IN, self._handle_accept)
Exemple #8
0
 def _connect_local_socket(self):
     self._msg_sock = socket.socket(socket.AF_INET)
     self._msg_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self._msg_sock.bind(('127.0.0.1', 21693))
     self._msg_sock.listen(5)
     gobject.io_add_watch(self._msg_sock, gobject.IO_IN,
                          self._msg_sock_connection)
Exemple #9
0
  def main(self):
    self.thread_lock = threading.Lock()

    window = gtk.Window() #gtk.WINDOW_TOPLEVEL) 
    window.set_decorated(False)
    window.set_app_paintable(True)
    screen = window.get_screen()
    rgba = screen.get_rgba_colormap()
    window.set_colormap(rgba)
    
    window.set_title("Quark Web Browser Output")
    window.set_default_size(1100,710)
    window.set_decorated(False)
    window.connect("destroy", self.window_destroyed)
    window.connect('expose-event', self.expose)
    window.move(100,300)
    self.win = window
                
    window.show_all()

    (x,y,width,height,depth) = self.win.window.get_geometry()
    self.pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)

    msg.init()
    gobject.io_add_watch(msg.KCHAN.fileno(), gobject.IO_IN, self.handle_msgs)

    gtk.main()
Exemple #10
0
 def start_connecting(self):
     sock = socket.socket()
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     print "connecting.."
     sock.connect((HOST, PORT))
     print "connected"
     gobject.io_add_watch(sock, gobject.IO_IN, self.handler)
 def button_resume(widget):
     if self._tracing:
         return
     self._tracing = 1
     widget.set_label("Tracing ...")
     gobject.io_add_watch(self._tf, gobject.IO_IN, TrackFile)
     return
Exemple #12
0
    def __init__(self, path=os.path.join(yoga_ao_top, "glade"), parent=None, py2yo=None):

        self.path = path

        self.gladefile = "widget_sky.glade"

        self.glade = gtk.glade.XML(os.path.join(path, self.gladefile), root="top")
        self.top = self.glade.get_widget("top")

        # handle destroy event
        if self.top:
            self.top.connect("destroy", self.destroy)

        self.glade.signal_autoconnect(self)

        if parent:
            parent.foreach(parent.remove)
            parent.add(self.top)

        # Do not open stdin event if not in standalone mode
        if not py2yo:
            # set stdin non blocking, this will prevent readline to block
            fd = sys.stdin.fileno()
            flags = fcntl.fcntl(fd, fcntl.F_GETFL)
            fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)

            # add stdin to the event loop (yorick input pipe by spawn)
            gobject.io_add_watch(sys.stdin, gobject.IO_IN | gobject.IO_HUP, self.yo2py, None)

        # self.glade.get_widget('expander1').set_expanded(0)
        # self.glade.get_widget('expander2').set_expanded(0)
        self.glade.get_widget("layer_select").set_active(0)
        self.glade.get_widget("target_select").set_active(0)
Exemple #13
0
 def connect(self, callback, errback):
     self._reqID = 0
     self.connected = False
     self.errback = errback
     
     cmd = ['ssh', '-o', 'ConnectTimeout=6', self.hostname, 'sepiida-connect']
     self._process = process = subprocess.Popen(cmd, shell=False,
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      preexec_fn=os.setsid)
     sid1 = gobject.io_add_watch(process.stdout, gobject.IO_IN, self._readResponse)
     sid2 = gobject.io_add_watch(process.stdout, gobject.IO_ERR | gobject.IO_HUP, self._IOErr)
     self.sourceIDs = [sid1, sid2]
 
     def cbHello(server, data, error=''):
         if error:
             gobject.idle_add(errback, self, _('Not authorized'))
             self._process.wait()
             
             for sid in self.sourceIDs:
                 gobject.source_remove(sid)
         else:
             self.connected = True
             gobject.idle_add(callback, self)
     
     self._requests[self._reqID] = cbHello
Exemple #14
0
 def __init__(self, fd, separator):
     self.fd = fd
     self.count = 0
     self.prepend_timestamp = False
     self.prepend_count = False
     self.separator = separator
     gobject.io_add_watch(self.fd, gobject.IO_IN, self.parse_input)
Exemple #15
0
    def __init__(self, backend, socket, peer, rules):
        self._backend = backend
        self._socket = socket
        self._socket.setblocking(0)
        self._peer = peer

        self._rbuf = ""
        self._wbuf = ""
        self._read = 0
        self._written = 0

        self._read_delimiter = "\r\n\r\n"
        self._bytes_to_read = 0
        self._rcb = self.on_headers

        self._is_alive = True

        self._rules = rules

        self._in_id = gobject.io_add_watch(socket.fileno(),
                             gobject.IO_IN | gobject.IO_PRI,
                             self.on_read)
        self._out_id = gobject.io_add_watch(self._socket.fileno(),
                             gobject.IO_OUT,
                             self.on_write)
        self._err_id = gobject.io_add_watch(self._socket.fileno(),
                             gobject.IO_ERR,
                             self.on_error)
        self._hup_id = gobject.io_add_watch(self._socket.fileno(),
                             gobject.IO_HUP,
                             self.on_hang_up)
    def start_server(self):
        self.server_sock = bluetooth.BluetoothSocket (bluetooth.L2CAP)
        self.server_sock.bind(("",0x1001))
        self.server_sock.listen(1)

        gobject.io_add_watch(self.server_sock, 
                gobject.IO_IN, self.incoming_connection)
Exemple #17
0
    def __init__(self, gyotoytop):
        gobject.set_application_name("Gyotoy")
        gobject.set_prgname("Gyotoy")

        self.gyotoytop = gyotoytop
        self._pyk_blocked = 0
        self.length_unit = "geometrical"

        # read GUI definition
        self.glade = gtk.glade.XML(os.path.join(self.gyotoytop, "gyotoy.glade"))

        # handle destroy event (so that we can kill the window through window bar)
        self.window = self.glade.get_widget("window1")
        if self.window:
            self.window.connect("destroy", self.destroy)

        # autoconnect to callback functions
        # this will automatically connect the event handler "on_something_event"
        # to the here-defined function of the same name. This avoid defining a
        # long dictionary that serves the same purpose
        self.glade.signal_autoconnect(self)

        # set stdin non blocking, this will prevent readline to block
        # stdin is coming from yorick (yorick spawned this python process)
        fd = sys.stdin.fileno()
        flags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)

        # ... and add stdin to the event loop (yorick input pipe by spawn)
        gobject.io_add_watch(sys.stdin, gobject.IO_IN | gobject.IO_HUP, self.yo2py, None)

        # run: realize the interface, start event management
        gtk.main()
    def listen(self):

        # integrate the ooxcb event handlers into the gobject mainloop.
        gobject.io_add_watch(
                self.display.get_file_descriptor(),
                gobject.IO_IN,
                self._ooxcb_callback)
Exemple #19
0
	def build(self):
		self.create() # change me
		
		self._bottom_panel.activate_item(self._panel)
		
#		docs = self._window.get_unsaved_documents()
#		for doc in docs:
#			if doc.get_uri() != None:
#				doc.save(0)

		self._panel.clear()

		cmdline = "scons -Q debug=1"
		self.pipe = subprocess.Popen(cmdline.split(" "), stdout=PIPE, stderr=PIPE, cwd=self._directory)
		
		gobject.io_add_watch(self.pipe.stdout,
		                     gobject.IO_IN | gobject.IO_HUP,
		                     self.on_output)
		gobject.io_add_watch(self.pipe.stderr,
		                     gobject.IO_IN | gobject.IO_HUP,
		                     self.on_output)

		self._firstError = True
		# Wait for the process to complete
		gobject.child_watch_add(self.pipe.pid, self.on_child_end)
Exemple #20
0
 def listener(self, sock, *args):
     '''Asynchronous connection listener. Starts a handler for each connection.'''
     self.conn, self.addr = self.sock.accept()
     print _("Connected")
     gobject.io_add_watch(self.conn, gobject.IO_IN, self.handler)
     self.conn.send(self.msg_banner())
     return True
Exemple #21
0
    def _setup_fifo_watcher(self, fifo_socket):
        '''Open fifo socket fd and setup gobject IO_IN & IO_HUP watchers.
        Also log the creation of a fd and store the the internal
        self._watchers dictionary along with the filename of the fd.'''

        if fifo_socket in self._fifos.keys():
            fd, watchers = self._fifos[fifo_socket]
            os.close(fd)
            for watcherid in watchers.keys():
                gobject.source_remove(watchers[watcherid])
                del watchers[watcherid]

            del self._fifos[fifo_socket]
        
        # Re-open fifo and add listeners.
        fd = os.open(fifo_socket, os.O_RDONLY | os.O_NONBLOCK)
        watchers = {}
        self._fifos[fifo_socket] = (fd, watchers)
        watcher = lambda key, id: watchers.__setitem__(key, id)
        
        # Watch for incoming data.
        gid = gobject.io_add_watch(fd, gobject.IO_IN, self.main_fifo_read)
        watcher('main-fifo-read', gid)
        
        # Watch for fifo hangups.
        gid = gobject.io_add_watch(fd, gobject.IO_HUP, self.main_fifo_hangup)
        watcher('main-fifo-hangup', gid)
Exemple #22
0
def main():
    global vol,pipe
    pipe = None
    if sys.argv[1] == '1':
        pipe,vol = do_mic()
    elif sys.argv[1] == '2':
        pipe,vol = do_file()
        print "pipe %s vol %s" % (pipe,vol)
    else:
        print "what?"
        exit(1)

    print "initial volume: %s" % vol.get_property('volume')
    gobject.io_add_watch(sys.stdin, gobject.IO_IN, adjust_volume)

    # gtk.main()

    if sys.argv[1] == '1':
        gtk.main()

    loop = gobject.MainLoop()
    gobject.threads_init()
    bus = pipe.get_bus()
    while(1):
        msg = bus.poll(gst.MESSAGE_ANY, -1)
        if msg.type != gst.MESSAGE_STATE_CHANGED:
            # print msg.type
            pass
        if msg.type == gst.MESSAGE_EOS:
           # print "--- EOS"
           # pipe,vol = do_file()
           pipe.set_state(gst.STATE_READY)
           pipe.set_state(gst.STATE_PLAYING)
        pass
    def run(self):
        signal.signal(signal.SIGINT, self.terminate)
        signal.signal(signal.SIGTERM, self.terminate)
        setproctitle.setproctitle('pulse_watcher')

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        signals = (
            ('NewPlaybackStream', 'org.PulseAudio.Core1.{}',
                self.on_new_playback_stream),
            ('PlaybackStreamRemoved', 'org.PulseAudio.Core1.{}',
                self.on_playback_stream_removed),
            ('FallbackSinkUpdated', 'org.PulseAudio.Core1.{}',
                self.on_fallback_sink_updated),
            ('DeviceUpdated', 'org.PulseAudio.Core1.Stream.{}',
                self.on_device_updated),
        )
        self._connect(signals)
        self.update()
        self.default_sink = self.fallback_sink

        self.thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)

        mainloop = gobject.MainLoop()
        gobject.io_add_watch(
            self.message_queue._reader, gobject.IO_IN | gobject.IO_PRI,
            self._on_new_message)
        try:
            mainloop.run()
        except KeyboardInterrupt:
            pass
def startserver(host, port, window):
    def on_fifo_data(fd, *args):
        sck = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
        try:
            client, addr = sck.accept()
            client.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
            try:
                client.shutdown(socket.SHUT_RDWR)
            finally:
                client.close()
        except socket.error as err:
            pass
        toggle_visible(window)
        return True

    sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    sck.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sck.bind((host, port))
    sck.listen(socket.SOMAXCONN)
    gobject.io_add_watch(sck.fileno(), gobject.IO_IN, on_fifo_data)

    sighandler = makesighandler(sck)
    signal.signal(signal.SIGQUIT, sighandler)
    signal.signal(signal.SIGTERM, sighandler)
    signal.signal(signal.SIGINT, sighandler)
    atexit.register(sighandler)
Exemple #25
0
def run():
    """ Run the UI. """
    global loop
    loop = gobject.MainLoop()

    ui.set_mouse_tracking()
    app = appGUI()

    # Connect signals and whatnot to UI screen control functions
    bus.add_signal_receiver(app.dbus_scan_finished, 'SendEndScanSignal',
                            'org.wicd.daemon.wireless')
    bus.add_signal_receiver(app.dbus_scan_started, 'SendStartScanSignal',
                            'org.wicd.daemon.wireless')
    # I've left this commented out many times.
    bus.add_signal_receiver(app.update_netlist, 'StatusChanged',
                            'org.wicd.daemon')
    # Update the connection status on the bottom every 2 s.
    gobject.timeout_add(2000, app.update_status)

    # Get input file descriptors and add callbacks to the ui-updating function
    fds = ui.get_input_descriptors()
    for fd in fds:
        gobject.io_add_watch(fd, gobject.IO_IN, app.call_update_ui)
    app.update_ui()
    loop.run()
Exemple #26
0
   def __init__(self,spydrtop,spydr_showlower,spydr_dpi,spydr_showplugins):
      self.spydrtop = spydrtop
      self.spydr_showlower = spydr_showlower
      self.spydr_defaultdpi = spydr_dpi
      self.spydr_dpi = spydr_dpi
      self.spydr_showplugins = spydr_showplugins
      self.usercmd = 'STOP'

      # callbacks and glade UI

      self.glade = gtk.glade.XML(os.path.join(self.spydrtop,'spydr.glade'))
      self.window = self.glade.get_widget('window1')
      # handle destroy event
      if (self.window):
         self.window.connect('destroy', self.destroy)
      self.glade.signal_autoconnect(self)

      # set stdin non blocking, this will prevent readline to block
      fd = sys.stdin.fileno()
      flags = fcntl.fcntl(fd, fcntl.F_GETFL)
      fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)

      # add stdin to the event loop (yorick input pipe by spawn)
      gobject.io_add_watch(sys.stdin,gobject.IO_IN|gobject.IO_HUP,self.yo2py,None)

      # update parameters from yorick:
      #self.py2yo('gui_update')

      ebox = self.glade.get_widget('vbox3')
      ebox.connect('key-press-event',self.on_vbox3_key_press)

      # set size of graphic areas:
      self.drawingareas_size_allocate(spydr_dpi)

      self.pyk_debug=0
      self.win_init_done = 0
      self.currentdir=os.getcwd()
      self.currentsavedir=os.getcwd()
      self.imgroup=None
      self.current_image_menu=0
      self.current_image_saveas_name=None
      self.just_done_range=0
      self.next_to_all = 0

      if (spydr_showlower==0):
         if (spydr_dpi < 70):
            self.glade.get_widget('frame1').hide()
         if (spydr_dpi < 85):
            self.glade.get_widget('frame2').hide()
         self.glade.get_widget('table1').hide()
         self.glade.get_widget('drawingarea3').hide()
         self.glade.get_widget('togglelower').set_active(0)

      if (spydr_showplugins):
         self.glade.get_widget('plugins_pane').show()

      self.pyk_status_push(1,'Initializing...')

      # run
      gtk.main()
Exemple #27
0
 def __init__(self, sock, addr, clients, pinfo_msg, msg_handler_fn, c_type):
     
     self.__sock = sock
     self.__addr = addr
     self.__clients = clients
     self.__pinfo_msg = pinfo_msg
     self.__msg_handler_fn = msg_handler_fn
     self.__conn_type = c_type
     
     # client info
     self.info = ClientInfo()
     self.__psave = False
     
     # the following fields are used for iterative receiving on message data
     # see io_recv() and io_recv_buff()
     self.__rcv_buff_header = ReceiveBuffer()
     self.__rcv_buff_data = ReceiveBuffer()
     self.__rcv_msg_id = message.IGNORE
     self.__rcv_msg_size = 0
     
     self.__snd_buff = "" # buffer for outgoing data
     
     # source IDs for various events
     self.__sids = [
         gobject.io_add_watch(self.__sock, gobject.IO_IN, self.__io_recv),
         gobject.io_add_watch(self.__sock, gobject.IO_ERR, self.__io_error),
         gobject.io_add_watch(self.__sock, gobject.IO_HUP, self.__io_hup)
         ]
     self.__sid_out = 0
     
     log.debug("send 'hello' to %s" % self)
     
     self.send(ClientConnection.IO_HELLO)
Exemple #28
0
    def _receive(self, conn, cond, data):
        try:
            recv = conn.recv(4096)
        except socket.error as e:
            if er.errno in (errno.EAGAIN, errno.EINTR):
                return True
            raise
        else:
            if recv == '':
                gobject.source_remove(data['tag'])
                conn.close()
                return True

            data['buffer'] += recv
            if 'header' not in data and len(data['buffer']) >= HDRLEN:
                data['header'] = struct.unpack("!L", data['buffer'][:HDRLEN])
                data['buffer'] = data['buffer'][HDRLEN:]
            if 'header' in data:
                if len(data['buffer']) < data['header'][0]:
                    return True

            req = self._unpack_body(data['buffer'])
            data['result'] = self._pack_reply(self.handler(req))
            gobject.io_add_watch(conn, gobject.IO_OUT, self._send, data)
            return False
Exemple #29
0
 def handle_input(self, source, condition):
     #olog("handle_input:")
     m = self.message_handler.recv()
     if m[0] == message.RenderCompleted :
         # load a new shared memory
         #olog("display msg is received")
         shmid = int(m[1])
         if self.shm_obj <> None:
             if self.shm_obj.shmid == shmid :
                 self.redraw()
             else:
                 self.thread_lock.acquire()
                 try :
                     self.shm_obj.detach()
                     self.shm_obj = shm.memory(shmid)
                     self.sem_obj = shm.semaphore(shm.getsemid(shmid))
                     self.shm_obj.attach()
                 finally:
                     self.thread_lock.release()
         else :
             self.thread_lock.acquire()
             try :
                 self.shm_obj = shm.memory(shmid)
                 self.sem_obj = shm.semaphore(shm.getsemid(shmid))
                 self.shm_obj.attach()
             finally:
                 self.thread_lock.release()
     else :
         sys.stderr.write('invalid event type\n')
         sys.exit(1)
     gobject.io_add_watch(self.soc.fileno(), gobject.IO_IN, self.handle_input)
     return False
Exemple #30
0
    def main(self):
        self.thread_lock = threading.Lock()
        self.shm_obj = None
        self.sem_obj = None

        self.soc = socket.fromfd(int(sys.argv[1]), msg.FAMILY, msg.TYPE)

        gobject.io_add_watch(self.soc.fileno(), gobject.IO_IN, self.handle_input)
        gobject.io_add_watch(self.soc.fileno(), gobject.IO_HUP, self.handle_hup)

        window = gtk.Window() #gtk.WINDOW_TOPLEVEL) 
        window.set_decorated(False)
        window.set_app_paintable(True)
        screen = window.get_screen()
        rgba = screen.get_rgba_colormap()
        window.set_colormap(rgba)

        window.set_title("Quark Web Browser Output")
        window.set_default_size(1100,710)
        #window.set_keep_above(True)
        window.set_decorated(False)
        window.connect("destroy", self.window_destroyed)
        window.connect('expose-event', self.expose)
        window.move(100,300)
        self.win = window
                
        window.show_all()

        (x,y,width,height,depth) = self.win.window.get_geometry()
        self.pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
        gtk.main()
Exemple #31
0
    def on_connect(self, widget):
        if self.client:
            self.client.close()
            self.client = None

        if self.status_icon:
            self.status_icon.set_from_stock(gtk.STOCK_DISCONNECT,
                                            gtk.ICON_SIZE_LARGE_TOOLBAR)

        # prompt user for hostname
        dialog = gtk.Dialog("Select host", None,
                            gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                            (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                             gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        dialog.show()
        entry = gtk.combo_box_new_text()
        for hn, kn in HOST_ADDR_LIST.iteritems():
            entry.append_text(hn)
        dialog.vbox.pack_start(entry, True, True, 0)
        entry.show()
        entry.set_active(0)
        response = dialog.run()
        if response == gtk.RESPONSE_REJECT:
            dialog.destroy()
            return
        hostname = entry.get_active_text()
        dialog.destroy()

        self.messages.append("Trying to connect to " + hostname)

        # create socket
        self.client = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)
        addr = HOST_ADDR_LIST[hostname]
        port = 17
        address = (addr, port)

        try:
            print "trying to connect to " + addr
            self.client.connect(address)
            gobject.io_add_watch(self.client, gobject.IO_IN, self.handle_data)
            self._connected = True
            self.messages.append("Connected to " + hostname)
            print "connected!"
        except error:
            self.client.close()
            self.client = None
            self._connected = False
            self.dialog("Connection failed!", gtk.MESSAGE_ERROR)

        if self.client and self.status_icon:
            self.status_icon.set_from_stock(gtk.STOCK_CONNECT,
                                            gtk.ICON_SIZE_LARGE_TOOLBAR)
Exemple #32
0
 def __init__(self,dev_num): 
     gobject.GObject.__init__(self) 
     #define the device 
     device = '/dev/input/js%s' % dev_num 
     #error check that this can be read 
     try: 
         #open the joystick device 
         self.device = open(device) 
         #keep an eye on the device, when there is data to read, execute the read function 
         gobject.io_add_watch(self.device,gobject.IO_IN,self.read_buttons) 
     except Exception,ex:
         #raise an exception 
         raise Exception( ex ) 
 def __init__(self, sock, callbacks, myid=0):
     self.sock = sock
     self.__reset()
     self.callbacks = callbacks
     self.myid = myid
     self.partid = 1
     self.is_server = True
     sock.setblocking(0)
     gobject.io_add_watch(self.sock.fileno(), gobject.IO_IN,
                          self.__data_in)
     gobject.io_add_watch(self.sock.fileno(),
                          gobject.IO_ERR | gobject.IO_HUP,
                          self.__error)
Exemple #34
0
    def watch_debconf_fd(self, from_debconf, process_input):
        """Event loop interface to debconffilter.

        A frontend typically provides its own event loop. When a
        debconffiltered command is running, debconffilter must be given an
        opportunity to process input from that command as it arrives. This
        method will be called with from_debconf as a file descriptor reading
        from the filtered command and a process_input callback which should
        be called when input events are received."""

        gobject.io_add_watch(from_debconf,
                             gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP,
                             self.watch_debconf_fd_helper, process_input)
Exemple #35
0
 def __init__(self):
     self.commands = []
     self.pending = GdbCommand('dummy')
     self.pending.prompted = False
     self.pending.returned = True
     self.handle_event = None
     self.status_changed = None
     self.gdb = subprocess.Popen(
             ['gdb', '--interpreter=mi2'],
             stdin=subprocess.PIPE,
             stdout=subprocess.PIPE)
     set_non_blocking(self.gdb.stdout)
     gobject.io_add_watch(self.gdb.stdout, gobject.IO_IN, self.__read_gdb)
Exemple #36
0
    def send(self, data, handler=None):
        if handler is None:

            def handler(source, condition):
                data = source.recv(1024)
                if len(data) > 0:
                    print "RECEIVED: " + data
                    return True
                else:
                    return False

        self.socket.send(data)
        gobject.io_add_watch(self.socket, gobject.IO_IN, handler)
Exemple #37
0
    def __init__(self, server_address, handler_class, allowed_ip='*'):
        self._handler_class = handler_class
        self._allowed_ips = []
        self.add_allowed_ip(allowed_ip)

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(server_address)
        self.socket.setblocking(0)  # Set nonblocking

        # Watch the listener socket for data
        gobject.io_add_watch(self.socket, gobject.IO_IN, self._handle_accept)
        self.socket.listen(1)
Exemple #38
0
    def start(self):
        self.proc = subprocess.Popen(
            self.args,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        self._out = gobject.io_add_watch(self.proc.stdout, gobject.IO_IN,
                                         self.on_buff_read, "stdout-data")
        self._err = gobject.io_add_watch(self.proc.stderr, gobject.IO_IN,
                                         self.on_buff_read, "stderr-data")
        gobject.child_watch_add(self.proc.pid, self.on_finished)
        self.emit("started", self.proc.pid)
Exemple #39
0
 def start_daemon(self):
     try:
         self.root.change_attributes(event_mask=X.KeyPressMask)
         self.keys = {self.display.keysym_to_keycode(k):self.KEYS[k] for k in self.KEYS}
         for keycode in self.keys:
             self.root.grab_key(keycode, X.ControlMask | X.Mod1Mask, 1, X.GrabModeAsync, X.GrabModeAsync)
             self.root.grab_key(keycode, X.ControlMask | X.Mod1Mask | X.Mod2Mask, 1, X.GrabModeAsync, X.GrabModeAsync)
         for event in range(0, self.root.display.pending_events()):
             self.root.display.next_event()
         gobject.io_add_watch(self.root.display, gobject.IO_IN, self.handle_event)
         gtk.main()
     except KeyboardInterrupt:
         print "Stopping PyGrid daemon"
Exemple #40
0
    def start_writing(self):
        def outgoing(socket, condition):
            if len(self.codebuffer) > 0:
                sent = socket.send(self.codebuffer)
                self.emit("new_message", DIR_OUTGOING, "[your code...]\n")
                self.codebuffer = self.codebuffer[sent:]
            elif len(self.outbuffer) > 0:
                sent = socket.send(self.outbuffer)
                self.emit("new_message", DIR_OUTGOING, self.outbuffer[:sent])
                self.outbuffer = self.outbuffer[sent:]
            return len(self.codebuffer) > 0 or len(self.outbuffer) > 0

        gobject.io_add_watch(self.socket, gobject.IO_OUT, outgoing)
Exemple #41
0
 def serve_forever(self, poll_interval=0.5):
     self.mainloop = gobject.MainLoop()
     gobject.io_add_watch(self, gobject.IO_IN | gobject.IO_PRI,
                          self._on_new_request)
     context = self.mainloop.get_context()
     while True:
         try:
             if context.pending():
                 context.iteration(True)
             else:
                 time.sleep(0.1)
         except KeyboardInterrupt:
             break
Exemple #42
0
        def response(box, resp):
            if resp == _RESPONSE_NEXT:
                iface = uri.get_text()
                if not self._sanity_check(iface):
                    return
                self.window.set_sensitive(False)
                self.set_keep_above(False)
                import subprocess
                child = subprocess.Popen(
                    ['0launch', '--gui', '--download-only', '--', iface],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT)
                errors = ['']

                def output_ready(src, cond):
                    got = os.read(src.fileno(), 100)
                    if got:
                        errors[0] += got
                    else:
                        status = child.wait()
                        self.window.set_sensitive(True)
                        self.set_keep_above(True)
                        if status == 0:
                            update_details_page()
                            nb.next_page()
                            dialog_next.set_property('visible', False)
                            dialog_ok.set_property('visible', True)
                            dialog_ok.grab_focus()
                        else:
                            box = gtk.MessageDialog(
                                self.window, gtk.DIALOG_MODAL,
                                gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
                                _('Failed to run 0launch.\n') + errors[0])
                            box.run()
                            box.destroy()
                        return False
                    return True

                gobject.io_add_watch(child.stdout,
                                     gobject.IO_IN | gobject.IO_HUP,
                                     output_ready)
            elif resp == gtk.RESPONSE_OK:
                finish()
            elif resp == _RESPONSE_PREV:
                dialog_next.set_property('visible', True)
                dialog_ok.set_property('visible', False)
                dialog_next.grab_focus()
                nb.prev_page()
                self.window.set_response_sensitive(_RESPONSE_PREV, False)
            else:
                box.destroy()
Exemple #43
0
 def readyHandler(source, condition):
     data = source.recv(1024)
     data = data.strip().split(" ")
     if len(data) == 4:
         self.myTurn = True
     else:
         gobject.io_add_watch(self.socket, gobject.IO_IN,
                              self.boardHandler)
     self.opponent = data[1]
     self.myPiece = int(data[2])
     print "My piece is %d" % self.myPiece
     self.board = [[-1, -1, -1], [-1, -1, -1], [-1, -1, -1]]
     self.refresh()
     return False
Exemple #44
0
def childmain(conn, remoteobject, loglevel, logqueue, arg, kwarg):
	'''Main function for child processes'''
	global SERVER_CONTEXT
	global _recursive_conn_lock
	_recursive_conn_lock = True

	setup_child_logging(loglevel, logqueue)
	zim.errors.set_use_gtk(True)
		# Assume any child process to be a gui process

	try:
		klassname, id = remoteobject.klassname, remoteobject.id

		# __import__ has some quirks, see the reference manual
		modname, klassname = klassname.rsplit('.', 1)
		mod = __import__(modname)
		for name in modname.split('.')[1:]:
			mod = getattr(mod, name)
		klass = getattr(mod, klassname)
		assert hasattr(klass, 'main'), 'Child process objects should at least have a "main()" and a "quit()"'
		assert hasattr(klass, 'quit'), 'Child process objects should at least have a "main()" and a "quit()"'

		SERVER_CONTEXT = ServerProxyClass(ischildprocess=True)

		if id is None:
			obj = klass(*arg, **kwarg)
		else:
			obj = klass(id, *arg, **kwarg)
		#~ print '>>>> CREATED', obj

		adapter = ConnectionAdapter(conn, remoteobject, obj)
		RemoteObjectProxy._client_proxy_authkey = multiprocessing.current_process().authkey
			# Since we inherit from the server, we inherit authkey
		SERVER_CONTEXT.set_adapter(adapter)
			# Need to set adapter to allow "connect()" via SERVER_CONTEXT
			# FIXME - improve object dependencies to allow connect from
			# klass init as well

		if sys.platform == 'win32':
			# Windows pipe
			# idle handler uses a bit to much CPU for my taste,
			# timeout every 0.5 sec is better - poll() check for queue
			gobject.timeout_add(500, adapter.poll)
		else:
			# multiprocessing uses unix file desriptors
			gobject.io_add_watch(conn.fileno(), gobject.IO_IN, adapter.poll)
	except Exception, err:
		logger.exception('Exception while setting up child process')
		conn.send(err)
		_recursive_conn_lock = False
Exemple #45
0
    def setup_fifo_watchers(self):
        '''Open fifo socket fd and setup gobject IO_IN & IO_HUP event
        handlers.'''

        # Close currently open fifo_socket fd and kill all watchers
        self.close_fifo()

        fd = os.open(self.fifo_socket, os.O_RDONLY | os.O_NONBLOCK)

        # Add gobject io event handlers to the fifo socket.
        watchers = [io_add_watch(fd, IO_IN, self.main_fifo_read),\
          io_add_watch(fd, IO_HUP, self.main_fifo_hangup)]

        self._fifo = (fd, watchers)
Exemple #46
0
 def __init__(self, conn, address, progress, parent):
     self.dcmprss = zlib.decompressobj()
     gobject.io_add_watch(conn,
                          gobject.IO_IN,
                          self.event_cb,
                          priority=gobject.PRIORITY_DEFAULT_IDLE)
     self.state = 0
     self.buffer = common.Buffer()
     progress.show()
     progress.set_text("Waiting for header...")
     #progress.show()
     self.progress = progress
     self.address = address
     self.parent = parent
Exemple #47
0
 def _connection(self, sock, cond):
     try:
         conn, _ = self.sock.accept()
     except socket.error as er:
         if er.errno in (errno.EAGAIN, errno.EINTR):
             return True
         raise
     else:
         flags = fcntl.fcntl(conn, fcntl.F_GETFD)
         fcntl.fcntl(conn, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
         conn.setblocking(0)
         data = {'buffer': ''} #object which holds connection state
         gobject.io_add_watch(conn, gobject.IO_IN, self._receive, data)
         return True
Exemple #48
0
 def send(self, message, callback=None):
     self._socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     try:
         self._socket.connect('/tmp/gsrvdir1000/gsrv')
         self._socket.send('\4%s\4' % message)
         if callback:
             self.callbacks[self._socket.fileno()] = callback
             gobject.io_add_watch(self._socket, gobject.IO_IN,
                                  self.cb_readable)
     except socket.error, e:
         ecode = e.args[0]
         if ecode == 111:
             #self.launch()
             self.cb.evt('disconnected')
Exemple #49
0
def server(host, port, skype = None):
	global options
	if ":" in host:
		sock = socket.socket(socket.AF_INET6)
	else:
		sock = socket.socket()
	sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	sock.bind((host, port))
	sock.listen(1)
	if hasgobject:
		gobject.io_add_watch(sock, gobject.IO_IN, listener)
	else:
		dprint("Waiting for connection...")
		listener(sock, skype)
Exemple #50
0
    def __init__(self, sys_file):
        self.__log = getLogger('panucci.serivces.__headphone_watcher')
        ObservableService.__init__(self, self.signals, self.__log)

        self.__is_connected = None

        if platform.MAEMO and not platform.FREMANTLE:
            try:
                self.__sys_file = open(sys_file, 'r')
                self.__is_connected = self.__get_state_from_fd(self.__sys_file)
                gobject.io_add_watch(self.__sys_file, gobject.IO_PRI,
                                     self.__on_status_changed)
            except IOError:
                self.__log.exception("Can't open headphone status file.")
Exemple #51
0
    def __init__ (self, cmd, resultHandler, prio=gobject.PRIORITY_LOW):
        self.lineSplitter = LineSplitter(resultHandler)

        #print "executing command: %s" % cmd
        self.popenObj = popen2.Popen3(cmd)
        self.pipe = self.popenObj.fromchild

        # make pipe non-blocking:
        fl = fcntl.fcntl(self.pipe, fcntl.F_GETFL)
        fcntl.fcntl(self.pipe, fcntl.F_SETFL, fl | os.O_NONBLOCK)

        #print "(add watch)"
        gobject.io_add_watch(self.pipe, gobject.IO_IN | gobject.IO_ERR | gobject.IO_HUP,
            self.onPipeReadable, priority=prio)
    def main(self):

        # begin to listen
        self.socket = lrs_net_init()

        # gather results when available
        gobject.io_add_watch(self.socket, gtk.gdk.INPUT_READ,
                             self._cb_refresh_backupdata)

        # refresh display
        gobject.timeout_add(BEAM_LRS_THREAD_AWAKE,
                            self._cb_refresh_backupdisplay)

        gtk.main()
        sys.exit()
Exemple #53
0
    def init_alsa(self):
        try:
            self.mixer = alsaaudio.Mixer(self.MASTER, 0, self.CARD)
        except alsaaudio.ALSAAudioError:
            print >> sys.stderr, 'Could not initialize mixer'
            sys.exit(2)

        try:
            self.headphone = alsaaudio.Mixer('Headphone', 0, self.CARD)
            self.speaker = alsaaudio.Mixer('Speaker', 0, self.CARD)
        except alsaaudio.ALSAAudioError:
            pass

        fd, eventmask = self.mixer.polldescriptors()[0]
        gobject.io_add_watch(fd, eventmask, self.watch)
Exemple #54
0
 def create_server_socket(self):
     logger.info("Creating stream socket %s" % self.portnumber)
     s = sk.socket(sk.AF_INET, sk.SOCK_STREAM, 0)
     s.setsockopt(sk.SOL_SOCKET, sk.SO_REUSEADDR, 1)
     s.setblocking(False)
     s.bind((self.interface, self.portnumber))
     s.listen(128)
     flag = 0
     for f in dir(gobject):
         if f.startswith('IO_'):
             print f
             flag |= getattr(gobject, f)
     gobject.io_add_watch(s.fileno(), flag, self.connection_ready)
     logger.info("Stream Server ready")
     self.socket = s
def inputhook(context):
    """
    When the eventloop of prompt-toolkit is idle, call this inputhook.

    This will run the GTK main loop until the file descriptor
    `context.fileno()` becomes ready.

    :param context: An `InputHookContext` instance.
    """
    def _main_quit(*a, **kw):
        gtk.main_quit()
        return False

    gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit)
    gtk.main()
Exemple #56
0
        def __init__(self,
                     watch_manager,
                     default_proc_fun=None,
                     read_freq=0,
                     threshold=0,
                     timeout=None):
            """
			Initializes the gobject notifier. See the
			Notifier class for the meaning of the parameters.

			"""
            pyinotify.Notifier.__init__(self, watch_manager, default_proc_fun,
                                        read_freq, threshold, timeout)
            gobject.io_add_watch(self._fd, gobject.IO_IN | gobject.IO_PRI,
                                 self.handle_read)
Exemple #57
0
 def __create_gena_socket(self):
     """
     Creates an asynchronous socket for listening to GENA events.
     """
     
     self.__gena_url = "http://%s:%d" % (network.get_ip(), _PORT)
     
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     sock.bind(("", _PORT))
     sock.listen(1)
     
     gobject.io_add_watch(sock, gobject.IO_IN, self.__on_new_client)
     
     return sock
 def init(self, exit_cb, sockfile=TEST_SOCKFILE):
     log.info("SimpleServer(%s, %s)", exit_cb, sockfile)
     if os.path.exists(sockfile):
         os.unlink(sockfile)
     self.exit_cb = exit_cb
     sock = socket.socket(socket.AF_UNIX)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     sock.setblocking(1)
     orig_umask = os.umask(127)  #600
     sock.bind(sockfile)
     os.umask(orig_umask)
     sock.listen(5)
     self.listener = sock
     gobject.io_add_watch(sock, gobject.IO_IN, self.new_connection, sock)
     log.info("SimpleServer() on %s", sock)
Exemple #59
0
    def __init__(self):
        # Connect to the panel to get the panel events.
    
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.connect("delete_event", self.delete_event)
        window.connect("destroy", self.destroy)
        window.set_border_width(10)
        window.show()   # show window
        
        vbox = gtk.VBox(False,0)
        window.add(vbox)
        vbox.show()
        self.vbox = vbox
        
        area = gtk.DrawingArea()
        area.set_size_request(400, 116)
        vbox.pack_start(area, True, True, 0)
        area.show()
        
        area.connect("expose_event", self.expose_event)
        area.connect("configure_event", self.configure_event)

        # colours
        self.pixelon = area.window.new_gc()
        self.pixelon.set_rgb_fg_color(gtk.gdk.color_parse("#000000"))
        self.pixeloff = area.window.new_gc()
        self.pixeloff.set_rgb_fg_color(gtk.gdk.color_parse("#949494"))
        self.background = area.window.new_gc()
        self.background.set_rgb_fg_color(gtk.gdk.color_parse("#c6c6c6"))
        self.white = area.window.new_gc()
        self.white.set_rgb_fg_color(gtk.gdk.color_parse("#ffffff"))
        self.shade = area.window.new_gc()
        self.shade.set_rgb_fg_color(gtk.gdk.color_parse("#dedede"))
        
        self.window = window
        self.area = area
        self.vbox = vbox
        
        self.pixmap = None
        self.font = lcdfont.Font5x7()
        self.pixel = 4
        self.bezel = 18
        
        self.lcd_text = "\x00" * 32 
        panel = PanelEvents(self.repaint, self.lcd_text)
        gobject.io_add_watch(panel.socket, gobject.IO_IN|gobject.IO_HUP,self.poll_now)
        for i in range(10):
          asyncore.poll()  # make the connection
Exemple #60
0
    def send(self, msg):
        """Send a message to the client.
        
        @param msg:
            complete message (incl. ID and length) in binary format
            (net.build_message() is your friend here)
        
        @see: net.build_message()
        
        """

        if msg is None:
            log.error("** BUG ** msg is None")
            return

        if self.__sock is None:
            log.debug("cannot send message to %s, already disconnected" % self)
            return

        if self.__psave:
            log.debug("%s is in sleep mode, send nothing" % self)
            return

        self.__snd_buff = "%s%s" % (self.__snd_buff, msg)

        # if not already trying to send data ..
        if self.__sid_out == 0:
            # .. do it when it is possible:
            self.__sid_out = gobject.io_add_watch(self.__sock, gobject.IO_OUT,
                                                  self.__io_send)