The power of simple design

Posted on by Patrick Gotthardt


As most of you will probably know, I’m not exactly the world’s best designer, yet, I’ve recently had the most positive response a designer could recieve.

I accepted a client who wanted a simple WordPress installation and for me to help her pick the right (=cheap yet reliable) hoster. Naturally, I recommended her my long time hoster all-inkl.com and the startup of a friend: mykro.de. I wasn’t biased one way or the other even though I had designed the logo for the friend. After I told her about the options I’d recommend she wanted to take a look at their websites.

If you haven’t looked at it yet, I’d like you to take a look at all-inkl.com now. Their design is highly professional and they provide a lot of details on their website. My client was pleased for those very reasons. However, when I showed her mykro.de, she focused only on one thing: the logo. She looked at it for a couple of seconds and said: “I’ll take that one!”

She made her decision based on the logo I designed and it took her only seconds to decide. There was no “bad” or “wrong” decision to make — both services are most suitable for her needs and the price is comparable — but it was a nice experience to see how a simple design beats a business one.

This really was one of my best professional experiences. I had gained nothing from it (I actually lost a couple of euros provision from all-inkl) but to see the reaction of an actual client of a client is something special. To see them being able to stand up to big competition because of a logo I designed — just awesome.

Posted in Design | Comments Off

PgsAction and Guice — a mix made in heaven

Posted on by Patrick Gotthardt


Close to 100 years ago I published an Open Source library called “PgsAction”. This library was targeted towards Swing developers who used Swings Action class. PgsAction supports to styles of usage. You can extend from the AbstractSystemAction class and gain transparent I18N support or you could use an Annotation-based API where you could specify that a method acts as an Action.

The Annotation-based API was introduced because the Swing Application Framework supported that style of usage. Personally, I hate it. It encourages code duplication, bad API-Design and is a source of frustation because of the use of strings as identifiers for actions. Thus I only use it in small projects or highly encapsulated environments (i.e. actions for a small dialog)

PgsAction thus promoted a different usage style: Each Action is a class, you should use inheritance when possible and Actions are identified through their Class.

In theory using Class-identifiers also enables a loser coupling between the Action and the ActionContainer/Swing component. Sadly I never made the effort to implement something like that. However, when I recently started a new Swing project (a special kind of PDF-Viewer for my new work as a math/english tutor) I really wanted to put some of my newly found wisdom on application design to use. For example I finally understood the concept of MVC-programming (at least I hope that — though I’ll probably understand that I know nothing in a few months again…) and I really appreciate dependency injection and test driven development.

Since I hate XML and wanted a lightweight solution (in this context I define “lightweight” as “something that I can add without having to write a hundred lines of code just to get it going”) I decided to use Google Guice as my dependency injection framework for the application. After I had finished the model– and service-layer part I was absolutly sure that I wanted to use Guice for the UI-layer as well. When I came to the point of having to implement actual actions I didn’t think twice before using PgsAction. Even after all those years and with the total stagnancy of development for PgsAction it still is the library that fits my style best. There was just one problem: I can’t use dependency injection with PgsAction! The ActionManager class that is used to recieve an instance of a concrete Action doesn’t provide any kind of intelligent lookup facility. It just uses reflection to create a new instance of an Action and returns that — making sure that there is exactly one instance of each Action.

While I prefer that to the string-based alternatives, I still saw a great potential in mixing in some Guice into PgsAction. You might really want more than a single instance of an Action, your Action implementation might need some dependencies (in SimpleEdit I used a ServiceLocator-API to handle dependencies) and you might want to test it or use a different implementation of a single Action based on the OS or (product-)license or whatever. Guice is great in all of this and thanks to the ActionManager class it is unbelievably easy for PgsAction to hook up with Guice. Below I’ll provide an ActionManager implementation for Guice and show some examples from my new application.

/*
 * Copyright (c) 2010 Patrick Gotthardt
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.pagosoft.myview.actions;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.pagosoft.action.ActionManager;

import javax.swing.*;

/**
 * A simple class to connect PgsAction with Guice.
 */

public class GuiceActionManager extends ActionManager {
    private Injector injector;

