Preface

Goal: Manage Herbstclient process trigerred by idle event

Focusing in "herbstclient --idle". 

HerbstluftWM: Tag Status

This is the next Part, of the previous Tutorial. This tutorial cover Lemonbar. In order to use Dzen2, any reader could use the source code in github.


Reading

Before you jump off to scripting, you might desire to read this overview.

All The Source Code:

Impatient coder like me, like to open many tab on browser.

The PipeHandler Source File:

Let’s have a look at pipehandler.lua in github.


HerbstluftWM Idle Event in Many Languages

This article is one part of a collection. All integrated, on related to another. So we can compare each other quickly.

Tutorial/ Guidance/ Article: [ Idle Event Overview ] [ BASH ] [ Perl ] [ Python ] [ Ruby ] [ PHP ] [ Lua ] [ Haskell ]

Dzen2 Source Code Directory: [ BASH ] [ Perl ] [ Python ] [ Ruby ] [ PHP ] [ Lua ] [ Haskell ]

Lemonbar Source Code Directory: [ BASH ] [ Perl ] [ Python ] [ Ruby ] [ PHP ] [ Lua ] [ Haskell ]


Statusbar Screenshot

Dzen2

Statusbar: Dzen2 Screenshot

Lemonbar

Statusbar: Lemonbar Screenshot


Without Idle event

Let’s have a look at our main panel.lua in github. At the end of the script, we finally call lemonbar with detach_lemon function.

-- remove all lemonbar instance
os.execute('pkill lemonbar')

-- run process in the background
pipehandler.detach_lemon(monitor, lemon_parameters)

View Source File:

Run Lemon, Run !

This detach_lemon function. is just a function that enable the lemonbar running process to be detached, using posix.fork().

function _M.detach_lemon(monitor, parameters)
    local pid_lemon = posix.fork()

    if pid_lemon == 0 then -- this is the child process
        _M.run_lemon(monitor, parameters)
    else                   -- this is the parent process
        -- nothing
    end
end

The real function is run_lemon. You must be familiar with this io.popen.

function _M.run_lemon(monitor, parameters) 
    local command_out  = 'lemonbar ' .. parameters .. ' -p'
    local pipe_lemon_out = assert(io.popen(command_out, 'w'))
    
    _M.content_init(monitor, pipe_lemon_out)       
    pipe_lemon_out:close()
end

Note: that we want to ignore idle event for a while. And append the -p for a while, to make the statusbar persistent.

Statusbar Initialization

Here we have the content_init. It is just an initialization of global variable. We are going to have some loop later in different function, to do the real works.

function _M.content_init(monitor, pipe_lemon_out)
    output.set_tag_value(monitor)
    output.set_windowtitle('')

    local text = output.get_statusbar_text(monitor)
    pipe_lemon_out:write(text .. "\n")
    pipe_lemon_out:flush()
end

Now is time to try the panel, on your terminal. Note: that we already reach this stage in our previous article. These two functions, set_tag_value and set_windowtitle, have already been discussed.

View Source File:

Simple version. No idle event. Only statusbar initialization.


With Idle event

Consider this content_walk call, after content_init call, inside the run_lemon.

function _M.run_lemon(monitor, parameters) 
    local command_out  = 'lemonbar ' .. parameters
    local pipe_lemon_out = assert(io.popen(command_out, 'w'))
    
    _M.content_init(monitor, pipe_lemon_out)
    _M.content_walk(monitor, pipe_lemon_out) -- loop for each event
        
    pipe_lemon_out:close()
end

Wrapping Idle Event into Code

content_walk is the heart of this script. We have to capture every event, and process the event in event handler.

Walk step by step, Process event by event

After the event handler, we will get the statusbar text, in the same way, we did in content_init.

function _M.content_walk(monitor, pipe_lemon_out)    
    -- start a pipe
    command_in = 'herbstclient --idle'
    local pipe_in  = assert(io.popen(command_in,  'r'))
    local text = ''
  
    -- wait for each event, trim newline
    for event in pipe_in:lines() do
        _M.handle_command_event(monitor, common.trim1(event))
    
        text = output.get_statusbar_text(monitor)
        pipe_lemon_out:write(text .. "\n")
        pipe_lemon_out:flush()
    end -- for loop
   
    pipein:close()
end

The Event Handler

For each idle event, there are multicolumn string. The first string define the event origin.

HerbstluftWM: Tag Status

