class DockDriver::I3

A class to provide IPC communication with i3wm.

Attributes

ipc[RW]

The IPC socket object.

path[RW]

The IPC socket path.

Public Class Methods

new( socket = '~/.i3/ipc.sock' ) click to toggle source

A constructor OF DOOM!

# File lib/dock_driver/i3.rb, line 30
def initialize( socket = '~/.i3/ipc.sock' )
    @path = Pathname( socket ).expand_path.to_s 
    @ipc = UNIXSocket.open( @path )
end

Public Instance Methods

command( cmd ) click to toggle source

Send a command to i3.

# File lib/dock_driver/i3.rb, line 36
def command( cmd )
    self.send_data( COMMAND, cmd )
end
get_workspaces() click to toggle source

Return an array of current workspace state.

# File lib/dock_driver/i3.rb, line 41
def get_workspaces
    self.send_data( GET_WORKSPACES )
    return self.read_data( GET_WORKSPACES )
end
subscribe_workspaces() click to toggle source

Register interest in workspace change events.

# File lib/dock_driver/i3.rb, line 47
def subscribe_workspaces
    self.send_data( SUBSCRIBE, JSON.generate(['workspace']))
    result = self.read_data( SUBSCRIBE )
    return result[ 'success' ]
end
wait_for_event( type, timeout=nil ) { |msg| ... } click to toggle source

Do a blocking select, yielding an event when one is seen.

# File lib/dock_driver/i3.rb, line 54
def wait_for_event( type, timeout=nil )
    sock = select( [self.ipc], nil, nil, timeout )
    return nil unless sock and type and msg = self.read_data( type )
    yield msg if block_given?
    return msg
end

Protected Instance Methods

read_data( expected_type=nil ) click to toggle source

Receive a message payload from i3, returning it as a data structure. Returns nil if a message wasn’t successfully read (closed socket, etc.) or if a type is specified and didn’t match the message’s type.

# File lib/dock_driver/i3.rb, line 78
def read_data( expected_type=nil )
    buf = self.ipc.read( MAGIC.bytes.count + 4 + 4 )
    return nil unless buf
    len, type = buf[6..-1].unpack( 'LL' )
    msg = self.ipc.read( len )

    return nil if ! expected_type.nil? && expected_type != type
    return JSON.parse( msg )
end
send_data( type, data=nil ) click to toggle source

Format a message payload and send it to i3.

# File lib/dock_driver/i3.rb, line 66
def send_data( type, data=nil )
    len = data.nil? ? 0 : data.to_s.bytes.count
    body = MAGIC + [ len, type ].pack( 'LL' )
    body << data.to_s unless data.nil?

    self.ipc.write( body )
end