    @Inject
    public GuiceActionManager(Injector injector) {
        this.injector = injector;
    }

    @Override
    public <K> K get(Class<K> kClass) {
        return injector.getInstance(kClass);
    }
}

As you can see we request an instance of the injector and delegate the construction of new Actions to it. This gives you amazing flexibility. You can now provide different implementations of an Action based on some conditions, you can specify whether or not an Action is supposed to be a singleton and most importantly it allows you to use dependency injection in your Action classes!

The next code snippet will show an Action implementation that requires a PrintService (for the actual action) and the EventBus (to adept its state). As you can see this is really just a little bit of code, but its a great way to decouple your classes.

/*
 * Copyright (c) 2010 Patrick Gotthardt. All rights reserved.
 */


package com.pagosoft.myview.actions;

import com.google.inject.Inject;
import com.pagosoft.action.AbstractSystemAction;
import com.pagosoft.eventbus.ApplicationListener;
import com.pagosoft.eventbus.EventBus;
import com.pagosoft.myview.domain.Document;
import com.pagosoft.myview.events.DocumentChangedEvent;
import com.pagosoft.myview.print.DocumentPrintJob;
import com.pagosoft.myview.print.PrintService;

import java.awt.event.ActionEvent;

/**
 * Prints a single document.
 */

public class PrintDocument extends AbstractSystemAction implements ApplicationListener<DocumentChangedEvent> {
    private PrintService ps;
    private Document doc;

    @Inject
    public PrintDocument(EventBus eventBus, PrintService ps) {
        super("print.document");
        this.ps = ps;
        eventBus.add(this, DocumentChangedEvent.class);
        setEnabled(false);
    }

    public void actionPerformed(ActionEvent e) {
        ps.print(new DocumentPrintJob(doc));
    }

    public void handleEvent(DocumentChangedEvent event) {
        doc = event.getSource();
        setEnabled(doc != null);
    }
}

Now all that is left is to create a menubar or toolbar. Usually you should use the ActionContainer class of the PgsAction library, but in this case all I really need is a toolbar so I didn’t use ActionContainer.

public class MyViewToolBar extends JToolBar {
    @Inject
    public MyViewToolBar(ActionManager am, ToolBarUI ui) {
        setUI(ui);

        PopupButton print = new PopupButton(am.get(PrintDocument.class));
        JPopupMenu menu = print.getPopup();
        menu.add(am.get(PrintDocument.class));
        menu.add(am.get(PrintExercise.class));
        menu.addSeparator();
        menu.add(am.get(PrinterSettings.class));
        add(print);

        add(am.get(PreviousDocument.class));
        add(am.get(RandomDocument.class));
        add(am.get(NextDocument.class));
    }
}

As you can see we do not use Guices Injector class but instead rely on ActionManager to produce the actions. This further reduces the coupling between your classes since you could just pass an ActionManager Mock Object instead of the actual one.

While it is absolutly true that the application I wrote has a very basic UI I still think it is worth mentioning that I could easily provide a completely alternative (Swing) UI without having to rewrite anything but the UI layer.

Posted in Java, Pagosoft, Swing | 8 Comments

Using Inkscape on Leopard

Posted on by Patrick Gotthardt


When I recently tried to get Inkscape running on my MacBook it just wouldn’t startup. Well, it was kind enough to tell me that it was now loading the fonts and that this step might take some time, but confirming the dialog just killed it (it disapeared from the dock).

Today I wanted to give it a try again, after noticing I’m not really smart enough to use Gimp. Really, all I want is to draw a simple gradient and it just won’t look right. *sigh*

Anyway, I tried to start it, it failed as usual. As I really need that gradient, I decided to google for a solution and — thank god — I found one.

First step (and I really don’t know if this one is required because Inkscape didn’t work after I applied this “trick”) is to alter the startup script in |/Applications/Inkscape.app/Contents/Resources/script|

Simply replace those lines:

open-x11 /tmp/getdisplay.sh || \
open -a XDarwin /tmp/getdisplay.sh || \

With this one:

open -a X11 /tmp/getdisplay.sh

