Kah – The Developer

Starting with Tables in OpenOffice Base

Posted by: kahgoh on: 27 October, 2009

When you create a new database using OpenOffice base, you will need to setup one or more tables to store and organise your data. If you are already familar with other database systems, like MySQL or PostgreSQL, you already how to use tables and should be able to do this part yourself. If you wish, you can always use the wizard to create a table. Read the rest of this entry »

Formatting Source Code in HTML

Posted by: kahgoh on: 18 August, 2009

If have you seen a number of my tutorials, you would have seen some nicely formatted sample code embedded within the page. Pastebins can host your code there are Javascripts that can also format your code. However, the WordPress service does not allow either of those options to be used. The only way I have been able to do so far has been to convert the code into an HTML code.

Read the rest of this entry »

Tags: ,

Controlling UI Components using JGoodies Binding

Posted by: kahgoh on: 7 July, 2009

In Binding with JGoodies Binding, the binding library from JGoodies was introduced with a relatively simple example. The binding framework can also be used to automatically enable or disable user interface components depending on some condition.

A model is used to notify when the component should be enabled or disabled. This is a relatively simple model. It only needs to notify the library when the component should be enabled or disabled. I’ve called the model Allowance, as it is designed to notify when a feature or function is allowed to be used or performed rather than when something should be enabled or disabled. The code for the model is presented here:

 1 public class Allowance extends Model {
 2
 3   private static final long 
 4     serialVersionUID = 1L;
 5   
 6   public static final String
 7     PROPERTY_ALLOWANCE = "allowed";
 8
 9   private boolean allow = false;
10   
11   public void setAllowed(boolean nowAllowed) 
12   {
13     boolean oldAllowed = allow;
14     allow = nowAllowed;
15     firePropertyChange(PROPERTY_ALLOWANCE,
16       oldAllowed, allow);
17   }
18
19   public boolean isAllowed()
20   {
21     return allow;
22   }
23 }

Next, the Allowance model needs to be bound to the UI component. In the previously mentioned tutorial, an editor for a book's subject and title was created and bound to a model for a book. Let's say that the title field will now be enabled only when a subject is selected and disabled at all other times. Models allows listeners to be attached to receive notification of changes to specific properties. Interested listeners must implement the PropertyChangeListener interface. Here is the corresponding block of code to implement this behaviour:

final Allowance allowed = new Allowance();
PropertyChangeListener allowanceUpdate =
  new PropertyChangeListener() {

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
      if (!evt.getNewValue().equals("none")) {
        allowed.setAllowed(true);
      } else {
        allowed.setAllowed(false);
      }
    }
  };

The listener simply receives an event that contains information on the source of the event (i.e. the object with the changed property) and the old and new values of the property.

To be of any use, the listener has to be attached to our model. There are a few options on how this could be done. The listener can be directly attached to our model or indirectly via the same presentation model used in creating the editor. Generally, I recommend going through presentation model, as that would allow you to change the instance being edited much more easily. The listener requires knowledge of changes to the subject only. The binding library allows listeners to be notified of only changes to the subject. To attach the listener:

presentation.getModel(Book.PROPERTY_TOPIC).
  addPropertyChangeListener(allowanceUpdate);

The call to getModel() will retrieve the value model for the subject property of the book model. When you want to change the instance of the model that is being edited, you can use the presentation model's setBean() to load the new instance. If the listener had been attached to the our object, we would have to move the listener to the new instance ourselves. This is why I prefer going through the presentation model.

Finally, the allowance model needs to somehow be connected to the UI component. The line to do this:

PropertyConnector connection =
  PropertyConnector.connect(nameField, "enable",
    allowed, Allowance.PROPERTY_ALLOWANCE);
allowed.setAllowed(false);
connection.updateProperty1();

The PropertyConnector will automatically listen for changes to the Allowance and update the "enable" property of the component. Note that the "enable" property could have also been substituted for "visible" to have it change its visibility or &quoy;editable" to change whether it is editable or not. Using any of these properties will effectively control whether the user is able to edit the contents of the text field. There are also a few other properties that can be controlled in this way, such as "focusable" and "opaque". Files from this tutorial are downloadable from here

