Skip to main content

# Is My Terminal Window Active?

I've been working in OSX for almost 3 years now, but I recently switched back to Linux because of all the problems people encountered with Yosemite. There are some things I missed from OSX though. One of which is zsh-notify. It's a zsh plugin that alerts you if your long-running task is complete, and whether it failed or not.

It's pretty convenient when you're compiling something and then go on to browse reddit while waiting. Usually, I spend too much time just reading and forget about the compilation entirely. With the plugin, I get the notification and maybe go back to work.

One nice feature it has is that if you're currently looking at the terminal window of the job that just finished, it won't notify you. It only notifies on windows that aren't currently in focus. To do this, it has to actually talk to Terminal.app or iTerm2 to see if the window and tab are active.

This is alright in OSX since those 2 are the generally most used terminal emulators. On Linux though, everyone has their own favorite terminal. Given that, I figured I could probably rely on talking to X to see if the window is active instead of each single terminal emulator. X can't tell if the tab is active though, but I don't use tabs in my current setup so it should still be good.

### xdotool

Preliminary research reveals that we can easily get what the active window is with xdotool. `xdotool getactivewindow` gives us the X window id of the active one. Now all we need is a way to get the window id of the terminal we're in.

### First Attempt: $WINDOWID

Apparently, xterm and similar terminal emulators define an environment variable called `$WINDOWID` with the window id of the terminal. Obviously, this is too good to be true. In xterm and konsole the `$WINDOWID` was correct, but in VTE-based terminal emulators, `$WINDOWID` had the wrong value. In terminology, it didn't define `$WINDOWID` altogether. So `$WINDOWID` wasn't going to work.

### Second Attempt: xdotool search $MAGIC

My second idea was that you can use zsh to change the window title to a magic number and then just check if the active window is the same one as the window with the magic number. This sort of worked for most terminals, except konsole which does whatever it wants with the window title. There's also the problem of some zsh configs automatically settings the window title to the current command.

In hindsight, I could probably have just done `xdotool search --name xdotool` since in most cases, when you run the search, zsh or konsole will set the window name to the current command. Maybe that's another option I can explore some day.

### Third Attempt: $PPID

My third idea was another environment variable called `$PPID`, which is the process id of the parent of the shell. As it happens, the parent is the window containing the zsh instance. This is actually pretty consistent across most terminals. The only problem was if you launched zsh from another shell since your new zsh's parent will now be another zsh instance instead of an X window.

At first glance, launching zsh within zsh doesn't seem like something most people would do, but this is what happens when you run screen or tmux. To work around this, we can actually just save the original `$PPID` in a different variable and use that instead.

Now that we have the PID of the window from zsh, we can once again use xdotool to get the PID of the current active window with `xdotool getactivewindow getwindowpid`. We just simply compare that with our `$PPID` and we can tell if we're in an active window or not. Overall, this approach worked surprisingly well so that's the final solution I went with.

Posted: 2015-06-07 16:20 | Comments

# Removing PLDTMyDSLBiz from the ZyXEL P-2612HNU

I've always thought that people were just too lazy to change their SSIDs when I see "PLDTMyDSLBizCafeJapan". It became apparent when we got our own PLDT line that it was because the bundled router/modem does not allow you to remove the prefix.

This is not the kind of thing you expect as a business customer. Even for home customers, I feel it's still a bit dishonest. I'd be fine if it was just the default SSID, but forcing people to have it as part of their SSID is like advertising that your company (I mean PLDT) is a douche.

Of course, we couldn't just leave the SSID prefix there, so we tried a number of things to get rid of it. There are articles for removing it from the Prolink H5004N or the ZyXEL P-660HN-T1A but not for the one we got which was the ZyXEL P-2612HNU-F1F.

We did still try the firebug/inspector tricks, but it seems that there is a server-side check that adds in the "PLDTMyDSLBiz". We tried a number of things, but the one that ultimately worked (and we had a good laugh about) was to backup the configuration, edit the dumped file and restore it.

The backup is actually just an XML file. You can search for SSID and change the parameter there. It's a bit annoying because the router has to restart after restoring the configuration, but it works!

A minor note, the router doesn't seem to support SSIDs with a comma (,) well. It just gets everything before the comma as the SSID for some reason.

Posted: 2013-11-27 10:12 | Comments

# Console Keymap Switching

At the office, we have some people who use DVORAK. Normally, this isn't a problem. To each his own after all. It does become a bit problematic though, when we're dealing with the servers around the office.

We normally leave the servers on QWERTY. After all, most people start off as QWERTY typists and migrate to something else. That said, it's apparently difficult to stay fluent in both. People tend to forget how to type in QWERTY once they learn DVORAK or something else. While it is true that they can just look a the keyboard while typing, my coworkers would prefer it to just be in DVORAK.

For the console, they'd typically do `sudo loadkeys dvorak` after logging in. The problem with this is, after they logout, the keymapping is still on DVORAK. This has been quite annoying for a few times since I can't even login to change the keymap. What I wanted was something like you get in the graphical login screens where you can pick your keymap before logging in. Apparently, there isn't a readily available thing for the console.

I googled around for solutions and came across a nice idea. You could alias `asdf` to load the DVORAK mapping and `aoeu` (the equivalent to asdf in DVORAK) to load the QWERTY mapping. This actually makes sense since you don't really have to know where the letters are. The only problem is, you once again have to be logged in to change the key mappings.

After some further searching, I found something close to what I wanted. Apparently, Alt+Up sends a KeyboardSignal keycode to the init process, which can act on that. It also works anywhere, even before being logged in. For SysVinit systems, you can just add a line to your inittab for a command to be run when Alt+Up is pressed.

