Sunday, April 07, 2013

Simple computer program for one year olds

Kids love to use the same things that their parents are using. Rather than buying them toy versions of objects, we use these opportunities to teach them the correct way to use everyday objects.

My son loves to see us use the computer, and wants to use a computer too. So we bought a real adult keyboard at an electronic store, and attached it to a real computer running Linux. The only thing he can do is hit a key and see the computer's reaction.  In most programs, this produces no visible result.

So I wrote a very simple program in Python using Gtk to display a single character from the keyboard in a huge font. This is what the computer looks like when it is running this program:


Lots of advantages to this approach:
  1. The child uses a "real" keyboard and a real computer, something that parents use too.
  2. There is no way to exit, except to Alt-Tab to switch programs.
  3. The child can be rough with the spare keyboard, you just buy a new one.
  4. The computer can be disconnected from the Internet, and put on a spare child account if required.
  5. The program should work on Windows and Mac as well, after you set up Python + Gtk.
The entire program is listed here:
#!/usr/bin/python

import gtk, string, pango

class BigChar():
    """ Create a Gtk window for a single giant textview that accepts all keyboard input. """
    def on_key_press(self, widget, data=None):
        """ Intercept all keypress events and show ascii
            characters. This requires the CAPS_LOCK to be off.  We
            don't intercept CAPS NUM or SCROLL lock, probably
            should."""
        ascii_value = data.keyval
        if (ascii_value >= 97 and ascii_value <= 122):
            self.textBuffer.set_text(string.ascii_uppercase[ascii_value-97])
            start = self.textBuffer.get_start_iter()
            end = self.textBuffer.get_end_iter()
            self.textBuffer.apply_tag_by_name("real_big", start, end)

    def __init__(self):
        """ Create a window with a single giant text view. Disables all chrome.
        """
        self.w = gtk.Window(gtk.WINDOW_TOPLEVEL)
        # No border
        self.w.set_border_width(0)
        self.w.realize()
        # Take over the entire screen
        self.w.fullscreen()

        # Connect the callback on_key_press to the signal key_press.
        self.w.connect("key_press_event", self.on_key_press)
        # Make the widget aware of the signal to catch.
        self.w.set_events(gtk.gdk.KEY_PRESS_MASK)

        # Add a text view to show the key pressed
        self.textView = gtk.TextView()
        # Disable a cursor in the text view.
        self.textView.set_editable(False)
        self.textView.set_can_focus(False)
        # Show the single character in the middle
        self.textView.set_justification(gtk.JUSTIFY_CENTER)
        # This is the place we will write the character to
        self.textBuffer = self.textView.get_buffer()
        # Make the text view huge, blue on white
        fontdesc = pango.FontDescription("monospace 512")
        self.textView.modify_font(fontdesc)
        tag = self.textBuffer.create_tag("real_big", background="white", foreground="red")

        # Make the text view take the entire window
        self.hbox = gtk.HBox(homogeneous=False, spacing=0)
        self.hbox.pack_start(self.textView, expand=True, fill=True)
        self.w.add(self.hbox)

    def show(self):
        """ Show the window"""
        self.w.show_all()


if __name__ == '__main__':
    # Create a bigchar window, and show it.
    bigchar = BigChar()
    bigchar.show()
    gtk.main()



Tuesday, March 19, 2013

Sound Sleep: Free application for Android

Frustrated by existing sleep-time applications, I wrote a simple application to play music on an Android phone. The application is called Sound Sleep and it is available for free on the Play Store.

To use the application, create a subdirectory called "sleeping" under the "music" directory in the SD-card or external storage. Put night-time sleep music in this subdirectory. Many music file formats (mp3, ogg, ...) are supported. All directory names are case insensitive.

Start the application. The top half of the screen starts and stops night-time music.

The bottom half starts/stops white noise.


Since the application allows tapping anywhere, it is perfect for clumsy night-time use. It works on all Android devices starting with version 1.5, so give it a try!


Privacy policy

Soundsleep collects no data about you. I don't maintain any crash logs, any usage information, nothing. The only information I get is the total number of installs on Android devices through the Play Store. I do nothing with this information either.

 It doesn't serve any ads, doesn't report anything to any server. I don't maintain a backend stack for this.


The entire source code is available if you want to look at it, or compile it yourself. You can compile and install the software on devices that have no network connectivity.

Monday, February 25, 2013

Adding photography grid lines in GIMP

In photography, the "Rule of thirds" suggests places for optimal visual interest. You divide the photo into nine equal parts, like a tic-tac-toe board. The rule says that the most important visual elements must be at the dividing lines, or along the lines of the tic-tac-toe. This is an easy rule, and helps to determine how best to crop an image, or to judge a composition.

GIMP, the free image editor, allows the user to create guide lines. These are lines shown for reference while editing an image. They do not modify the underlying image, and can be dragged out from the ruler or created using a menu item. Gimp also allows certain edits to stick to guide lines. This is useful if you are adding text, or adding layers as it makes it easy to align visual elements in an appealing manner.