The origin is either reload, or quit_panel, tag_changed, or tag_flags, or tag_added, or tag_removed, or focus_changed, or window_title_changed. More complete event, can be read in herbstclient manual.

All we need is to pay attention to this two function. set_tag_value and set_windowtitle.

function _M.handle_command_event(monitor, event)
    -- find out event origin
    local column = common.split(event, "\t")
    local origin = column[1] -- non zero based

    local tag_cmds = {'tag_changed', 
         'tag_flags', 'tag_added', 'tag_removed'}
    local title_cmds = {'window_title_changed', 'focus_changed'}

    if origin == 'reload' then
        os.execute('pkill lemonbar')
    elseif origin == 'quit_panel' then
        os.exit()
    elseif common.has_value(tag_cmds, origin) then
        output.set_tag_value(monitor)
    elseif common.has_value(title_cmds, origin) then
        local title = (#column > 2) and (column[3]) or ''
        output.set_windowtitle(title)
    end
end

Actually that’s all we need to have a functional lemonbar. This is the minimum version.

Be aware, that Lua is using non zero based array.

    origin = column[1]

View Source File:

With idle event. The heart of the script.


Lemonbar Clickable Areas

This is specific issue for lemonbar, that we don’t have in dzen2.

Consider have a look at output.lua.

    -- clickable tags
    local text_name = '%{A:herbstclient focus_monitor '
                   .. '"' .. monitor .. '" && '
                   .. 'herbstclient use "' .. tag_index .. '":}'
                   .. ' ' .. tag_name ..' %{A} 

Issue: Lemonbar put the output on terminal instead of executing the command.

HerbstluftWM: Tag Status

Consider going back to pipehandler.lua.

We need to pipe the lemonbar output to shell. It means Lemonbar read input and write output at the same time. But the real issue is Lua does not support bidirectional pipe.

function _M.run_lemon(monitor, parameters) 
    -- no bidirectional in Lua, using shell pipe instead
    local command_out  = 'lemonbar ' .. parameters .. ' | sh'
    local pipe_lemon_out = assert(io.popen(command_out, 'w'))
    
    _M.content_init(monitor, pipe_lemon_out)
    _M.content_walk(monitor, pipe_lemon_out) -- loop for each event
        
    pipe_lemon_out:close()
end

There is complex solution using posix.pipe. We are going to use posix.pipe for a simple case later, the combined event case.

How does it work ?

Using shell pipe.
    local command_out  = 'lemonbar ' .. parameters .. ' | sh'

I know that piping using | sh looks primitive. But it does works. So why bother ?

View Source File:

Piping lemonbar output to shell, implementing lemonbar clickable area.

Interval Based Event

We can put custom event other than idle event in statusbar panel. This event, such as date event, called based on time interval in second.

It is a little bit tricky, because we have to make, a combined event that consist of, idle event (asynchronous) and interval event (synchronous). Merging two different paralel process into one.

This is an overview of what we want to achieve.

HerbstluftWM: Custom Event

In real code later, we do not need the timestamp. interval string is enough to trigger interval event.

View Testbed Source File:

Before merging combined event into main code, consider this test in an isolated fashion.


Combined Event

Preparing The View

This is what it looks like, an overview of what we want to achieve.

Statusbar: Event Screenshot

Consider make a progress in output.py.

_M.segment_datetime    = '' -- empty string

function _M.get_statusbar_text(monitor)
    ...

    -- draw date and time
    text = text .. '%{c}'
    text = text .. _M.output_by_datetime()

    ...
end

function _M.output_by_datetime()
    return _M.segment_datetime
end

function _M.set_datetime()
    ...

    _M.segment_datetime = date_text .. '  ' .. time_text
end

And a few enhancement in pipehandler.lua.

function _M.handle_command_event(monitor, event)
    ...

    if origin == 'reload' then
    ...
    elseif origin == 'interval' then
        output.set_datetime()
    end
end

function _M.content_init(monitor, pipe_lemon_out)
    ...
    output.set_windowtitle('')
    output.set_datetime()

    ...
end

Expanding The Event Controller

All we need to do is to split out content_walk into

  • content_walk: combined event, with the help of posix.pipe().

  • content_event_idle: HerbstluftWM idle event. Forked, as background processing.

  • content_event_interval : Custom date time event. Forked, as background processing.

function _M.content_event_idle(pipe_cat_out)
    local pid_idle = posix.fork()

    if pid_idle == 0 then -- this is the child process
        -- start a pipe
        command_in = 'herbstclient --idle'
        local pipe_in  = assert(io.popen(command_in,  'r'))
  
        -- wait for each event 
        for event in pipe_in:lines() do
            posix.write(pipe_cat_out, event)
            io.flush()
        end -- for loop
   
        pipe_in:close()
    else             -- this is the parent process
        -- nothing
    end
end
function _M.content_event_interval(pipe_cat_out) 
    local pid_interval = posix.fork()

    if pid_interval == 0 then -- this is the child process
        while true do
            posix.write(pipe_cat_out, "interval\n")
            io.flush() 

            _M.os_sleep(1)
        end
    else             -- this is the parent process
        -- nothing
    end
end
function _M.content_walk(monitor, pipe_lemon_out)  
    rd, wr = posix.pipe()

    _M.content_event_idle(wr)
    _M.content_event_interval(wr)

    local bufsize = 4096
    local event = ''

    while true do
        -- wait for next event, trim newline
        event = common.trim1(posix.read(rd, bufsize))
        if event == nil or #event == 0 then break end
    
        _M.handle_command_event(monitor, event)    
    
        text = output.get_statusbar_text(monitor)
        pipe_lemon_out:write(text .. "\n")
        pipe_lemon_out:flush()
    end -- not using for loop

    posix.close(rd)
    posix.close(wr)
end

This above is the most complex part. We are almost done.

View Source File:

Combined event consist of both, synchronous interval event and asynchronous idle event.


Dual Bar

The idea of this article comes from the fact that herbsclient --idle is asynchronous event. If you need another bar, just simply use Conky instead.

  • Dzen2: HerbstluftWM: Dzen2 Conky

  • Lemonbar: HerbstluftWM: Lemonbar Conky

We only need one function to do this in pipehandler.pm.

function _M.detach_lemon_conky(parameters)
    local pid_conky = posix.fork()

    if pid_conky == 0 then -- this is the child process
        local cmd_out  = 'lemonbar ' .. parameters
        local pipe_out = assert(io.popen(cmd_out, 'w'))

        local dirname  = debug.getinfo(1).source:match("@?(.*/)")
        local path     = dirname .. "../conky"
        local cmd_in   = 'conky -c ' .. path .. '/conky.lua'
        local pipe_in  = assert(io.popen(cmd_in,  'r'))

        for line in pipe_in:lines() do
            pipe_out:write(line.."\n")
            pipe_out:flush()
        end -- for loop
   
        pipe_in:close()    
        pipe_out:close()
    else                   -- this is the parent process
        -- nothing
    end
end

And execute the function main script in panel.pl.

#!/usr/bin/lua

local dirname  = debug.getinfo(1).source:match("@?(.*/)")
package.path   = package.path .. ';' .. dirname .. '?.lua;'
  
local helper      = require('.helper')
local pipehandler = require('.pipehandler')

-- main

local panel_height = 24
local monitor = helper.get_monitor(arg)

os.execute('pkill lemonbar')
os.execute('herbstclient pad ' .. monitor .. ' ' 
    .. panel_height .. ' 0 ' .. panel_height .. ' 0')

-- run process in the background

local params_top = helper.get_params_top(monitor, panel_height)
pipehandler.detach_lemon(monitor, params_top)

local params_bottom = helper.get_params_bottom(monitor, panel_height)
pipehandler.detach_lemon_conky(params_bottom)

View Source File:

Dual Bar, detach_lemon_conky function.


Avoid Zombie Apocalypse

Zombie are scary, and fork does have a tendecy to become a zombie. Application that utilize several forks should be aware of this threat. The reason why I use fork instead of thread is, because the original herbstluftwm configuration coming from bash, and this bash script is using fork.

However, you can use this short script to reduce zombie population. It won’t kill all zombie, but works for most case. You might still need htop, and kill -9 manually.

function _M.kill_zombie()
    os.execute('pkill -x dzen2')
    os.execute('pkill -x lemonbar')
    os.execute('pkill -x cat')
    os.execute('pkill conky')
    os.execute('pkill herbstclient')
end

Putting Them All Together

I also created compact for version, for use with main HerbstluftWM configuration, in ~/.config/herbstluftwm/ directory. After reunification, they are not very long scripts after all.


Desktop Screenshot

Fullscreen, Dual Panel, Zero Gap.

HerbstluftWM: Screenshot Dual Panel


Enjoy the statusbar ! Enjoy the window manager !