While in the example an Allowance model was created for the purpose of modelling when a component can be used or not, it should be noted that the binding library provides ComponentValueModel to control three of the properties – visible, editable and enabled. The model provides three separate methods for controlling the properties separately – setEditable, setEnabled and setVisible. Instead of using PropertyConnector to bind the model to the UI component, you should using Binding.addComponentPropertyHandler instead.

Setting the Font in a View

Posted by: kahgoh on: 24 June, 2009

Sometime ago, I was asked how to control the font used in a customised view. In the customised view, the onDraw method is overridden and had code looking like this:

Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
canvas.drawText("Text to display", posX,
    posY, textPaint);

To change the font, Paint has a setTypeface method. This method takes in a Typeface object, which determines which font is used. The Typeface class has a number of static methods to create the instance for us. If you want to use TrueType Font file, place the file in assets folder, like how this:

TTF file in the assets

Now in the code, we can use the createFromAsset method to create the Typeface object and set the Paint to use it. With the additional lines, the code fragment now looks like this (the added lines are in bold):

Paint textPaint = new Paint();
textPaint.setColor(Color.BLACK);
Typeface font = Typeface.createFromAsset(
    getContext().getAssets(), 
    "fonts/androidnation.ttf");
textPaint.setTypeface(font);
canvas.drawText("Text to display", posX, posY,
    textPaint);

Typeface also has a few fonts that are already defined and can be loaded without having to additional font files. These fonts are defined as public constants in Typeface and they are listed in the documentation for Typeface. For example, to set the Paint to use the default bold font:

textPaint.setTypeface(Typeface.DEFAULT_BOLD);

The other fonts defined accessible as constants from Typeface are serif, sans serif and monospace.

The font of text inside a TextView can also be changed using its setTypeface method. Like the one for Paint, it also takes in a Typeface as an argument. If the TextView is being specified in a layout XML file, the font can be changed using the android:typeface attribute. For example.

<TextView android:id="@+id/TextView01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Customised Font"
    android:typeface="monospace" />

However, the fonts must be either normal, sans, serif or monospace.

Manage your Finances with GnuCash

Posted by: kahgoh on: 23 June, 2009

I have been GnuCash to help manage my finances for a while now. If used correctly, it is useful tool for tracking your finances and planning for those big ticket purchases. You do not require a lot of knowledge of accounting to use this software – just enough discipline to keep the data up to date! It is also an open source software. This tutorial provide a quick introduction to some of its basic functions.

Setup the Accounts

All assets, expenses, etc. are organised into a hierarchy of accounts. When you create a new file for the first time, you can use a wizard to set up some default accounts and custom them later. To begin, create your first accounts by selecting FileNewNew File. A New Account Heirarchy Setup druid (or a wizard) will guide you through to setting up the first set of accounts. Feel free to go through the druid to setup the first accounts. Once the wizard finishes, you’ll be brought to the accounts page.

Accounts Page

Here, you should review which accounts have been setup, as the hierarchy of accounts also represents the breakdown of your asserts, income, expenses, etc. You should check that the accounts are broken down to a level that you are happy with. For example, if you have multiple savings account you may wish to have separate subaccounts for each one instead of having just one account to represent all of them.

Tracking your Accounts

When you create a new account, the dialog will have an Opening Balance tab for you to enter the opening amount.

Opening Balance Tab

If you did not enter an opening balance, you can still enter this manually. First, open up the account that you want to enter the initial balance for. An empty accounts page will looks something like this:

Transactions For an Account

The transfer column is the account that the amount is taken from. All transactions must result in a transfer to or from another account. If you leave the column blank, GnuCash will assign a default account. For opening balances, GnuCash would have suggested using a separate equity account. After entering your opening balance, you can open the account that you transferred from. You should be able to find a corresponding entry back to your account. Each time you enter a transaction into an account, there will always be a corresponding entry in the account that you transfer from or to. When you return to the main account page, the amounts in each account will be updated to account for the transactions. The totals under each account reveal how much is in an account or how much has been spent, etc.

Recurring Transactions

GnuCash allows can automatically enter recurring transactions. There are a couple of ways to setup the transactions. The scheduled transactions editor accessed through ActionsScheduled TransactionsScheduled Transaction Editor. You should be able to go through each of the options and fill in the fields without much trouble. Once you have created your scheduled transaction, it should be added to the list of transactions on the Scheduled Transactions page. You can also create scheduled transactions from an accounts page by right clicking when you are entering a new transaction.