I find it helpful to create rule of thirds guide lines to evaluate photographs. Rather than manually drag out guide lines, I have written a GIMP script to automatically create such rule-of-thirds guide lines. This is what the result looks like.


To use, download the rule-of-thirds script and copy it to your local scripts directory. On my machine, this is $HOME/.gimp-2.6/scripts. The exact location depends on your platform (Windows/Linux/Mac) and Gimp version. You can find out the exact location by going to [Menu] -> Edit -> Preferences -> Folders -> Scripts.

Now start gimp and navigate to [Menu] -> Filters -> Script-Fu -> Refresh scripts.

Once it is refreshed, the rule of thirds guide lines should be available under [Menu] -> Images -> Guides -> Photography.


Monday, February 11, 2013

Android framework debugging through IntelliJ

I had blogged earlier about using the Android Open Source Project (AOSP) to learn about the Android framework, and help debug your Android applications.

I missed out how easy it is to do this through IntelliJ, the other popular IDE.

IntelliJ is an IDE that was released in 2001, and has boasted an impressive feature set. It started out as a paid product and a community edition was released in 2009, along with source code licensed under the Apache License 2.0. A commercial version is still sold, and that includes enterprise support. For an Android developer's perspective, the community edition is a great product to use for all Android development. This post shows how to get set up and start debugging your project with full cross-references into the AOSP framework code.  This is a great way to learn the intricacies of the framework.

Installing IntelliJ IDEA


  1. Download IntelliJ IDEA community edition for your platform. Linux, Mac and Windows versions are available. At the time of writing this post, version 12 was the latest.
  2. Install it according to the instructions for your platform.

Set up JDK

Android development needs a Java Development Kit installed on the device. I choose to use Sun's Java 1.6, but you are free to use any JDK of your choice.
Configure -> Settings -> Project
It will say "No SDK". Click on New and select the path to your jdk. This is probably in /usr/local/sun-java-1.6, or somewhere else.


Set Android SDK

You should also have the Android SDK downloaded. If you need to download the SDK, notice that you need just the SDK for other IDEs, not the entire ADT. Say you unzip it into /usr/local/android-sdk-linux:
export ANDROID_SDK=/usr/local/android-sdk/linux

Create a new project on the previous screen.


On the following screen, create an "Android Application Module" and set the location of the Android SDK:

