ACFactory Day 4: Command & Control

This is the fourth part of a series documenting the development of ‘ACFactory’ (ACFabrik in German), an application that generates printable character sheets for the Pen & Paper role playing game Arcane Codex (English page).

You might also want to read Day 3: Authoring XAML.

Today, I was mostly lost in the vast unknown jungle that WPF is, even after having read “Windows Presentation Foundation: Unleashed by Adam Nathan” (I really recommend it!).

Control

First there was the difference between UserControl and custom control. (No, I am not very familiar with any other UI framework). Whereas UserControls are little more than include on steroids (you get a code behind file), if you *really* want to create something new or abstract over a composition of controls, then creating custom controls is your only option.

But custom controls are just C# (or VB.NET) code files. There is no XAML involved. How can that be the preferred way to author new controls? Remember that WPF controls are supposed to be look-less, platonic ideas of what they represent.
I wanted to create a zoom view control. What are the abstract properties of such a zoom view control?

  1. It has content
  2. It can magnify its content

Number 1 tells us to derive from ContentControl, the type that defines the Content property. Number 2 is a bit trickier. I decided that my control has a ZoomFactor property (type double, 1.0 == 100%) to which a ScaleTransform is bound. Whether or not this works, I am not exactly sure as the control is not working yet.

But how does the control look? Well that’s not the controls concern. A look is provided by the Themes/Generic.xaml resource dictionary, the default fallback in the absence of local definitions and system specific themes. In my case there is going to be a neat little zoom control (combo box + slider) hovering in the top left corner.

Command

To establish communication between the ZoomViewer template and the ZoomViewer control, there is really only one good mechanism: Commands. Commands are yet another abstraction that makes event handling more modular. Controls like buttons, hyperlinks and menu item can be “bound” to a certain command. That command determines whether they are enabled or not and what happens when they are clicked. You could for instance bind the menu item Edit > Paste, a toolbar button and Ctr+V to the Application.Paste command and they would all automatically be activated/deactivated depending on the state of the clipboard.

Even better, the default implementation, RoutedCommands, work just like routed events and bubble up the tree of your XAML interface. You can then define different command bindings at different locations in your UI. The best of all: Via the command target property, you can tell the command routing where to look for command bindings. I could have two buttons, that both invoke the Navigation.Zoom command, but on two different ZoomViewers.

My ZoomViewer does support the Navigation.IncreaseZoom, .DecreaseZoom and .Zoom commands. This is how the default control template can communicate with the ZoomViewer, by invoking those commands.

There is however one thing, I found very irritating: neither the slider nor the combo box implement commands by default. The msdn contains a sample, that shows how to do this. It turns out to come with quite a few things to watch out for:

  • You must differentiate between routed and ordinary commands as only the former can react to command bindings and can be set to originate from different InputElements.
  • You should rather pass a reference to the invoking control than null as the command target.
  • You must be careful with the CanExecuteChanged event handler. It must be correctly unset, when the command is changed/removed.

How well this all turns out, will hoepfully see soon. Development right now is a bit sluggish as I keep switching over to msdn and/or my book for reference, since Visual Studios XAML editor is not very sophisticated, even with basic ReSharper support. This must get much better in VS10. Up until now, I have observed VS08SP1 only crash 3 times (twice due to a recursive binding *blush*) and once with an HRESULT of E_FAIL (whatever that exactly was). But at least I lost no code.

Oh, and why exactly the Microsoft Blend XAML editor does not provide any support is totally beyond me. I mean free (that means it costs nothing) tools provide better code completion than Blend: Kaxaml, the “better XamlPad”. Even though it takes some time to load, I can definitely recommend it.

ACFactory Day 2: ExtendableEnum and XAML Serialization

This is the second part of a series documenting the development of ‘ACFactory’ (ACFabrik in German), an application that generates printable character sheets for the Pen & Paper role playing game Arcane Codex (English page).

You might also want to read Day 1: SealedSun goes WPF.

ExtendableEnum

Talents in Arcane Codex have a number of properties that are best described as enumerations. Unfortunately plain old enumerations are very flat. Translating them (when displayed in a user interface) requires you to wrap each and every appearance in the system. This is why I need a richer enumeration type.

Enter ExtendableEnum, an abstract base class that handles comparison and parsing of enumeration values. An existing enumeration could even be extended by a plug-in, should my application ever implement a plug-in system.