Generating Reports

The data collected by GnuCash can be displayed in many different ways. Firstly, there is the main accounts page that provides a snapshot of how much is in each account or how much you have spent in each category. Expense Piechart and Expense Barchart reports available under Income and Expenses are especially useful if you are trying to find ways at reducing spending. If you are also wondering how much you are worth over a period of time, you should check out the Net Work Barchart under Assests & Liabilities. However, it is important to note that the reliability of the information provided by these reports depends on how well you manage to keep the data up to date.

This covers the some of the features that you would most likely use in managing your personal finances. However, there are many more features not yet covered. If you run a business, it also has features for employee salaries, invoices and bills. If you hold shares, it also has features for entering purchased stocks and retrieving the latest prices. There are simply too many features to cover in this tutorial! If you are interested in using the other functions, the Tutorial and Concepts Guide under Help will provide most of the information that you require.

Binding with JGoodies Binding

Posted by: kahgoh on: 29 April, 2009

The binding framework allows you to write classes that represents model completely independent of the user interface. The classes are bound to the user interface and are updated as the user interface enters information. The frame is based on the presentation pattern, described by Martin Fowler.

The framework already provides a Model class. Classes containing attributes that are editable on the user interface would be a subclass of this. It adds functionality to notify of events. By default, the frame assumes that the used naming conventions for the properties, accessors and mutator methods follow the same pattern as suggested in the Java beans specification. For the models that I create, I provide the property as a public constant within the model. The mutator code also need to call the model’s firePropertyChange method to notify listeners of a change to the property. For example, a model for a book could be the following:


public class Book extends Model 
{
    

    /**
     * References to the properties for the model.
     */
    public static final String PROPERTY_TITLE = "title";
    
    

    /**
     * Keeps track of the title of the book. 
     */
    private String title = " ";

    

    /**
     * Changes the title of the book.
     * 
     * @param newTitle
     *             The new title for the book.
     */
    public void setTitle(String newTitle) 
    {
        String oldTitle = title;
        title = newTitle;
        firePropertyChange(PROPERTY_TITLE, oldTitle, 
                newTitle);
    }
    
    /**
     * @return The title of the book.
     */
    public String getTitle() 
    {
        return title;
    }
    
    
}

For creating the user interface components that will be editing the model, the PresentationModel is created for the object. The PresentationModel provides a representation of the user interface. The framework also supplies a BasicComponentFactory that you can use to create the components. The factory will also bind the component to the appropriate attribute. The methods that create text fields require a value model as one of its paramters. The value model is what is actually updated when the user makes changes in the component and it should be retrieved from the PresentationModel using its getModel method. For example, to create a text field for entering the title of a book:

        
        final Book subject = new Book();
                
        final PresentationModel<Book> presentation =
            new PresentationModel<Book>(subject);
        
        JTextField nameField = BasicComponentFactory.
            createTextField(presentation.getModel(
                Book.PROPERTY_TITLE), false);
        

The third parameter, which is set to false will cause the bounded instance to be updated as the user makes changes in the text field. Setting it to true will result in the changes being made only when the field loses focus instead.

In the case of list selection fields, such as a JList and JComboBox, the required model is a SelectionInList. SelectionInList provides the functionality for tracking changes in the selection. Setting up a SelectionInList might require a few different calls.

    
    public static final String TOPICS[] = 
    {"science", "history", "arts"};
    
        SelectionInList<String> topicSelect =
            new SelectionInList<String>(TOPICS);

        /**
         * Set the presentation model as the model that
         * holds the selected value.
         */
        topicSelect.setSelectionHolder(
            presentation.getModel(
                Book.PROPERTY_TOPIC));
        
        JComboBox topicBox = BasicComponentFactory.
            createComboBox(topicSelect);
        

The SelectionInList class has a few different constructors that allow you to specify the set of possible options as a list or an array. The call to setSelectionHolder will make updates to the presention model as the selection of the value is changed.

