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.pm 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.pm in github. At the end of the script, we finally call lemonbar with detach_lemon function.

# remove all lemonbar instance
system('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 my $pid = fork.

sub detach_lemon { 
    my $monitor = shift;
    my $parameters = shift;

    my $pid_lemon = fork;
    return if $pid_lemon;     # in the parent process
    
    run_lemon($monitor, $parameters);
    exit; 
}

The real function is run_lemon. Note that we are using IPC::Open2 instead of IO::Pipe, to enable bidirectional pipe later.

sub run_lemon { 
    my $monitor = shift;
    my $parameters = shift;

    my $command_out = "lemonbar $parameters -p";
    my ($rh_lemon_out, $wh_lemon_out);
    my $pid_lemon_out = open2 (
            $rh_lemon_out, $wh_lemon_out, $command_out) 
        or die "can't pipe lemon out: $!";

    content_init($monitor, $wh_lemon_out);
    waitpid( $pid_lemon_out, 0 );
}

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.

sub content_init {
    my $monitor = shift;
    my $pipe_lemon_out = shift;

    output::set_tag_value($monitor);
    output::set_windowtitle('');

    my $text = output::get_statusbar_text($monitor);
    print $pipe_lemon_out $text."\n";
    flush $pipe_lemon_out;
}

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.

sub run_lemon { 
    my $monitor = shift;
    my $parameters = shift;

    my $command_out = "lemonbar $parameters";
    my ($rh_lemon_out, $wh_lemon_out);
    my $pid_lemon_out = open2 (
            $rh_lemon_out, $wh_lemon_out, $command_out) 
        or die "can't pipe lemon out: $!";

    content_init($monitor, $wh_lemon_out);
    content_walk($monitor, $wh_lemon_out); # loop for each event

    waitpid( $pid_lemon_out, 0 );
}

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. IO::Pipe is sufficient for unidirectional pipe.

sub content_walk {
    my $monitor = shift;
    my $pipe_lemon_out = shift; 
    
    # start a pipe
    my $pipe_idle_in = IO::Pipe->new();
    my $command = 'herbstclient --idle';
    my $handle  = $pipe_idle_in->reader($command);

    my $text = '';
    my $event = '';

    # wait for each event, trim newline
    while (chomp($event = <$pipe_idle_in>)) {
        handle_command_event($monitor, $event);
        
        $text = output::get_statusbar_text($monitor);     
        print $pipe_lemon_out $text."\n";
        flush $pipe_lemon_out;
    }
    
    $pipe_idle_in->close();
}

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.

sub handle_command_event {
    my $monitor = shift;
    my $event = shift;
    
    # find out event origin
    my @column = split(/\t/, $event);
    my $origin = $column[0];

    if ($origin eq 'reload') {
        system('pkill lemonbar');
    } elsif ($origin eq 'quit_panel') {
        exit;
    } elsif (  # avoiding the unstable ~~ smartmatch operator
               ($origin eq 'tag_changed') 
            or ($origin eq 'tag_flags')
            or ($origin eq 'tag_added')
            or ($origin eq 'tag_removed')
            ) {
        output::set_tag_value($monitor);
    } elsif (  ($origin eq 'window_title_changed') 
            or ($origin eq 'focus_changed')
            ) {
        my $title = ($#column > 2) ? $column[2] : '';
        output::set_windowtitle($title);
    }    
}

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

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.pm.

    # clickable tags
    my $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.pm.

We need to pipe the lemonbar output to shell. It means Lemonbar read input and write output at the same time.

sub run_lemon { 
    my $monitor = shift;
    my $parameters = shift;

    my $command_out = "lemonbar $parameters";
    my ($rh_lemon_out, $wh_lemon_out);
    my $pid_lemon_out = open2 (
            $rh_lemon_out, $wh_lemon_out, $command_out) 
        or die "can't pipe lemon out: $!";
        
    my ($rh_sh, $wh_sh);
    my $pid_sh = open2 ($rh_sh, $wh_sh, 'sh') 
        or die "can't pipe sh: $!";

    my $pid_content = fork;
    if ($pid_content) {
        # in the parent process
        my $line_clickable = '';
        while($line_clickable = <$rh_lemon_out>) {
            print $wh_sh $line_clickable;
            flush $wh_sh;
        }        
    } else {
        # in the child process
        content_init($monitor, $wh_lemon_out);
        content_walk($monitor, $wh_lemon_out); # loop for each event
    }

    waitpid( $pid_lemon_out, 0 );
    waitpid( $pid_sh, 0 );
}

How does it work ?

Forking solve this issue.

Seriously, we have to take care on where to put the loop, without interfering the original loop in content_walk.

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. Luckily we can treat interval as event.

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.pm.

use Time::Piece;

my $segment_datetime    = ''; # empty string

sub get_statusbar_text {
    ...

    # draw date and time
    $text .= '%{c}';
    $text .= output_by_datetime();
    
    ...
}

sub output_by_datetime {
    return $segment_datetime;
}

sub set_datetime {    ...

    $segment_datetime = "$date_text  $time_text";
}

And a few enhancement in pipehandler.pm.

sub handle_command_event {
    ...

    if ($origin eq 'reload') {
    ...
    } elsif ($origin eq 'interval') {
        output::set_datetime();
    }   
}

sub content_init {
    ...
    output::set_windowtitle('');
    output::set_datetime();

    ...
}

Expanding The Event Controller

All we need to do is to split out content_walk into

  • content_walk: combined event, with the help of cat process.

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

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

sub content_event_idle {
    my $pipe_cat_out = shift;
 
    my $pid_idle = fork;
    return if $pid_idle;     # in the parent process

    # start a pipe
    my $pipe_idle_in = IO::Pipe->new();
    my $command = 'herbstclient --idle';
    my $handle  = $pipe_idle_in->reader($command);

    # wait for each event
    my $event = '';
    while ($event = <$pipe_idle_in>) {
        print $pipe_cat_out $event;
        flush $pipe_cat_out;
    }
    
    $pipe_idle_in->close();
}
sub content_event_interval {
    my $pipe_cat_out = shift;

    my $pid_interval = fork;
    return if $pid_interval;     # in the parent process
    
    while(1) {         
        print $pipe_cat_out "interval\n";
        flush $pipe_cat_out;
        
        sleep 1;
    }
}
sub content_walk {
    my $monitor = shift;
    my $pipe_lemon_out = shift; 

    my ($rh_cat, $wh_cat);
    my $pid_cat = open2 ($rh_cat, $wh_cat, 'cat') 
        or die "can't pipe sh: $!";

    content_event_idle($wh_cat);
    content_event_interval($wh_cat);

    my $text  = '';
    my $event = '';

    # wait for each event, trim newline
    while (chomp($event = <$rh_cat>)) {
        handle_command_event($monitor, $event);
        
        $text = output::get_statusbar_text($monitor);     
        print $pipe_lemon_out $text."\n";
        flush $pipe_lemon_out;
    }

    waitpid( $pid_cat, 0 );
}

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.

sub detach_lemon_conky { 
    my $parameters = shift;

    my $pid_conky = fork;
    return if $pid_conky;     # in the parent process

    my $pipe_out = IO::Pipe->new();
    my $cmd_in   = "lemonbar " . $parameters;
    my $hnd_in   = $pipe_out->writer($cmd_in);

    my $pipe_in  = IO::Pipe->new();
    my $dirname  = dirname(__FILE__);
    my $path     = "$dirname/../conky";       
    my $cmd_out  = "conky -c $path/conky.lua";
    my $hnd_out  = $pipe_in->reader($cmd_out);

    while(<$pipe_in>) {
        print $pipe_out $_;
        flush $pipe_out;
    }

    $pipe_in->close();
    $pipe_out->close();
    exit; 
}

And execute the function main script in panel.pl.

#!/usr/bin/perl

use warnings;
use strict;

use File::Basename;
use lib dirname(__FILE__);

use helper;
use pipehandler;

# main

my $panel_height = 24;
my $monitor = helper::get_monitor(@ARGV);

system('pkill lemonbar');
system("herbstclient pad $monitor $panel_height 0 $panel_height 0");

# run process in the background

my $params_top = helper::get_params_top($monitor, $panel_height);
pipehandler::detach_lemon($monitor, $params_top);

my $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.

sub kill_zombie() {
    system('pkill -x dzen2');
    system('pkill -x lemonbar');
    system('pkill -x cat');
    system('pkill conky');
    system('pkill herbstclient');
}

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 !