I was, however, confronted with a very annoying problem: type initialisation is lazy. The CLR employs certain “heuristics” to find out when to initialise a type. By default, a type is marked with “beforeFieldInit”, which means that the type is usable before its static fields have been initialised. Of course, static fields are always initialised “just-in-time” when they are accessed. The attribute is not applied when the class contains a static constructor (or class constructor or type initializer). In that case, the type is initialised when one of its members is first accessed.

While this is a pretty good strategy for the “normal” use of types, it might be a problem in XAML-based applications since the ExtendableEnum-parser is used before any of the enumeration values is referenced in code, which in turn means that the corresponding enumeration types had no chance to register their enumeration values with the corresponding registry.

One Solution I have found is the System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor method which, well, runs type initializers. I can only hope that the method (which points right into the heart of the CLR) is smart enough not to initialise a type twice. My approach is not perfect as extensions of enumerations are not necessarily included. For a future plug-in system, some sort of InitializeOnLoad attribute could save the plug-in writers day. But my hack works 100% for all non-extended enumerations and that’s enough for milestone 1.

XAML Serialization

Step 1: Make your objects “expressable” in XAML

The “read”-aspect of XAML serialization is much more important as it is an absolute requirement for milestone 1. The tricky thing with XAML is, that you cannot express circular references for plain CLR objects (no DependencyObject). My object model, however, requires two way relationships in some places. For instance: Talents need access to the attributes of “their” hero in order to compute effective talent levels. Now since there has to be a default constructor, the hero reference will be initialised with null, resulting in an invalid state. There is no way to ensure that your object is initialised correctly, as you don’t know when WPF/XAML is “done” with its manipulations.

The only option is to propagate the hero reference down the hero graph once the hero is created, which means that even collections have references to the hero they belong to.

Step 2: Make your objects serialize correctly

Contrary to what people might tell you, XAML Serialization does not come for free. There are severe limitations and not that many customisation options. Here is how I wished I could store my heroes:

<Hero ShortName="Kyle" FullName="Kyle MacDuncan">
    <Hero.Attributes>
        <Attribute Level="8">Strength</Attribute>
        ...
    </Hero.Attributes>
    <Hero.Talents>
        <Talent Level="5">Sword</Talent>
        ...
    </Hero.Talents>
</Hero>

Automatically converting the hero-less Attribute and Talent to their bound equivalents, HeroAttribute and HeroTalent respectively. Interpreting this is one thing. A bit of Voodoo magic and a couple of virgins (read: TypeConverters and the like) would make this work. But as I said, there is no way to tell the XAML serializer to first convert certain values to more serializable equivalents.

So eventually I gave up and implemented  XAML serialization using a pretty nasty hack: All the properties that need processing prior to assignment are loaded off into a xData class (HeroData, TalentData, and so on). This essentially means that I have to implement each non-trivial property at least twice and that extension via plug-ins has become at least twice as difficult. My serialised hero looks like this:

<Hero x:Key="codeHero"
      xmlns="clr-namespace:ACFabrik.Model"
      xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      ShortName="Kyle" FullName="Kyle Mac Duncan"
      ExperienceTotal="14" ExperienceUsed="12"
      FameTotal="15" FameUsed="10" Encumberment="0" >
    <HeroData LocalLibrary="{wpf:StaticResource defaultLibrary}">
        <HeroData.Attributes>
            <HeroAttribute Level="8" Attribute="Strength" />
            <HeroAttribute Level="7" Attribute="Constitution" />
            ...
        </HeroData.Attributes>
        <HeroData.Talents>
            <HeroTalent Level="7">Alchemy</HeroTalent>
            <HeroTalent Level="8">Attention</HeroTalent>
            ...
        </HeroData.Talents>
    </HeroData>
</Hero>

The HeroData node defines a new attribute: “LocalLibrary”. It is used to map the talent names (and possibly others) to their definition in an external library. This way multiple heroes can share the same talents. LocalLibrary is only required when heroes are loaded as part of XAML resources, i.e. when you don’t have control over the XamlReader.Load method.

The result is a bit more verbose and not that beautiful.

Well, at least it will yield good compression ratios (the “<Hero”-prefix…).

Next Steps

