Table of Content

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

Tutorial/ Guidance/ Article:

[ Tag Status Overview ]  [ BASH ]  [ Perl ]  [ Python ]  [ Ruby ]  [ PHP ]  [ Lua ]  [ Haskell ] [ Global Notes ]

Example Using Dzen2:

[ BASH ]  [ Perl ]  [ Python ]  [ Ruby ]  [ PHP ]  [ Lua ]  [ Haskell ]

Example Using Lemonbar:

[ BASH ]  [ Perl ]  [ Python ]  [ Ruby ]  [ PHP ]  [ Lua ]  [ Haskell ]

Preface

Goal: Show the Herbstclient Tag.

Focusing in "herbstclient tag_status". 

HerbstluftWM: Tag Status

This tutorial cover Lemonbar, and in order to use Dzen2, any reader could use the source code in github.

Table of Content


Reference

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.


Screenshot

Since window manager is out of topic in this tutorial, I present only panel HerbstluftWM screenshot.

Dzen2

Statusbar: Dzen2 Screenshot

Lemonbar

Statusbar: Lemonbar Screenshot


1: Directory Structure

Directory Structure has been explained in preface. For both Dzen2 and Lemonbar, the structure are the same. This figure will explain how it looks in Python script directory.

Statusbar: Directory Structure

Special customization can be done in output script, without changing the whole stuff.


2: Get Geometry

Let’s have a look at helper.py in github.

View Source File:

Similar Code

Dzen2 Example:

[ BASH Helper ]  [ Perl Helper ]  [ Python Helper ]  [ Ruby Helper ]  [ PHP Helper ]  [ Lua Helper ]  [ Haskell Helper ]

Lemonbar Example:

[ BASH Helper ]  [ Perl Helper ]  [ Python Helper ]  [ Ruby Helper ]  [ PHP Helper ]  [ Lua Helper ]  [ Haskell Helper ]

Get Script Argument

The original herbstluftwm panel example, contain statusbar for each monitor. The default is using monitor 0, although you can use other monitor as well.

$ ./panel.py 0

I do not implement statusbar in multi monitor since I only have my notebook. But I’ll pass the argument anyway for learning purpose. Here it is our code in Python.

helper.py

# script arguments
def get_monitor(arguments):
    # ternary operator
    monitor = int(arguments[1]) if (len(arguments) > 1) else 0

    return monitor

And in main code we can call

import sys
import helper

monitor  = helper.get_monitor(sys.argv)
print(monitor)

This will display 0 or else such as 1, depend on the script argument given.

0

Get Monitor Geometry

HerbstluftWM give this little tools to manage monitor geometry by getting monitor rectangle.

$ herbstclient monitor_rect

This will show something similar to this.

0 0 1280 800

HerbstluftWM: Monitor Rectangle

Consider wrap the code into function. And get an array as function return.

helper.py

def get_geometry(monitor):
    raw = os.popen('herbstclient monitor_rect '+ str(monitor)).read()

    if not raw: 
        print('Invalid monitor ' + str(monitor))
        exit(1)
    
    geometry = raw.rstrip().split(' ')
    
    return geometry

Consider call this function from script later. To print array in Python, we just have to wrap it in ' '.join(geometry).

monitor  = helper.get_monitor(sys.argv)
geometry = helper.get_geometry(monitor)
print(' '.join(geometry))

This will produce

0 0 1280 800

Get Panel Geometry

The Panel geometry is completely depend on the user flavor and taste. You can put it, on top, or bottom, or hanging somewhere. You can create gap on both left and right.

Consider this example: helper.py

def get_bottom_panel_geometry(height, geometry):
    # geometry has the format X Y W H
    return (int(geometry[0]) + 24, int(geometry[3])-height, 
            int(geometry[2]) - 48, height )

We are going to use this X Y W H, to get lemonbar parameter.