Now, this didn’t help me, but might be enough to get you started. The second step was to start Inkscape using XTerm from within X11. So fire up your X11 (if you haven’t already) and open XTerm (if it doesn’t open automatically). Within XTerm you can start Inkscape like this:

cd /Applications/Inkscape.app
./Contents/Resources/bin/inkscape

And Inkscape should run (did for me). Now using this method to start it isn’t really cool, right? Good news: You don’t need to. Once you’ve started it this way (you’ll see a couple of error messages in XTerm and it might take a while), you can start it from the dock just like you do with any other application. It starts X11 and shows its windows just like it should have from the start.

Used applications versions: OS X 10.5.4, Inkscape 0.46

This is basicly just a recap (and the note that you won’t need to start it from xterm again if you did that once) to what I’ve found at a thread in the Apfelforum (german).

Posted in OS X | Comments Off

Java 6: Anwendungen programmieren”, featuring me ;)

Posted on by Patrick Gotthardt


Just a quick note: One of my Professors at university, Prof. Dr. Helmut Balzert, has recently published his new book Java 6: Anwendungen programmieren (roughly “Java 6: Application development”). It is, obviously, written in german and I’ve again been asked to function as a reviewer and contribute some feedback. Furthermore I’ve had the honor to contribute a chapter on the development of a custom LayoutManager. Its just 7 pages strong but I think its quite acceptable. To say the truth: I think I’m spending like 3 pages on telling why you shouldn’t use the Null-Layout (from my experience the most common problem with Swing-beginners) and explaining that its actually pretty easy to implement a custom, highly specialized, LayoutManager. If you happen to read it be sure to send me some feedback. ;)

I wouldn’t say it’s the best book on Swing but for german students that’d like to get their feet wet with Swing, I can definitly recommend it. There are nice examples on not only Swing but MVC, automated testing of Swing applications, Databases and so on.

Posted in Java, Swing | Comments Off

Pgs_StringTemplate 1.0 beta 1 released

Posted on by Patrick Gotthardt


In my previous blog entry I introduced Pgs_StringTemplate. Today I’m announcing the first beta release of this project.
It includes:

  • The ST-Compiler
  • An introduction to ST (based on my previous blog entry)
  • The Treebank-website with complete source code (as an example of how to use ST), licensed under terms of the BSD license
  • PgsParser-framework (though this is not formally released yet)

I decided to pick the BSD license for this project, so you can use it for whatever you want. If you need help with it, send me a mail or leave a comment.

Download Pgs_StringTemplate 1.0 beta 1

Posted in Pagosoft, PHP | Comments Off

Introducing Pgs_StringTemplate — yet another PHP template engine

Posted on by Patrick Gotthardt


There has been a lot of discussions about Template-Engines and PHP for years with opinions ranging from “PHP is a great template language on its own!” to “Using PHP for templates feels like shooting birds with a bazooka.”

As for me, I remember having used PHP as a template language years ago and I don’t want to go back to that time. My experience is that given the power of PHP you’re likely to use it. That means sooner or later you’ll find “just one very basic query” in your template and a little later you’re likely to have more business than UI-logic in your templates. But that’s just me and others might have made different experiences. It pretty much comes down to whom you’re working with and how much you can control what they’re doing.

However, looking at the alternatives in the PHP-land you can choose between Smarty, a handful of XML-based engines, XSLT and some that use an HTML-comment like syntax. All of them have some serious shortcomings and advantages over each other and it is very important to think about who is going to edit these templates before you decide what engine to use.

As for XML and XSLT in special, let’s just point out that they’re written in XML which means they’re great when used with a WYSIWYG-tool but fall down pretty hard when some sad human being has to edit them by hand. XML is cool unless you have to write/read it.

Smarty comes with its own share of problems. It’s mostly a subset of PHP, supporting limited invocation of functions, foreach-loops and the ability to write your own plug-ins. It’s very well known for having heavy problems with recursion (the solutions I’ve seen the last time I looked at it weren’t really great). But I still prefer it over PHP as it keeps me and co-workers from doing stupid things.