The project name doesn't much matter. You could create a Hello World project for the purpose of this guide. After clicking no "New", you need to set it to the path of the Android sdk, which is the location where you expanded the Android SDK zip file: ${ANDROID_SDK}.  You can change this setting later under  Menu bar -> File -> Other Settings -> Default Project Settings -> Platform Settings SDKs -> Project Structure.
This can also be set on a per-project basis. However, you should never need to change the SDK location. Instead, you can change the Build Target to the version of Android you wish to support. A single SDK location can hold multiple build targets (Starting from the earliest version of Android all the way to the latest.
At the end of this, you should have a Hello World Android project. IntelliJ supports looking up code sources if you have downloaded the sources with the SDK. To verify, run ${ANDROID_SDK}/tools/android
Select the sources for the Android build targets you need.

Debug with framework source

At this point, you are ready to debug using the framework source. Highlight any framework code (like Activity, or Context) and hit Ctrl+B. It will take you to the source for that class. Sometimes documentation can be vague, and the definitive word is the source. You can also use the source to learn how canonical classes like ListView or DialogFragment are written. Looking at framework code is a very powerful way of learning good coding practices and system paradigms.

Happy hacking!

Monday, October 22, 2012

Expert C Programming: Deep C Secrets

I read a friend's copy of "Expert C Programming" many years ago, and ended up buying a copy for later reference. I didn't quite remember why I would purchase a book I had read already. Recently, I cracked open my copy for the first time: it still had the new book smell.

Oh, now I remember.

This is the most enjoyable programming book I have ever read.

The book is about corner cases and implementation-quirks of C, with a smattering of C++ thrown in. The entire book is divided into themes, and each theme is self-contained in a chapter. Each chapter talks about a quirk of the language, something that good C programmers should be aware of.  For example, one chapter talks about the differences between Kernighan&Ritchie C and ANSI C. Each idea is crisply presented, with source code and clear explanation. The chapters are littered with relevant anecdotes, historical background, and tantalizing puzzles.

Programming books can be dry and just about the facts. Recent technologies usually come with books that focus on how to get things done. While this is useful, it does not improve the appreciation of the technology. Expert C Programming was written 20 years after the development of the language. Perhaps time leads to some clarity and a light-hearted view of things.

Programming is more than just a profession: it is a creative process. It helps to have such books in your shelf: so you can them pick up and remind yourself how fun computing can be.


(Image courtesy: Amazon)

Wednesday, September 19, 2012

Android debugging using the framework source

When writing Android apps, it is helpful to be able to read the implementation of the framework to clarify a point.  This might be when the documentation is incomplete, or if you want to learn from canonical classes like ListView.

Nexus devices contain this framework code unmodified. This allows you to trace your application flow down to the framework level, either to learn how the platform works or to find a bug. Today, the cheapest Nexus device is $199, so having an additional Nexus device is an excellent tool for Android developers, even if you do most of your development for non-Nexus devices.

It is easy to get the source code from the Android Open Source Project (AOSP). You need the following:
  1. A good Internet connection. The full AOSP tree is well over 8 gigabytes of data. If you have more than one Android developer, you could download the tree for a single developer, and then mirror it locally.
  2. A fast computer. AOSP is a lot of code and Eclipse chews a lot of CPU and RAM with large projects. A computer with two CPUs and about 4GB of RAM should do perfectly, you might get away with lesser RAM.
  3. Disk space. If you choose to build the code, you're look at 30 gigabytes of disk space.
  4. Eclipse, some recent version and Sun's Java 1.6.
  5. Linux or Mac. The instructions work for Ubuntu 10.04/11.10/12.04 and some Mac version.

Here are all the steps:
  1. Set up your computer: This can be done on all developer computers simultaneously. This will install all the development tools. At the end of this, you have all the tools but no AOSP code.
  2. Download all the AOSP source: This uses your internet connection to download all the source. The AOSP source has everything going back to the earliest releases of Android. You get all source history, the framework, the open source applications, the kernel, all open drivers, everything. There are instructions on that page to set up a local mirror. Follow those steps to download the source once and then share it over your local network. This conserves bandwidth, and saves time. You might want to start this download over a weekend, depending on your network connection and other users' needs. I will assume that you are putting the source in /usr/local/aosp.
  3. Build the source. Here, you have two options. You could follow the AOSP instructions. However, if you just want to include the source in an eclipse project, those instructions are overkill. You can get a much smaller project if you follow these alternate instructions. If you have trouble with java versions, read the bottom of this post.
    $ cd /usr/local/aosp
    $ source build/envsetup.sh
    $ lunch full-eng
    $ # The following step takes time. -j<num jobs> increases parallelism.
    $ make -k -j2 sdk
    
  4. Create the Eclipse classpath. By default, we can create a project with all the Android source code. This is beneficial if you want to have access to all the AOSP code for reference. If you want just the framework, you can reduce the size of the project significantly. To do this, first create a file in the directory containing the following:
    $ cd /usr/local/aosp
    $ cat excluded-paths 
    ^external/.*
    ^packages/.*
    ^cts/.*
    ^dalvik/.*
    ^development/.*
    ^prebuilts/.*
    ^out/.*
    ^tools/.*
    ^sdk/.*
    ^libcore/.*
    ^gdk/.*
    ^hardware/.*
    ^device/.*
    
    This file allows you to reduce the size of the Eclipse project, which improves Eclipse's performance significantly. Now, we can generate the Eclipse classpath as follows:
    $ cd /usr/local/aosp
    $ ./development/tools/idegen/idegen.sh 
    Read excludes: 3ms
    Traversed tree: 781ms
    $ ls -l .classpath
    -rw-rw-r-- 1 user group 16938 Sep 18 21:50 .classpath
    
  5. Create the project in Eclipse. First you need to start Eclipse with increased heap size and virtual memory:
    $ eclipse -vmargs -Xms128m -Xmx512m -XX:MaxPermSize=256m
    
    Now, create a new Eclipse project (File -> New Java Project -> Next). In the dialog, under the "Libraries" tab, click the "Add Library" button -> Add System Library -> Add JRE system library. This will help resolve the references to core libraries like Integer and String. Adding the system library is not required, but it reduces the number of syntax error Eclipse finds with the framework. Click "Finish" when done.
  6. Done! Try your setup by searching (Ctrl-Shift-T) for FragmentManager. You should be able to see its source code, and navigate through its code. Some handy commands are: Ctrl-Shift-G to look for references of a class, and F3 to look for a method's implementation.

JDK version pain: You might encounter a problem with JDK versions. You need Sun Java 1.6 to compile the AOSP source code, while your Eclipse setup might require a different version (OpenJDK?). One solution is to use sun-java only to compile the AOSP, and switch back to the previous version after the compilation has finished. On Ubuntu, this is done with the commands shown below. Select the number that corresponds to sun-java before the compilation, and run these commands after running idegen.sh to switch back to your previous version of jdk.
$ sudo update-alternatives --config javac
There are 2 choices for the alternative javac (providing /usr/bin/javac).

  Selection    Path                                         Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-6-openjdk-amd64/bin/javac   1061      auto mode
  1            /usr/lib/jvm/java-6-openjdk-amd64/bin/javac   1061      manual mode
* 2            /usr/local/sun-java-1.6/jdk/bin/javac         1         manual mode

Press enter to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/lib/jvm/java-6-openjdk-amd64/bin/javac to provide /usr/bin/javac (javac) in manual mode.
$ sudo update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java   1061      auto mode
  1            /usr/lib/jvm/java-6-openjdk-amd64/jre/bin/java   1061      manual mode
* 2            /usr/local/sun-java-1.6/jdk/bin/java             1         manual mode

Press enter to keep the current choice[*], or type selection number: 2