The BasicComponentFactory can also create JLabel that displays the current value of an attribute in the model. The label gets updated as the value of the attribute changes.

        
        JLabel titleLabel = BasicComponentFactory.
            createLabel(presentation.getModel(
                Book.PROPERTY_TITLE));
        
        JLabel topicLabel = BasicComponentFactory.
            createLabel(presentation.getModel(
                Book.PROPERTY_TOPIC));
        

Since the title property has been bound to the title text field, the titleLabel will be automatically updated when the user makes changes in the field. Similarly, topic property has been bound such that when the user changes its selection, it the topicLabel will be updated. If you wish to try out the examples from here, you can get the source code here.

Merge Tracking with Subversion (pre 1.5.0)

Posted by: kahgoh on: 7 April, 2009

Merge tracking is a feature of some revision control software. This feature remembers which merges have taken place, allowing you to later see what merges have been done and what else needs to be merged. The feature was not part of Subversion until version 1.5.0. However, not all projects are using the latest version of Subversion. Fortunately, for projects that are using older versions of subversion, there is still the svnmerge script. If your project is using the latest version of Subversion, it should already have similar functionality.

Initialising Merge Tracking

To use the script, the branch should be made by using the svn cp command. The branch is usually created from trunk. Once the branch has been created and checked out, you must tell it to initialise your checkout before making any changes. It is also important to execute the initalisation command at the top level directory of the branch. For example, lets say you check out the file:///repository/branch/example to /home/user/work so that you now the contents of the branch is located in /home/user/work/example. Then you should change to the directory /home/user/work/example before executing the initialisation command:

svnmerge init

If you had already made any changes, you should receive an error similar to the following:

svnmerge: “.” has local modifications; it must be clean

If it was successful, you should now have a file svnmerge-commit-message.txt in the directory. This file is used by the script to track the merges that are performed and can also be added to your repository so that you do not lose your merge tracking information if you delete your current checkout. The contents of the file is also human readable, so you can view it to see what has been merged.

Finding Out What is Available for Merging

Now that the svnmerge has initialised merge tracking for the directory, you can find what changes from trunk need to be merged. The avail command will tell you which versions need to be merged. To view the log messages of the versions that need to be merged, you can simply use:

svnmerge avail –log

Omitting the “–log” option will cause svnmerge to output just the revision numbers that need to be merged. The avail command also has the option “–diff” to output the differences that need to be applied. If the initialisation was not properly done, you might receive the error:

svnmerge: no integration info available

Another message that you might receive is when you have created a branch from another branch. For example, if you create branch b from a and then c from b and you executed the command on branch c, you would receive an error message that is similar to the following:

svnmerge: multiple sources found. Explicit source argument (-S/–source) required.

The merge sources available are:

/trunk

/branch/test

The problem here is that svnmerge needs to know which of the parent branches to compare branch c with. As suggested in the message, using the “-S” option will tell svnmerge which branch to compare with.

Merging to the Branch

To perform the merge, you just have to use the merge command, as follows:

svnmerge merge

Once the command has been executed, the file svnmerge-commit-message.txt will be updated with latest merge information. Note that because this file is updated when the script is called on to perform the merge, it will NOT detect any merges that you may have performed manually. Should you perform a merge without using svnmerge, you can try executing the merge with svnmerge to update the file. Alternatively, the merge command has a “-M” command to record a merge without actually performing the merge. The merge command also allows you to specify the revisions that are merged. The option for this is “-r”.

Merging Back to Parent

After you complete making changes on the branch, the script can also be used to merge the changes back to the parent branch. To do this, first change to the top level directory where the parent branch was checked out (similar to what was done in Initialising Merge Tracking). Merge tracking needs to be initialised again. Beware that if you have a svnmerge-commit-message.txt file in the directory, it will be overwritten. This path to the branch where the changes were made needs to also be specified, by using the following form of the initialising command:

svnmerge init [path to branch]

While staying in the same directory, execute the merge command to merge the changes back. Again, depending on the number of branches created from the parent, it may be necessary to specify the source branch if it complains about multiple sources (see Finding Out What is Available for Merging). Note that when merging back to the parent, you do not have to execute the initialisation command at the location of the branch.

Preventing Specific Versions From Being Merged

After executing the avail command, you might discover revisions that you might not want to merge. Revisions that should never be merged can be blocked using:

svnmerge block -r [revisions to block]