However, what if you had to use recursion? What if the input wasn’t XML? (Yeah, I know it’s hard to believe, but sometimes stuff on the web just isn’t written in XML. Strange, isn’t it?).

I was in this situation, well, kind of. Actually I brought myself into this situation in order to develop the solution as part of a project for university. But that’s just fair, the result does what it should and the world has one more template-engine for PHP.

The rest of this article will discuss my Pgs_StringTemplate engine. I’ll talk about the Why? How? and When? related to it and try to explain my motivation behind it. Please keep in mind that it is totally clear to me that this engine is useless. I really know that you could do all it can do with pure PHP. I just don’t want to use PHP (as explained earlier). So thanks, but no, I don’t think you can convince me to switch to pure PHP any time soon.

Now for starters, why is it called Pgs_StringTemplate (or ST, as I’ll call it from now on)? When I looked into what was available at other places, I found StringTemplate, which turns out to be a totally different kind of template engine from what I knew before. For one thing: There are no loops. The other part is that it defines templates within a language instead of embedding the template expressions/commands within the static text. That way, you can define more than one template within a single file, kind of like a function.

I found this idea to be fascinating and ever since I first saw that engine I dreamed about writing a compiler for a comparable language that’d create pure PHP files. Having the ability to use the templates like objects. That’d surely be perfect for writing views (of the MVC-fame).

Just in case you didn’t yet checkout on StringTemplate, this isn’t the tool you’d give to your designer who doesn’t have any programming experience. In my view, this is more of a tool supposed to be used by a programmer that does have to write the view-part himself. Now for me this is perfect. I’m still working for clients on my own sometimes. Creating, updating and modifying websites and so on. And even when I need to consult a designer, he’ll just give me a PSD or image of the design he created and I’ll do the rest. That way both of us can do what we’re best at. He does the creative thinking and invents the design, and I’m using my knowledge of XHTML, CSS and so on to create the real thing.

Anyway, this project gave me the chance to actually implement my idea. I had written a basic library for writing LL(k)-Parsers in PHP long before (it’s a subset of the ANTLR3-library (just the runtime-library, not the tool itself), ported to PHP) and had gained a bit of experience in this field of software engineering, so I was pretty sure I could complete this project “in time”.

What we’d be using ST for was this: Given a Treebank-formatted text, output it in different formats. The Penn-Treebank format looks a lot like S-Expressions (think: Lisp). For example a valid sentence (possibly one of the most famous samples) might look like this:

( S
     ( NP-SBJ
         ( NP
             ( NNP Pierre )
             ( NNP Vinken ) )
         ( , , )
         ( ADJP
             ( NP
                 ( CD 61 )
                 ( NNS years ) )
             ( JJ old ) )
         ( , , ) )
     ( VP
         ( MD will )
         ( VP
             ( VB join )
             ( NP
                 ( DT the )
                 ( NN board ) )
             ( PP-CLR
                 ( IN as )
                 ( NP
                     ( DT a )
                     ( JJ nonexecutive )
                     ( NN director ) ) )
             ( NP-TMP
                 ( NNP Nov. )
                 ( CD 29 ) ) ) )
     ( . . ) )

The head of each expression is the linguistic category of the sub-expression. For example: NP means “nominal phrase” and a VP is a “verbal phrase”.

Our goal was to parse this into an array structure and look at what kind of output we could generate using ST and without having to modify the array in PHP.

Now as I mentioned before my personal goal was to bring a bit of Parrs StringTemplate to PHP but to leverage the PHP-platform at the same time. I wanted tight integration with PHP and I wanted the output to be PHP classes.

This means that you can actually extend a template written in ST from PHP and a ST-template can extend and implement PHP classes and interfaces.