panel_height = 24
monitor  = helper.get_monitor(sys.argv)
geometry = helper.get_geometry(monitor)
xpos, ypos, width, height = helper.get_bottom_panel_geometry(
       panel_height, geometry)

print('Lemonbar geometry: ' + 
    str(width)+'x'+str(height)+'+'+str(xpos)+'+'+str(ypos) )

This will show something similar to this result, depend on your monitor size.

Lemonbar geometry: 1280x24+24+776

Get Lemonbar Parameters

We almost done. This is the last step. We wrap it all inside this function below.

helper.py

def get_lemon_parameters(monitor, panel_height):  
    # calculate geometry
    geometry = get_geometry(monitor)
    xpos, ypos, width, height = get_top_panel_geometry(
       panel_height, geometry)

    # geometry: -g widthxheight+x+y
    geom_res = str(width)+'x'+str(height)+'+'+str(xpos)+'+'+str(ypos)

    # color, with transparency    
    bgcolor = "'#aa000000'"
    fgcolor = "'#ffffff'"
    
    # XFT: require lemonbar_xft_git 
    font_takaop  = "takaopgothic-9"
    font_bottom  = "monospace-9"
    font_symbol  = "PowerlineSymbols-11"
    font_awesome = "FontAwesome-9"

    # finally
    parameters  = ' -g '+geom_res+' -u 2 ' \
                + ' -B '+bgcolor+' -F '+fgcolor \
                + ' -f '+font_takaop+' -f '+font_awesome+' -f '+font_symbol

    return parameters

3: Testing The Parameters

Consider this code 01-testparams.py. The script call the above function to get lemon parameters.

#!/usr/bin/env python3

import os
import sys
import helper

# initialize
panel_height = 24
monitor = helper.get_monitor(sys.argv)

lemon_parameters = helper.get_lemon_parameters(monitor, panel_height)
print(lemon_parameters)

This will produce output something similar to this result

-g 1280x24+0+0 -u 2  -B '#aa000000' -F '#ffffff' 
-f takaopgothic-9 -f FontAwesome-9 -f PowerlineSymbols-11

Or in Dzen2 version:

-x 0 -y 0 -w 1280 -h 24 -ta l 
-bg '#000000' -fg '#ffffff' -title-name dzentop 
-fn '-*-takaopgothic-medium-*-*-*-12-*-*-*-*-*-*-*'

View Source File:


4: Adjusting the Desktop

Since we want to use panel, we have to adjust the desktop gap, giving space at the top and bottom.

$ herbstclient pad 0 24 0 24 0

For more information, do $ man herbsluftclient, and type \pad to search what it means.

In script, it looks like this below.