In the office, however, we generally use Arch Linux which uses SystemD. But apparently, it also has a mechanism of accepting the Alt+Up press. It runs the kbrequest target whenever it gets the keypress. `kbrequest.target` is normally aliased to run the rescue service though, so you have to manually create the file in `/etc/systemd/system/kbrequest.target` and fill it with a description:

    [Unit]
    Description=kbrequest target

We can then add a service to be run whenever the target is called. Something like `/etc/systemd/system/keymap-switch.service`:

    [Unit]
    Description=Keymap Switch Service

    [Service]
    Type=oneshot
    ExecStart=/usr/local/bin/keymap-switch

    [Install]
    WantedBy=kbrequest.target

After enabling said service, we only need the actual keymap switcher, `/usr/local/bin/keymap-switch`. The StackOverflow answer provides different ways of detecting the current keymap so we know which one to switch to. Since we're using SystemD, we can use that instead for managing which keymap we're actually using. It stores the current settings inside `/etc/vconsole.conf`. We can also then switch keymaps by using `localectl set-keymap`.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    #!/bin/sh
    source /etc/vconsole.conf

    if [ "$TERM" = "dumb" ]; then
      if [ "$KEYMAP" = "dvorak" ]; then
        localectl set-keymap us
      else
        localectl set-keymap dvorak
      fi
    fi

After putting it all together, it works! We can switch keymaps on the fly by simply pressing Alt+Up.

Posted: 2013-10-29 20:02 | Comments

# Geocoding Services

A key component for any routing service is being able to do geocoding. Most people who are looking for routes most probably don't know exactly where their start and end points are on the map. Even then, manually looking for a location on a map is a time-consuming task.

The gold standard for doing geocoding right now is Google Maps. It's hard to find a better location search experience. If they actually provided routing for jeeps here in the Philippines, I imagine there wouldn't be that much you could do for the competition.

When the competition started though, I took it as a challenge to avoid Google Maps as much as possible. I wanted to see how much is currently possible with other options such as OpenStreetMap. In fact, OSM does have a geocoding service called Nominatim.

Sadly, for a mapping app, what you want to do is not simply just geocoding. With geocoding, you take an address and turn it into coordinates. When you want to search for a place in a mapping app, you take part of an address, infer the rest of it, and give the user options to choose from.

Given a typical mapping app, you might type in "ateneo" and expect it to give you Ateneo de Manila University. With typical geocoding services like Nominatim or even Google's geocoding API, you probably won't get any result for this. What you want to use is the Places API which provides an autocomplete search box. Using it, when you type in "ateneo", it automatically suggests in the dropdown, "Ateneo de Manila University".

A downside to using the Places API is that it's against the terms of service to use it with something that isn't Google Maps, which means no OpenStreetMap. If there were more time, writing your own autocompletion engine using OpenStreetMap's data will probably be a better long term solution.

For now, since the competition's deadline is just a few days away, I'll be using Google Maps.

Posted: 2013-09-25 12:26 | Comments

# Jeep and Bus Schedules

Wouldn't it be wonderful if there were no buses or jeepneys in the Philippines over the weekends? It would truly be a cyclist's paradise. Imagine biking along EDSA, normally that would be a death sentence, but according to the GTFS data, you shouldn't worry. I can assure you, it's still a death sentence.

The GTFS spec defines 2 ways of statically specifying trip schedules. You can define the exact times that a service will arrive at a stop. You can also specify between what times the service is active and how often a new bus or jeep leaves the first stop. You also define which days those rules apply. You could say every MWF, the bus operates from 9:00AM to 9:00PM and every TTH, the bus services from 3:00AM to 11:00PM.

This should be sufficient in theory, but real world conditions like traffic or the weather could throw the schedules off. To solve this, there's another spec, GTFS-realtime. This allows transit agencies to push temporary schedule updates and service announcements.

Like much everything else about the Philippine transit system, there aren't really any "schedules" to speak of. It's generally whenever the buses or jeeps feel like it. So we have no static schedules. We don't have a central agency or the tracking technology to make it feasible to push updates via GTFS-RT.

Ideally, we shouldn't bother inputting the schedule information into GTFS. Only the route data is really important for jeeps and buses. However, the schedule information is required in the GTFS, and routing apps wouldn't work without it. So we have to add a reasonable trip schedule for jeeps and buses.

The current GTFS data does define these trip schedules. We assume that jeeps and buses operate between 6:00AM and 11:00PM and a new jeep passes by every 10 minutes. Also, jeeps and buses are defined to only operate on weekdays.

While there might be jeeps who change routes or don't operate on weekends, I'm pretty sure that jeeps and buses run on weekends. We'll have to fix it ourselves temporarily since there's no central GTFS feed yet.

    # 724594 seems to be the service id used by jeeps and buses
    sed -i .bak '/^724594/ s/0,0/1,1/' calendar.txt

Another thing we could do is to adjust the time between buses, although the improvement is arguable. With the current 10 minutes between jeeps, it might provide some routes a significant advantage just because the timing is right. So you might get differing route suggestions depending on what time you planned the route. This makes sense when you're sure what the times are, so you can minimize the wait, but with jeeps, you never really know how long the wait will actually be.

If we set the frequency to one minute, it might give better routes by eliminating the timing issue. Or not, it's kind of hard to tell.

    # jeep and bus route ids tend to start with 72
    sed -i .bak '/^72/ s/,600/,60/' frequencies.txt

Overall, the problems we're having is a symptom of the mismatch between our transit system and the GTFS. It would be great if our transit system gets better and we don't need to do hackish things for it to fit the GTFS, but that's still a dream. For now, all we can really do is fit a triangle into a square hole.

Posted: 2013-07-28 16:26 | Comments