I also added the ability to “import” methods from PHP-classes (this is done by creating an object of the class-type and dispatching calls to the method to this object, instead of a template function.

This mechanism allowed me to easily implement a couple of useful functions like first and rest that definitly eased the array-walking and you can even stretch it to enable stateful templates with variables (which I didn’t include in the language by itself because I don’t really want anyone to do this).

So ST is pretty flexible and very easy to extend from PHP. To underline this, let me show you the implementation of first and rest:

class Pgs_Treebank_Util {
    public function first($array) {
        return $array[0];
    }

    public function rest($array) {
        return array_slice($array, 1);
    }
}

As you can see there is absolutely nothing “special” about this class. Just some class that encapsulates a bit of logic. Now, to be fair to ST: This class does nothing that ST isn’t capable of itself. But writing rest(someArray) is a bit cleaner than |array_slice(someArray, 1)|, at least in my opinion. You couldn’t have written the functions using ST though, as it only supports functions that return Strings at the moment.

On the other hand ST does support one feature that PHP doesn’t (at least not without you having to write a hole lot of code): variable arguments. The last argument of an ST-function might be a vararg, meaning that all arguments starting with this one, will be reduced to a single array (pretty much the way Java does it). This feature enables us to write another simple utility function, this time in ST itself and a bit simpler than the PHP-alternative:

template Pgs_ST_Util;

concat(parts*) = << $parts$ >>
concatWith(separator, parts*) = << $parts; separator=separator >>

This function will take all of its arguments and reduce them to a single string. So whenever you write an ST-expression that involves an array in a scalar context (like in the example above) it’ll be reduced by concatenating all of its elements to a single string. You can use the separator-option to specify the separator that should be put between two elements, like I showed in the second function.

The above will be compiled into a class named Pgs_ST_Util and posses the two defined methods. You can instantiate it and use it like any other PHP-class. For example:

$util = new Pgs_ST_Util();
$helloWorld = $util->concat("Hello ", "World");

ST also supports map-operations in addition to reduce as well as partial application and currying.

format(tree) = <<
    $tree:concat("<ul>", formatSubtree(_), "</ul>;")$
>>

This example demonstrates the map operation as well as partial application (as you might’ve guessed, the expression after the colon isn’t a complete one, instead the “_” is a placeholder for the currently processed element in the array). A naive translation into english might sound like this: For each element in tree, concatenate |<ul>|, the result of calling formatSubtree with the current element as argument and |</ul>|, and reduce the result to a single string.

One could’ve done the same a bit easier, but more verbose, by using currying and a simple utility function:

tag(t, txt) = << <$t$>$txt$</$t$> >>
format(tree) = <<
    $tree:formatSubtree():tag("ul")$
>>

In English: For each element in tree, invoke the formatSubtree method on it, use the result of this function as the second argument for the tag function and concatenate all of the elements in the array to one single string.

To import methods of PHP-classes or standard PHP functions, you can use an import statement which can follow the template-definition. For example:

template MyTemplate extends MyOtherTemplate implements SomeInterface;

import Pgs_ST_Util [first, rest];
import functionSpace [is_array];

functionSpace is a special name that points to the global function namespace in PHP. Therefore you can use all PHP-functions in ST without any problems.

I think these examples already showed why this solution is both, superior and inferior to Smarty. For one thing it has a very light and powerful syntax with support for quite a few functional programming concepts and is amazing when it comes to recursion. On the other hand its syntax and concepts are hard to understand for designers and it is a bit out of place when you really just want to define a single template using just a few variables.

As for the Treebank-project, we managed to implement a pretty-printed version of the input (with syntax highlighting), an alternative bracket-format (using square brackets instead of parentheses and subscripted categories — with syntax-highlighting), a simple HTML-list and SVG output. The latter was obviously the hardest to implement and forced me to implement PHP-classes to manage a stack and state (to realize variables), but the output is pretty pleasing.

If you’d like to have a look at this, you might want to check out its website. There’s a paper about the project on that site, too. But it’s written in German so it’ll be of limited use for you if you don’t speak that language. You can still look at a few more samples, though.

And before you go off and tell me: I know that the website won’t work at all in IE. That’s probably because of the content-type I send (|application/xml+xhtml|) but I need that one in order to get the inlined SVG-output to work and I don’t feel like fixing it.

ST itself will be released soon under an open source license I have yet to pick. I’m fighting with myself to get me to choose LGPL in favor of BSD/MIT. But I’m still unsure. If you’d like to play with it, send me a mail and I’ll reply with a zip-archive.

Posted in Pagosoft, PHP | 1 Comment