os.system('herbstclient pad ' + str(monitor) + ' ' 
    + str(panel_height) + ' 0 ' + str(panel_height) + ' 0'

5: Color Schemes

Using a simple data structure key-value pairs, we have access to google material color for use with dzen2 or lemonbar. Having a nice pallete to work with, makes our panel more fun.

gmc.py

color = {
    'white' : '#ffffff', 
    'black' : '#000000',

    'grey50'      : '#fafafa',
    'grey100'     : '#f5f5f5'
}

View Source File:

Similar Code

Dzen2 Example:

[ BASH Color ]  [ Perl Color ]  [ Python Color ]  [ Ruby Color ]  [ PHP Color ]  [ Lua Color ]  [ Haskell Color ]

Lemonbar Example:

[ BASH Color ]  [ Perl Color ]  [ Python Color ]  [ Ruby Color ]  [ PHP Color ]  [ Lua Color ]  [ Haskell Color ]

6: Preparing Output

Let’s have a look at output.py in github.

View Source File:

Similar Code

Dzen2 Example:

[ BASH Output ]  [ Perl Output ]  [ Python Output ]  [ Ruby Output ]  [ PHP Output ]  [ Lua Output ]  [ Haskell Output ]

Lemonbar Example:

[ BASH Output ]  [ Perl Output ]  [ Python Output ]  [ Ruby Output ]  [ PHP Output ]  [ Lua Output ]  [ Haskell Output ]

7: Global Variable and Constant

Officialy there is a no way to define constant in Python. Python does not differ between these two, for that reason we distinguish global constant with capital case.

Mutable State: Segment Variable

The different between interval based and event based is that, with interval based all panel segment are recalculated, while with event based only recalculate the trigerred segment.

In this case, we only have two segment in panel.

  • Tag

  • Title

output.py In script, we initialize the variable as below

segment_windowtitle = '' # empty string
tags_status = []         # empty list

Each segment buffered. And will be called while rendering the panel.

Global Constant: Tag Name

Assuming that herbstclient tag status only consist of nine number element.

$ herbstclient tag_status
	#1	:2	:3	:4	:5	.6	.7	.8	.9	

We can manage custom tag names, consist of nine string element. We can also freely using unicode string instead of plain one.

output.py

TAG_SHOWS = ['一 ichi', '二 ni', '三 san', '四 shi', 
    '五 go', '六 roku', '七 shichi', '八 hachi', '九 kyū', '十 jū']

Global Constant: Decoration

output.py Decoration consist lemonbar formatting tag.

from gmc import color

# decoration
SEPARATOR = '%{B-}%{F' + color['yellow500'] + '}|%{B-}%{F-}'

# Powerline Symbol
RIGHT_HARD_ARROW = ""
RIGHT_SOFT_ARROW = ""
LEFT_HARD_ARROW  = ""
LEFT_SOFT_ARROW  = ""

# theme
PRE_ICON    = '%{F' + color['yellow500'] + '}'
POST_ICON   = '%{F-}'

8: Segment Variable

As response to herbstclient event idle, these two function set the state of segment variable.

output.py

def set_tag_value(monitor):
    global tags_status

    raw = os.popen('herbstclient tag_status ' + str(monitor)).read()
    raw = raw.strip()
    tags_status = raw.split("\t")

This function above turn the tag status string into array of tags for later use.

output.py

def set_windowtitle(windowtitle):
    global segment_windowtitle
    icon = PRE_ICON + '' + POST_ICON

    segment_windowtitle = ' ' + icon + \
        ' %{B-}%{F' + color['grey700'] + '} ' + windowtitle

We will call these two functions later.


9: Decorating: Window Title

This is self explanatory. I put separator, just in case you want to add other segment. And then returning string as result.

output.py

def output_by_title():
    text = segment_windowtitle + ' ' + SEPARATOR + '  '

    return text

10: Decorating: Tag Status

This transform each plain tag such as .2, to decorated tag names such as 二 ni. Note that it only process one tag. We process all tags in a loop in other function.

This has some parts:

  • Pre Text: Color setting for Main Text (Background, Foreground, Underline). Arrow before the text, only for active tag.

  • Main Text: Tag Name by number, each with their tag state #, +, ., |, !, and each tag has clickable area setting.

  • Post Text: Arrow after the text, only for active tag.

  • Color Reset: %{B-}, %{F-}, %{-u} (Background, Foreground, Underline).

output.py

def output_by_tag(monitor, tag_status):
    tag_index  = tag_status[1:2]
    tag_mark   = tag_status[0:1]
    tag_name   = TAG_SHOWS[int(tag_index) - 1] # zero based

    # ----- pre tag

    if tag_mark == '#':
        text_pre = '%{B' + color['blue500'] + '}' \
                   '%{F' + color['black'] + '}' \
                   '%{U' + color['white'] + '}%{+u}' \
                 + RIGHT_HARD_ARROW \
                 + '%{B' + color['blue500'] + '}' \
                   '%{F' + color['white'] + '}' \
                   '%{U' + color['white'] + '}%{+u}'
    elif tag_mark == '+':
        text_pre = '%{B' + color['yellow500'] + '}' \
                   '%{F' + color['grey400'] + '}'
    elif tag_mark == ':':
        text_pre = '%{B-}%{F' + color['white'] + '}' \
                   '%{U' + color['red500'] + '}%{+u}'
    elif tag_mark == '!':
        text_pre = '%{B' + color['red500'] + '}' \
                   '%{F' + color['white'] + '}' \
                   '%{U' + color['white'] + '}%{+u}'
    else:
        text_pre = '%{B-}%{F' + color['grey600'] + '}%{-u}'

    # ----- tag by number
    
    # clickable tags
    text_name = '%{A:herbstclient focus_monitor "' \
              + str(monitor) + '" && ' + 'herbstclient use "' \
              + tag_index + '":} ' + tag_name + ' %{A} '

    # non clickable tags
    # text_name = ' ' + tag_name + ' '
    
    # ----- post tag

    if tag_mark == '#':
        text_post = '%{B-}' \
                    '%{F' + color['blue500'] + '}' \
                    '%{U' + color['red500'] + '}%{+u}' \
                  + RIGHT_HARD_ARROW
    else: 
        text_post = ''
    
    text_clear = '%{B-}%{F-}%{-u}';
     
    return (text_pre + text_name + text_post + text_clear)

11: Combine The Segments

Now it is time to combine all segments to compose one panel. Lemonbar is using %{l} to align left segment, and %{r} to align right segment. All tags processed in a loop.

output.py

def get_statusbar_text(monitor):
    text = ''

    # draw tags
    text += '%{l}'
    for tag_status in tags_status:
        text += output_by_tag(monitor, tag_status)
    
    # draw window title    
    text += '%{r}'
    text += output_by_title()
    
    return text

12: Testing The Output

Consider this code 02-testoutput.py. The script using pipe as feed to lemonbar.

We append -p parameter to make the panel persistent.

#!/usr/bin/env python3

import os
import sys
import helper

# process handler
def test_lemon(monitor, parameters): 
    import subprocess
    import output
 
    command_out  = 'lemonbar ' + parameters + ' -p'

    pipe_out = subprocess.Popen(
            [command_out], 
            stdin  = subprocess.PIPE,
            shell  = True,
            universal_newlines=True
        )

    # initialize statusbar
    output.set_tag_value(monitor)
    output.set_windowtitle('test')
        
    text = output.get_statusbar_text(monitor)
    pipe_out.stdin.write(text + '\n')
    pipe_out.stdin.flush()

    pipe_out.stdin.close()

# initialize
panel_height = 24
monitor = helper.get_monitor(sys.argv)
lemon_parameters = helper.get_lemon_parameters(monitor, panel_height)

# test
os.system('herbstclient pad ' + str(monitor) + ' ' 
    + str(panel_height) + ' 0 ' + str(panel_height) + ' 0')

test_lemon(monitor, lemon_parameters)

This will produce a panel on top.

Statusbar: Lemonbar Screenshot

The panel only contain the initialized version of the text. It does not really interact with the HerbstluftWM event.

You can also click the clickable area to see it’s result. It only show text, not executed yet.

herbstclient focus_monitor "0" && herbstclient use "2"
herbstclient focus_monitor "0" && herbstclient use "3"

View Source File:

Similar Code

Dzen2 Example:

[ BASH Output ]  [ Perl Output ]  [ Python Output ]  [ Ruby Output ]  [ PHP Output ]  [ Lua Output ]  [ Haskell Output ]

Lemonbar Example:

[ BASH Output ]  [ Perl Output ]  [ Python Output ]  [ Ruby Output ]  [ PHP Output ]  [ Lua Output ]  [ Haskell Output ]

Coming up Next

It is already a long tutorial. It is time to take a break for a while.

We are going to continue on next tutorial to cover interaction between the script process and HerbstluftWM idle event.


Enjoy the statusbar !