On the data side, the next question to answer is how the file formats look exactly. While I now have the basic capability to serialize my objects to streams, I need to come up with concrete formats for heroes and libraries.

Also, I need to start thinking about the general UI concept. Printing in WPF works via Visuals, so I literally get previewing for free. I therefore include a very basic UI (preview + print button) in the requirements for milestone 1.

ACFactory Day 1: SealedSun goes WPF

This is the first part of a series documenting the development of ‘ACFactory’ (ACFabrik in German), an application that generates printable character sheets for the Pen & Paper role playing game Arcane Codex (English page).

Before I explain why I chose to implement ACFactory in WPF, let me quickly sketch the application’s functionality planned for the first iteration:

  • Read a hero definition from a human-writeable text file
  • Print a sheet that lists all the talents known by a hero

Note that having a graphical UI is explicitly not a requirement for the first iteration. It is not the first character sheet generator I’m writing. The Heldenfabrik (Hero factory, not released) project for instance uses the Prexonite scripting engine to define a DSL used to specify heroes and the same GDI+ based rendering framework (read: bunch-a-classes) as the DSA calendar generator (DSA Kalendergenerator) to generate an almost-A4-sized png. Needless to say, that it was very painful to hard code all the spacings and layout characteristics. I needed something that supported me in designing fixed-page layouts. One solution would have been to write a custom rendering engine that would be tailored to the special needs of fitting content of variable size onto a fixed page. I even went so far as to prototype a possible architecture in F#, only find out that

  1. It is really hard to express complex object models in F# due to the lack of forward declarations.
  2. It is a lot of work to implement automated layout.

So what are the alternatives? What publicly available layout engines exist out there? One obvious answer is XHTML+CSS. XHTML documents are relatively easy to generate (System.Xml.Linq aka LINQ to XML or XLINQ), well understood and can be printed by modern browsers. The problem: XHTML documents are inherently digital and thus optimised for variable sizes. Also the final look depends on the layout engine (read: browser) used to display the document. I don’t even want to talk about the horror that printing from a browser is.

Living in a .NET 3.5 environment I could no longer ignore our little newcomer to the graphical user interface world: Windows Presentation Foundation (WPF). We all suspected, that this user interface framework has more to offer than a ridiculously unpronounceable name and fancy 3D graphics. It comes with layout features web designers can only dream about (one word: Grid). So what’s the catch apart from acknowledging that WPF might be cool?

A friggin’ steep learning curve. You can learn C# without a book if you’ve already worked with the .NET framework (via, say, VB.NET). You can learn CSS, XML, XPath, XSLT without a book given good online tutorials. But WPF is so complex, that it would take you months to harvest even basic knowledge of WPF from blogs and tutorials all over the net.

Windows Presentation Foundation Unleashed (WPF) (Paperback)Since I want to finish the project within 7 days, this was not an option (also, I’m a very impatient person). I needed a book. There were two books recommended all over the internet (Applications = Code + Markup by Charles Petzold) and Windows Presentation Foundation Unleashed by Adam Nathan. Based on the customer reviews I decided to buy the latter (the fact that this one was printed in colour made the decision much easier :-) ).