When you execute the merge again, you should find that the specified revisions are left out of the merge. Note that omitting the “-r” option and the revisions will cause all available revisions to be added to the blocked list. This is also reflected in the output from executing the avail command.

If you later decide would like to make the revision available for merging later, you can use the unblock command.

svnmerge unblock -r [revisions to unblock]

Again, omitting the “-r” and listing the revisions altogether will unblock all revisions. Should you also forget which revisions were previously blocked, you can examine the property svnmerge-blocked.

Finding Out What has Been Merged

After having committed the merges, you might want to view the merges that have been previously performed. This viewable with the integrated command, which can be used like this:

svn integrated –log

Similar to the avail command, omitting the “–log” option will cause to print out just revision numbers and “–diff” can be used to view the differences. The versions that have been merged are also recorded in the property svnmerge-integrated.

Adding Selection Functionality to the Table View

Posted by: kahgoh on: 29 March, 2009

Lately, I was looking at how to present data in a table format, where each row would be data from an object, and allow users to select a particular row. One way of doing it is writing a ListAdapter and using it with a ListView. However, the way I tried to do it was using the TableLayout.

Admittedly, using the TableLayout looked like it is more complicated than using the ListView, although I have yet to try using ListView. Using the TableLayout, the view is programatically created (without using an XML file). In order to implement this, the implementing class needs to keep track of a number of things.


  1 package com.android.selectable;
  2
  3 import java.util.Collection;
  4
  5 import android.content.Context;
  6 import android.graphics.Color;
  7 import android.util.Log;
  8 import android.view.MotionEvent;
  9 import android.view.View;
 10 import android.widget.TableLayout;
 11 import android.widget.TableRow;
 12
 13 /**
 14  * Manages the display of the watch list.
 15  *  
 16  * @author Kah
 17  */
 18 public class ListDisplay<T>
 19 {
 20   /**
 21   * Reference to the list of stocks that are in the
 22   * watch list.
 23   */
 24   private final Collection<T> itemsCollection;
 25   
 26   /**
 27    * Reference to the view that displays the watch
 28    * list on the user interface. This needs to
 29    * inflated later, since the instance of the
 30    * layout inflater is required to create it.
 31    */
 32   private final TableLayout display;
 33
 34   private final Context appContext;
 35
 36   private final DisplayAdapter<T> dataAdapter;
 37
 38   private SelectionReceiver<T> selectionObserver;
 39   
 40   private T highlighted;
 41   

The DisplayAdapter is used to convert the objects into the data that gets displayed. A SelectionReceiver is notified when a item is selected by clicking on it.

The constructor creates the TableLayout, which may be set as the content view or may be added to another view.
 67   /**
 68    * Retrieves the display component to display the
 69    * contents of the watch
 70    * list on the user interface.
 71    *
 72    * @return The display view for viewing the contents
 73    *         of the watch list.
 74    */
 75   public View getDisplay() 
 76   {
 77     return display;
 78   }
 79
 80   /**
 81    * Retrieves the last item that was selected, but not
 82    * necessarily "clicked".
 83    *
 84    * @return The item that is currently at the cursor.
 85    */
 86   public T getSelected() 
 87   {
 88     return highlighted;
 89   }
 90

Next, the data from the list needs to be loaded into the table. This is done by adding a series table rows. Each row needs to be made focusable. Listeners are added to row to handle the highlighting and when the user clicks on a row. For highlighting, the OnFocusChangeListener and OnTouchListener are required. Clicking is handled by OnClickListener.

 91   /**
 92    * Loads the current contents of the list to the
 93    * displayed list. 
 94    */
 95   private void initialiseDisplay() 
 96   {
 97     // All rows will have the same parameters, so just
 98     // create it once.
 99     final TableRow.LayoutParams rowParams = new 
100       TableRow.LayoutParams(
101         TableRow.LayoutParams.FILL_PARENT,
102         TableRow.LayoutParams.WRAP_CONTENT);
103     
104     
105     // Go through the list and create table entries for
106     // each one.
107     for (T item: itemsCollection) 
108     {
109       TableRow newRow = new TableRow(appContext);
110       newRow.setLayoutParams(rowParams);
111       
112       View[] content = dataAdapter.getContent(item);
113       for (int index = 0; index < content.length; index++) 
114       {
115         newRow.addView(content[index]);
116       }
117       
118       newRow.setFocusable(true);
119       newRow.setFocusableInTouchMode(true);
120       newRow.setOnFocusChangeListener(
121         new RowHighlighter(item));
122       newRow.setOnClickListener(new RowSelector(item));
123
124       display.addView(newRow);
125     }
126   }
127   

Notifications about which item the user clicks is sent via the SelectionReceiver. This is an external class that we define. Of course, there needs to be a way of setting which instance of the SelectionReceiver will receive the notification.

128   /**
129    * Changes the receiver that is notified when an item
130    * is "clicked".
131    *
132    * @param receiver
133    *      The receiver that will be notified of changes.
134    */
135   public void setSelectionReceiver(
136    SelectionReceiver<T> receiver)
137   {
138     this.selectionObserver = receiver;
139   }
140   

The definition for the highlighting class:

141   /**
142    * This focus change listener handles the changing the
143    * background colour for highlighting the focused row.
144    * It also updates the variable keeping track the
145    * highlighted item.
146    */
147   private class RowHighlighter implements 
148     View.OnFocusChangeListener, View.OnTouchListener
149   {
150
151     /**
152      * The item that the highlighter is associated with. 
153      */
154     private final T association;
155     
156     public RowHighlighter(T association) 
157     {
158       this.association = association;
159     }
160     
161     /**
162      * {@inheritDoc}
163      */
164     @Override
165     public void onFocusChange(View v, boolean hasFocus)
166     {
167       int bgColour = Color.TRANSPARENT;
168       if (hasFocus == true
169       {
170         bgColour = Color.RED;
171         highlighted = association;
172       }
173
174       v.setBackgroundColor(bgColour);
175     }
176
177     /**
178      * {@inheritDoc}
179      */
180     @Override
181     public boolean onTouch(View v, MotionEvent event)
182     {
183       if (event.getAction() != MotionEvent.ACTION_UP) 
184       {
185         v.requestFocus();
186       }
187       return false;
188     }
189     
190   }
191   

Finally, the internal class for updating the row that is selected.

192   /**
193    * Handles the "clicking" on a row.
194    *
195    * @author Kah
196    */
197   private class RowSelector implements View.OnClickListener
198   {
199     private final T association;
200     
201     public RowSelector(T association) 
202     {
203       this.association = association;
204     }
205     
206     /**
207      * {@inheritDoc}
208      */
209     @Override
210     public void onClick(View v)
211     {
212       if (selectionObserver != null) {
213         selectionObserver.itemSelected(association);
214       }
215     }
216   }
217 }
218  
219

If you wish to download the source code, you can get it from here. As mentioned previously, this seems a long way of achieving a selectable list of items with three columns. Using a ListView, the item selection and item highlighting is taken care of. But how to use ListView is left for another day.

Using Ion, a Tiling Window Manager

Posted by: kahgoh on: 24 February, 2009

When working in Linux, I usually have multiple windows open. I always need at least one terminal to compile and execute commands. I would usually use Vim to edit my files too. Most likely, I would also have Firefox open with some information. During my work cycle, I constantly need to use these three windows.This means I need to be able to see the contents of these windows. The default Gnome and KDE window managers are rather inefficient at this because they can stack windows on top of one another. To make them non-overlapping, I have to individually resize the windows.

Ion is a tiling window manager. Unlike the stacking window managers, a tiling window manager can arrange your windows, such that they are non-overlapping (note I said can, because some they can still let you put a window on top of another).

Ion window manager with three non-overlapping frames.

Ion window manager with three non-overlapping frames.

To install, visit the Ion website. If you are using Ubuntu, you can install the Ion3 package instead. Once installed and running, you are likely to be presented with a window containing two frames.

Starting Applications in Frames

To open an application in the frame, press F3 and type in the command to start it (such as “firefox”). If you want to open up a terminal, you can press just F2 instead and F1 for man page. There are even short cuts to use SSH (F4), edit files (F5) and view text files (F6).

If you have tried starting multiple applications, you’ll notice that they will all open up to the frame that is in focus. Moving applications to the other frame can be done using the keyboard. For a number of the keyboard shortcuts, Ion uses the mod key. By default, the mod key is set to the alt key. If you do not like this, you can configure Ion to use a different key.

Moving Between Windows

Switching between the windows in the same frame is done by pressing mod + k  n (That is, press mod and k keys simultaneously. Let go of the k key, but keep holding the mod key. Then press n while still holding the mod key).

Moving Windows to Other Frames

Using a single frame is not a good utilisation of the available screen space. In Ion, moving an application to another frame requires you to “tag” it first. To tag an application, bring the application to focus and pressing mod + t. A mark is placed at the top corner of the title bar to show that it has been tagged.

A tagged title bar.

A title bar with a "tagged" mark in the top right corner.

Pressing mod + t again will remove the tagging. It is possible to have multiple windows tagged simultaneously. This is particularly helpful when you want to move multiple windows

Attaching Windows

Once the window the window is tagged, move horizontally to the adjacent frame with mod + tab. To move vertically, use mod + n or mod + p. Pressing mod + a will prompt you for the name of the window to attach to the frame. If you want to place all of the tagged windows to the frame, you can simply use mod + k a (like before, press mod + k then mod + a, without letting go with the mod key).

Reorganising Your Frames

Ion allows you to reorganise your frames, however you want. First, to resize a frame, press mod + r and then use arrow keys to make the frame grow. Windows can be maximised horizontally (mod + k h) and vertically (mod + k v). To further split the current frame, use mod + k s for horizontal splits. To delete the current frame, use mod + k x.

Workspaces

Finally, Ion support for multiple workspaces (similar to having multiple desktops). Workspaces are created using the F9 key. Before one is created, it will prompt you for a name for the workspace. If you enter the name of an existing workspace, it will go to that one instead. You can also switch between workspaces by holding the mod key and pressing a numeric key.

Verifying Using a Certificate Store

Posted by: kahgoh on: 15 February, 2009

An certificate store can be used to hold multiple CA certificates. It is used
for verification purposes, when you have multiple CA certificates, but you
do not necessarily know which of those CA certificates signed the
certificate. When verifying the certificate, OpenSSL will look for the CA
certificate or the chain in the store.

Setting up the store programatically involves allocating memory for the
store via X509_STORE_new and then loading certificates into it. There
are two ways of placing the certificates into the store – by loading and
adding each individual certificate or supplying the location of CA
certificates. For this tutorial, we’ll load each certificate programatically.

 1 void verifyCertificate()
 2 {
 3   X509 *cert = loadCert("cert.pem");
 4   X509_STORE *store = X509_STORE_new();
 5
 6   loadToStore("cert-1.pem", store);
 7   loadToStore("cert-2.pem", store);
 8   loadToStore("cert-3.pem", store);
 9

The listing for loading the certificate into the store will be shown later.
Verification is performed using a store context. Setting up a context
involves allocating space for a store context and initialising it.

10   // Create the context to verify the certificate.
11   X509_STORE_CTX *ctx = X509_STORE_CTX_new();
12
13   // Initial the store to verify the certificate.
14   X509_STORE_CTX_init(ctx, store, cert, NULL);
15
16   X509_verify_cert(ctx);
17
18   X509_STORE_CTX_cleanup(ctx);
19   X509_STORE_CTX_free(ctx);
20   X509_STORE_free(store);
21   ctx = NULL;
22   store = NULL;
23 }
24

The third parameter to X509_STORE_CTX_init, cert, is the
certificate that is going to be verified. The call to X509_verify_cert
should also return the value one, if verification succeeds.

Adding a certificate to the store requires the certificate to be read first.

25 void loadToStore(std::string file, X509_STORE *&store)
26 {
27   X509 *cert = loadCert(file);
28   if (cert != NULL)
29   {
30     X509_STORE_add_cert(store, cert);
31   }
32   else
33   {
34     std::cout << "Can not load certificate " 
35       << file << std::endl;
36   }
37 }
38
39 X509 *loadCert(std::string file)
40 {
41   FILE *fp = fopen(file.c_str(), "r");
42   X509 *cert = PEM_read_X509(fp, NULL, NULL, NULL);
43   fclose(fp);
44   return cert;
45 }

The process of adding the certificate should be self-explanatory from the listing.