So here I am, roughly in the middle of the book on page 355 at the beginning of chapter 11 about 2D graphics. One thing I noticed was the alarming number of pitfalls or things-to-remember when coding WPF interfaces. Although the majority of the framework builds on predictable and consistent patterns, there are odd edges here and there such as having to use {Binding RelativeSource={RelativeSource …}} for relative sources as opposed to the uniform {Binding Source={RelativeSource …}. Overall I have the feeling that there will be a lot of reinventing-the-wheel involved as WPF is not as complete as it could (should?) be. Sortable ListView out of the box, anyone?

But wait! Didn’t I forget something? Right: Like XHTML, WPF is tailored towards flexible layouts in containers of variable size. Doesn’t this rule WPF out as the layout engine of choice? Nope: WPF was designed to be resolution independent, operating on “virtual” pixels the size of 1/96th of an inch (or device pixels at DPI=96). I can therefore calculate the size of an A4 page at 96 DPI, which is roughly 793.701 pixels times 1122.52 pixels or 3.77953 pixels per millimetre (Beautiful number isn’t it? :-( ).

Next Steps

Before I start designing the character sheet, I want to have my Business Objects (the hero + his/her talents) to be up and running. I need a format that is human-writeable and can be loaded by my application. I’m currently looking into the object serialization aspect of XAML, which I already successfully used to define a serializable library of talents available to heroes.

XAML (aka System.Windows.Markup) knows how to serialize objects that

  • Have a public default constructor (no arguments)
  • Expose their representation in writeable properties

It’s not that adhering to those rules is especially difficult but it is extremely tedious as immutable objects are essentially ruled out. I like to build my objects (classes) like fortresses, using the type system, readonly modifiers and immutablity to reduce the number of ways an object can enter an invalid state. Designing a business model that serializes to XAML therefor means opening all doors to malicious (and/or stupid) users (developers that use my code). I practically live in the library-writer-world and having to write class that expose their representation the way WPF likes it, makes me twitch.

But seeing how elegant XAML maps XML elements to the familiar .NET objects really makes up for the mental pain I am about to go through. You’ll hear from me.

Continue reading on ACFactory Day 2: ExtendableEnum and XAML Serialization

Operator overloading for Prexonite, more or less

Prexonite October 2008

While Prexonite Script does not formally provide any means of object-oriented programming (not just consuming objects but actually defining new ones) there are mechanisms in Prexonite (the runtime) that try to make up for this.

What Prexonite includes so far

  • The Structure data type
    • groups values and functions together
    • provides "natural" access via dot-notation

    Prexonite Script:
    1. function create_complex(_re, _im)
    2. {   
    3.     _re ??= 0.0;
    4.     _im ??= 0.0;
    5.     var z = new Structure;
    6.    
    7.     z.\("re") = _re;
    8.     z.\("im") = _im;
    9.    
    10.     z.\\("norm") = (this) =>
    11.         sqrt(this.re^2 + this.im^2);
    12.     z.\\("add") = (this,other) =>
    13.         create_complex(this.re + other.re,this.im + other.im);
    14.     z.\\("ToString") = (this) =>
    15.         this.re + " " + this.im + "i";
    16.    
    17.     return z;
    18. }

  • The ExtendableObject base class
    • Makes it possible for Prexonite code to "extend" .NET objects, should the developer want to allow this.
  • The struct function (in psr/struct.pxs )
    • automates construction of Structure objects via reflection

    Prexonite Script:
    1. build does require("psr\\struct.pxs");
    2.  
    3. function create_complex(_re, _im)
    4. {   
    5.     _re ??= 0.0;
    6.     _im ??= 0.0;
    7.    
    8.     function re(this, new_re)
    9.     {
    10.         if(new_re is not Null)
    11.             _re = new_re;
    12.         return _re;   
    13.     }
    14.    
    15.     function im(this, new_im)
    16.     {
    17.         if(new_im is not Null)
    18.             _im = new_im;
    19.         return _im;   
    20.     }
    21.    
    22.     function norm = sqrt(_re^2 + _im^2);
    23.    
    24.     function add(this, other) =
    25.         create_complex(re + other.re,im + other.im);
    26.    
    27.     function ToString =
    28.         re + " " + im + "i";
    29.    
    30.     return struct;
    31. }

New in this release1

  • auto-property, proxy-property, property support via psr/prop.pxs
    Prexonite Script:
    1. build does require("psr\\struct.pxs","psr\\prop.pxs");
    2.  
    3. function create_car(a_color)
    4. {     
    5.     _re ??= 0.0;
    6.     _im ??= 0.0;
    7.    
    8.     function re = struct_prop(_re);
    9.    
    10.     function im = struct_prop(_im);
    11.    
    12.     function norm = sqrt(re^2 + im^2);
    13.    
    14.     function add(this, other) =
    15.         create_complex(re + other.re,im + other.im);
    16.    
    17.     function ToString =
    18.         re + " " + im + "i";
    19.    
    20.     return struct;
    21. }

  • operator overloading via (+), (==) etc.
    Prexonite Script:
    1. //...
    2. function (+) this other =
    3.     create_complex(re + other.re,im + other.im);
    4.  
    5. function (-.) =
    6.     create_complex(-re, -im);
    7.    
    8. function (-) this other = this + (-other);
    9.    
    10. //...

1psr/prop.pxs is in the repository since August.

Let's discuss those two extensions one by one…

Properties

First of all, there still is no language support for structures and properties. As of right now, they are implemented via compile time transformations. These two transformations can be enabled via importing the Prexonite Standard Repository scripts psr/struct.pxs and psr/prop.pxs. While the former has been around for some time now, the latter has only recently been implemented in managed code.

psr/prop.pxs defines the special function prop which is expanded into get and set code depending on the way it is used. The easiest mode of operation implements a property with an anonymous backing field (defined in the surrounding scope, i.e. as a global variable in a top-level function or a shared variable in the outer function) The second mode mimics a simple get-set proxy where the expression passed as an argument is used as the backing field. This works for arbitrary expressions as long as they can be the target of an assignment (i.e. they are get-set expressions). The third mode finally is a replication of C# properties taking separate lambda expressions for its get and set implementations.

struct_prop works the same way but ignores the additional this parameter for structure methods.

Operator overloading

When resolving operator calls, generic objects (as well as structures) now also try to call special instance methods after failing to find a corresponding static operator overload. This makes the implementation of operator overloads for structures and ExtendableObjects (An abstract class that makes an object extendable in the same way a structure can be extended) possible. In order to avoid strange operator names, I have introduced operator ids, special literals (on the lexical level) that represent operator names. There is nothing special about these literals, they can be used everywhere an id can be used. You could for instance define a local variable with the name (+).

SealedSun.GamePanel June08

[ Download SealedSun.Gamepanel June08 ]

SealedSun.GamePanel is a high level wrapper around the managed LcdInterface by http://www.cabhair-cainte.com/ismiselemeas/ that features a Winforms-like controls system as well as simplified event routing for the four soft buttons of the G15.

The library is not very mature and only the most commonly used features are implemented. Everyone with basic knowledge of System.Drawing should be able to implement custom functionality via user controls.

Quick Start

1. Create a new LcdScreen

The LcdScreen represents an entry in GamePanel manager and can be selected by the user via the application switch button on the Keyboard.

C#:
  1. using(var screen = new LcdScreen())
  2. // ...
  3. }

2. Open the LcdScreen

To notify the GamePanel manager of the new screen, call the Open method.

C#:
  1. screen.Open("My LCD");

3. Create a new LcdPage

An LCD page is like an empty canvas. It is the container for all your UI elements.

C#:
  1. var page = new LcdPage(screen);

4. Add controls to the LcdPage

There are currently only two built-in general purpose controls: LcdLabel and LcdImage. In order for your controls to show up, you need to add them to the page object. You can also nest controls by adding them to other controls. Always keep in mind, that the positioning is relative to the parent control and that controls cannot exceed the bounds of their container.

C#:
  1. var lTitle = new LcdLabel();
  2. lTitle.Text = "My LCD";
  3. lTitle.Location = new Point(10,10);
  4. page.Controls.Add(lTitle);

5. Configure soft buttons

The page object provides access to the four soft buttons via its Button0,1,2,3 members. Those special controls provide 'button pressed' events and are always located immediately above the respective buttons. Their Text and Image properties can be used to label them. If you need better control over the labelling, you can add child controls to the soft buttons like to any other control.

C#:
  1. page.Button0.Pressed += (sender,e) =&gt; {
  2. Console.WriteLine("0 Pressed!");
  3. };

6. Select active page

In order for a page to be displayed on a screen, it must be assigned to its CurrentPage property. Only pages that are currently active will fire events.

C#:
  1. screen.CurrentPage = page;

7. Enter message loop

Like a windows forms application, an LCD application too has a message loop. Similar to Application.Run, screen.Run will use the current thread to process messages from the GamePanel manager.

From here on...

If you want to get the users attention, you can change the pages screen priority to Alert for a short amount of time. A convenient way to do so is the TemporaryAlert method. This of course only works, if the user allows high priority screens.

C#:
  1. page.TemporaryAlert(500);

If you want to quit the message loop, either close the screen or call Screen.ExitMessageLoop.

License and Disclaimer

Except for the components mentioned in the ExternalResources.txt, I hereby release everything the zip archive under the terms of the Creative Commons Attribution-Share Alike 2.5 Switzerland license.

The software was written over the course of a few days and did therefor not undergo much testing. It is most likely that you will encounter bugs and unexpected behaviour. You use the library at your own risk.

Creative Commons License
SealedSun.GamePanel by Christian Klauser is licensed under a Creative Commons Attribution-Share Alike 2.5 Switzerland License.