Ancient Programming

What I encounter in my software part of life is in danger of being commented upon here

Archive for the 'how to' Category

Animating the drag drop example

Posted by Jacob von Eyben on 9th April 2012

As an update to my original ios drag drop post I have added an animation to the snap back to original position.

The changes is made to the DragContext.m file where the snapToOrignalPostion is changed to look like the following:

- (void)snapToOriginalPosition {
    [UIView animateWithDuration:0.3 animations:^() {
        CGPoint originalPointInSuperView = [_draggedView.superview convertPoint:_originalPosition fromView:_originalView];
        _draggedView.frame = CGRectMake(originalPointInSuperView.x, originalPointInSuperView.y, _draggedView.frame.size.width, _draggedView.frame.size.height);
    } completion:^(BOOL finished) {
        _draggedView.frame = CGRectMake(_originalPosition.x, _originalPosition.y, _draggedView.frame.size.width, _draggedView.frame.size.height);
        [_draggedView removeFromSuperview];
        [_originalView addSubview:_draggedView];

First we animate the dragged object back to the original position (in the super view containing all drag objects and drop areas). When the animation is completed, we change the superview.

Posted in animation, how to, ios, ipad, iphone, mac, objective-c | 1 Comment »

Drag and drop between multiple UIViews in iOS

Posted by Jacob von Eyben on 5th April 2012

This is an example showing how to drag and and drop UIViews between other UIViews in iOS.

Illustrates the drag and drop UIView stack

Illustrates the drag and drop UIView stack

The example is broken into the following four and a half step.

Example broken into steps
1. register a UIPanGestureRecognizer to be able to get drag panning events  (in our case drag events).
2. detect if the panning started above the view we would like to drag.
3. move the view according to the panning - which means removing the object from the view we would like to drag it from.
4. when dragging ends, drop the view onto the view below the dragged object.
4.a. optionally reset the dragged object, if the object is dragged onto a view which we don’t consider as a valid drop view.

In my example I have created a more or less generic DragDropManager, which is responsible for actually handling the UIViews objects we allow to drag ‘n drop and the UIVeiws we allow to drop onto.

Step 1
The manager registers the draggable objects and drop areas and takes care of detecting when a object should be dragged and dropped. This is done by receiving pan events from the UIPanGestureRecognizer. I recommend registering the gesture recognizer to a UIView having a frame covering the entire drag and drop area, because if you bind the recognizer to the actual draggable objects, you will loose the pan sequence as soon as you change super view for the dragged object (and changing super view is the hole point of dragging objects between UIViews).

@implementation DragDropBetweenViewsViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    _viewA = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 200)];
    [_viewA setBackgroundColor:[UIColor greenColor]];
    _viewA.tag = 1;
    _viewB = [[UIView alloc] initWithFrame:CGRectMake(0, 220, 320, 200)];
    [_viewB setBackgroundColor:[UIColor yellowColor]];
    _viewB.tag = 2;

    [[self view] addSubview:_viewA];
    [[self view] addSubview:_viewB];
    //[[self view] addSubview:_viewB];

    //add elements to drag and drop
    UIView *dragDropView1 = [[[UIView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)] autorelease];
    UIView *dragDropView2 = [[[UIView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)] autorelease];
    [_viewA addSubview:dragDropView1];
    [_viewB addSubview:dragDropView2];
    [dragDropView1 setBackgroundColor:[UIColor redColor]];
    [dragDropView2 setBackgroundColor:[UIColor blueColor]];
    NSMutableArray *draggableSubjects = [[NSMutableArray alloc] initWithObjects:dragDropView1, dragDropView2, nil];
    NSMutableArray *droppableAreas = [[NSMutableArray alloc] initWithObjects:_viewA, _viewB, nil];
    _dragDropManager = [[DragDropManager alloc] initWithDragSubjects:draggableSubjects andDropAreas:droppableAreas];
    [draggableSubjects release];
    [droppableAreas release];

    UIPanGestureRecognizer * uiTapGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:_dragDropManager action:@selector(dragging:)];
    [[self view] addGestureRecognizer:uiTapGestureRecognizer];
    [uiTapGestureRecognizer release];

Step 2
The manager switches on the different states of the UIPanGestureRecognizer and detects if a panning  starts on one of our dragSubjects. If so we store the DragContext containing the dragged view and the starting point (to be able to snap back to the offset in case the drag ends outside a drop zone). At the same time we change superview for the dragged object, by attaching it to the UIView spanning the entire area. This is done to ensure our UIView is shown above all other subviews and hence is visible during the entire drag drop session.

Step 3
During the drag process we simply move the object according to the coordinates of the UIGestureRecognizer.

Step 4
When the panning ends (the UIGestureRecognizer is in state UIGestureRecognizerStateEnded), we check to see if the dropped view is above any registered drop areas. If so, we add the dragged UIView as a subview of the detected drop area.

Step 4.a.
If we don’t recognize a valid drop area beneath our dragged view, we snap the dragged UIView back to its original superview and position.

The DragManager code can be seen here:

@implementation DragDropManager {

    NSArray *_dragSubjects;
    NSArray *_dropAreas;
    DragContext *_dragContext;

@synthesize dragContext = _dragContext;
@synthesize dropAreas = _dropAreas;

- (id)initWithDragSubjects:(NSArray *)dragSubjects andDropAreas:(NSArray *)dropAreas {
    self = [super init];
    if (self) {
        _dropAreas = [dropAreas retain];
        _dragSubjects = [dragSubjects retain];
        _dragContext = nil;

    return self;

- (void)dealloc {
    [_dragSubjects release];
    [_dragContext release];
    [_dropAreas release];
    [super dealloc];

- (void)dragObjectAccordingToGesture:(UIPanGestureRecognizer *)recognizer {
    if (self.dragContext) {
        CGPoint pointOnView = [recognizer locationInView:recognizer.view]; = pointOnView;

- (void)dragging:(id)sender {
    UIPanGestureRecognizer *recognizer = (UIPanGestureRecognizer *) sender;
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan: {
            for (UIView *dragSubject in _dragSubjects) {
                CGPoint pointInSubjectsView = [recognizer locationInView:dragSubject];
                BOOL pointInSideDraggableObject = [dragSubject pointInside:pointInSubjectsView withEvent:nil];
                NSLog(@"point%@ %@ subject%@", NSStringFromCGPoint(pointInSubjectsView), pointInSideDraggableObject ? @"inside" : @"outside", NSStringFromCGRect(dragSubject.frame));
                if (pointInSideDraggableObject) {
                    NSLog(@"started dragging an object");
                    self.dragContext = [[[DragContext alloc] initWithDraggedView:dragSubject] autorelease];
                    [dragSubject removeFromSuperview];
                    [recognizer.view addSubview:dragSubject];
                    [self dragObjectAccordingToGesture:recognizer];
                } else {
                    NSLog(@"started drag outside drag subjects");
        case UIGestureRecognizerStateChanged: {
            [self dragObjectAccordingToGesture:recognizer];
        case UIGestureRecognizerStateEnded: {
            if (self.dragContext) {
                UIView *viewBeingDragged = self.dragContext.draggedView;
                NSLog(@"ended drag event");
                CGPoint centerOfDraggedView =;
                BOOL droppedViewInKnownArea = NO;
                for (UIView *dropArea in self.dropAreas) {
                    CGPoint pointInDropView = [recognizer locationInView:dropArea];
                    NSLog(@"tag %li pointInDropView %@ center of dragged view %@", dropArea.tag, NSStringFromCGPoint(pointInDropView), NSStringFromCGPoint(centerOfDraggedView));
                    if ([dropArea pointInside:pointInDropView withEvent:nil]) {
                        droppedViewInKnownArea = YES;
                        NSLog(@"dropped subject %@ on to view tag %li", NSStringFromCGRect(viewBeingDragged.frame), dropArea.tag);
                        [viewBeingDragged removeFromSuperview];
                        [dropArea addSubview:viewBeingDragged];
                        //change origin to match offset on new super view
                        viewBeingDragged.frame = CGRectMake(pointInDropView.x - (viewBeingDragged.frame.size.width / 2), pointInDropView.y - (viewBeingDragged.frame.size.height / 2), viewBeingDragged.frame.size.width, viewBeingDragged.frame.size.height);

                if (!droppedViewInKnownArea) {
                    NSLog(@"release draggable object outside target views - snapping back to last known location");
                    [self.dragContext snapToOriginalPosition];

                self.dragContext = nil;
            } else {
                NSLog(@"Nothing was being dragged");

The DragContext containing the dragged view and the original position and view

#import "DragContext.h"

@implementation DragContext {

    UIView *_draggedView;
    CGPoint _originalPosition;
    UIView *_originalView;
@synthesize draggedView = _draggedView;

- (id)initWithDraggedView:(UIView *)draggedView {
    self = [super init];
    if (self) {
        _draggedView = [draggedView retain];
        _originalPosition = _draggedView.frame.origin;
        _originalView = [_draggedView.superview retain];

    return self;

- (void)dealloc {
    [_draggedView release];
    [_originalView release];
    [super dealloc];

- (void)snapToOriginalPosition {
    [_draggedView removeFromSuperview];
    [_originalView addSubview:_draggedView];
    _draggedView.frame = CGRectMake(_originalPosition.x, _originalPosition.y, _draggedView.frame.size.width, _draggedView.frame.size.height);

Room for improvements
- animations should be added to show more smooth look and feel.. This blog post demonstrates how to add animations to the snap back to orignial position.
- Consider the visible order of the views when selecting draggable UIView, if multiple draggable UIViews is stacked upon each other.

Posted in how to, ios, ipad, iphone, objective-c | 18 Comments »

Extend UITabBarController with an arrow marker

Posted by Jacob von Eyben on 18th September 2011

I have seen a couple of iPhone apps using an UITabBarController having an arrow showing just above the selected UITabBarItem as an extra visual pointer to the current visible view. At the same time the arrow moves animated between the items as the user selects them.

I decided to try implement the same effect and I have shared my solution here.

The solution is made generic enough to handle any number of UITabBarItems in the UITabBarController and basically what it does is:

  • In the viewDidAppear selector, the arrow is places above the first element. This is done by calculating the size and location (also known as the CGRect) of the first UITabBarItem. Then a new UIImageView is created and positioned centered and above the UITabBarItem. Again some math is used to find the offset to use for the newly created UIImageView
  • In the didSelectItem a transition is used to animate the movement of the arrow between the items as they are selected.

My CustomUITabBarController.h and CustomUITabBarController.m files looks like this:

@interface CustomUITabBarController : UITabBarController {
    UIImageView *_imageView;

The actual implementation looks like follows:

@interface CustomUITabBarController ()
@property(nonatomic, retain) UIImageView *imageView;

@implementation CustomUITabBarController

@synthesize imageView = _imageView;

- (CGRect) rectForItem:(UITabBarItem *)item {
    NSUInteger itemsInTabBar = [self.tabBar.items count];

    CGSize itemSize = CGSizeMake(self.tabBar.frame.size.width / itemsInTabBar, self.tabBar.frame.size.height);
    //find current selected item index
    int currentIndexSelected = 0;
    //if the item is nil, we keep the index at zero (selects the first element)
    if (item != nil) {
        for (int i = 0; i < itemsInTabBar; i++) {
            UITabBarItem *currentItem = [self.tabBar.items objectAtIndex:(NSUInteger) i];
            if (currentItem == item) {
                currentIndexSelected = i;
    //construct the rect that defines the current selected item
    return CGRectMake(lrint(currentIndexSelected * itemSize.width), itemSize.height, itemSize.width, itemSize.height);

- (CGRect)getRectForImage:(UIImage *)markerImage andTabPosition:(CGRect)itemRect {
    CGFloat windowHeight = [UIScreen mainScreen].bounds.size.height;
    CGRect markerImageRect = CGRectMake(itemRect.origin.x + lrint(itemRect.size.width / 2) - lrint(markerImage.size.width / 2), windowHeight - itemRect.size.height - markerImage.size.height, markerImage.size.width, markerImage.size.height);
    return markerImageRect;

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];  //To change the template use AppCode | Preferences | File Templates.
    UIImage * markerImage = [UIImage imageNamed:@"tabMarker.png"];
    CGRect firstItemRect = [self rectForItem:nil];
    CGRect markerImageRect = [self getRectForImage:markerImage andTabPosition:firstItemRect];
    _imageView = [[UIImageView alloc] initWithFrame:markerImageRect];
    _imageView.image = markerImage;
    [self.view addSubview:_imageView];

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    CGRect selectedItemRect = [self rectForItem:item];

    [UIView beginAnimations:@"move tabMarker" context:nil];
    [UIView setAnimationDuration:0.3f];
    _imageView.transform = CGAffineTransformMakeTranslation(selectedItemRect.origin.x,0);
    [UIView commitAnimations];

Posted in how to, ios, iphone, mac, objective-c | No Comments »

Logging sql statements and parameters using hibernate

Posted by Jacob von Eyben on 12th November 2009

If you need to log sql statements using hibernate you can turn debug on for the org.hibernate.sql logger.
That will log all sql statement, but the actual parameter values will not be logged.

To log the values bound to the hibernate prepared statements, you can turn on trace for the org.hibernate.type logger.

Unfortunately (apparently because of perfomance) the value of the org.hibernate.type logger is evaulated once in a static block, and cached, see:

That prevents you from turning the log on and off during runtime using a simple jsp page like the log4jAdmin.jsp. Note that if it were possible you still had to add trace to the page as debug is currently the lowest value.

Of course there must be a reason why the hibernate implementation are caching the value of the org.hibernate.type logger, but I believe it is still valuable to be able to turn on sql logging with parameters at runtime.

For that purpose I came across the logDriver. A simple database driver written by Ryan Bloom, that is wrapping an existing jdbc driver.

To use the logdriver all you have to do is set the driver and connection url as follows:


Now you can turn on logging by setting the net.rkbloom.logdriver logger to debug.

Posted in how to, java | 1 Comment »

Howto setup smooth ssh access

Posted by Jacob von Eyben on 24th October 2008

Everytime I have a new machine or a new ssh access to setup I forgot how to configure the access so I don’t have to type the username each time (if I login with a different user).
At the same time I would like to use a private rsa key. So here goes a note to myself and other scatter brains :-)

Instead of always have to type username and password like this:

[jeyben@machine ~]$ ssh
Last login: Fri Oct 24 16:31:03 2008 from somewhere
[username@servername ~]$

I would like to just do the following:

[jeyben@machine ~]$ ssh ancientprogramming
Last login: Fri Oct 24 16:31:03 2008 from somewhere
[username@servername ~]$

Create and use a public/private key pair


$ ssh-keygen -t rsa
$ scp ~/.ssh/


$ cat ~/ >> .ssh/authorized_keys

Modify .ssh/config

Host ancientprogramming
  User <username>
  Port 22
  LocalForward 3307 localhost:3306 (setup a localforward for the default mysql port)

Posted in how to, ssh | No Comments »

Automatically reconnect to NAS under Mac OS X

Posted by Jacob von Eyben on 27th June 2008

Mac OS X doesn’t remount network drives when booted. You have to do this yourselves.

You can easily automate this by creating an application using the automator and add it to your login items.

Automator - create application

You automator script should contain two items:

  • Get Specified Servers
  • Connect to Servers

Save the script as an application and put it into login items for your user account. This will execute your small application each time you login and you should be reconnected to your NAS on startup.

Posted in how to, mac | No Comments »

How to create macros for maven-site-plugin

Posted by Jacob von Eyben on 5th June 2008

Many maven projects uses the maven site plugin to generate there documentation.

The maven-site-plugin uses the doxia to let authors write xdoc, apt and fml documents as the source for there project documentation. These written documents is processed by doxia to generate html and merged into the complete project site by the maven-site-plugin.

I found doxia and especially the apt language somehow lacking in functionality. I would like to use the syntaxhighlighter to be able to highlight code examples on the fixedformat4j project.

Doxia comes out-of-the-box with a small bunch of macros and you have the ability to write custom macros as well.

Custom macro

I wrote a simple macro based on the core snippet macro:


  Doxia :: syntaxhighlighter


Changes to the snippet plugin:

  public void execute(Sink sink, MacroRequest request)
      throws MacroExecutionException {
    System.out.println("ancientprogramming - running execute");
    String id = (String) request.getParameter("id");

    required(id, "id");

    String urlParam = (String) request.getParameter("url");

    String fileParam = (String) request.getParameter("file");

    String codeParam = (String) request.getParameter("code");

    required(codeParam, "code");

    URL url;

    if (!StringUtils.isEmpty(urlParam)) {
      try {
        url = new URL(urlParam);
      catch (MalformedURLException e) {
        throw new IllegalArgumentException(urlParam + " is a malformed URL");
    } else if (!StringUtils.isEmpty(fileParam)) {
      File f = new File(fileParam);

      if (!f.isAbsolute()) {
        f = new File(request.getBasedir(), fileParam);

      try {
        url = f.toURL();
      catch (MalformedURLException e) {
        throw new IllegalArgumentException(urlParam + " is a malformed URL");
    } else {
      throw new IllegalArgumentException("Either the 'url' or the 'file' param has to be given.");

    StringBuffer snippet;

    try {
      snippet = getSnippet(url, id);
    catch (IOException e) {
      throw new MacroExecutionException("Error reading snippet", e);

   sink.rawText("... syntaxhighlighter prefix ...");
   sink.rawText("... syntaxhighlighter postfix ...");

Note: wordpress obfuscates the above code where I wrote the syntax hightlighter pre and post fix. You can see what you actually should write at the syntaxhighligther project.

Use custom macro
To be able to use the macro you have to add your macro as dependency to the maven-site-plugin:


Now you can use the macro by writing the following in your apt files:


Change your site template
Before the the source can be highlighted in your documentation you should add the syntaxhighlighter javascript and stylesheets to your template.
See how to change your template here.

Posted in how to, java, maven | 1 Comment »

Best practise when handling tags and branches (using subversion)

Posted by Jacob von Eyben on 15th March 2008

This is the way I prefer tagging and branching my code when developing and releasing software. I use subversion but the overall guidelines can be applied by any versioning tool - say CVS.
I assume that you keep your source in the recommended structure:

  • trunk
  • tags
  • branches


Always use three digits to denote a release: major.minor.bugfix. ex: 1.2.0.

Name your trunk code like this: major.minor-SNAPSHOT, where major.minor denotes the next version to release. ex: The version in production is 1.2.0, you should name the trunk version 1.3-SNAPSHOT. I use snapshot to tell others that such a version is an arbitrary build along the way to a stable 1.3 release (The name ’snapshot’ is inherited from maven).


When releasing your code, you should tag the version you release by the version. This gives you a chance to always branch from that specific release if a bugfix is required. Ex: you 1.3-SNAPSHOT is ready to go into production. Tag a version by the name 1.3.0.
Even though some versioning tools allow you to commit to a tag, you should not do so. Tags is an image of the sourcecode at the release time!

At the same time you should change your trunk version t0 1.4-SNAPSHOT.


If your newly created release contains a bug that can’t wait to be fixed until your next trunk release, you should create a branch. Do so from your release tag.

You should name your branch like this: major_minor_bugfix, where major and minor is the same as the software in production. Ex: 1_3_bugfix.


I do not recommend having unmerged code on your branch for to long.
I suggest you you merge your software back to trunk for each fix you do. At least you should merge your branch back to trunk when your release a new version.

To assist you in this I suggest your commit message tells what revisions that is involved, - The revision from the branch and the revision on trunk.

Subversion commands

The following is the commands to use in subversion. I assume you use ssh to access subversion and the subversion repository is located at in the directory /var/subversion:

Tagging in subversion

$ svn copy svn+ssh:// \

Branching in subversion

Similar to tagging except the path.

$ svn copy svn+ssh:// \


I will split this into two cases. The case where you merge from the branch the first time and the following merges.

First merge from a branch

First you want to know what revision you are to merge from.That is the revision your branch was created at. You find that revision by executing the following command in your branch checkout:

$ svn log –stop-on-copy

That will list all your changes created on your branch since it was created. You can see the revision where your branch where created in the log output.

Knowing the revision you are ready to merge your changes. Change to a working copy of your trunk code and make sure your checkout is up to date by executing and findout the revision to merge into:

$ svn up

This will update your trunk copy and output the revision you are to merge into.
Now merge the changes by using the following command on your trunk working copy:

$ svn merge -r rev1:rev2 \

where rev1 equals the revision your branch was created and rev2 equals the revision on your trunk working copy.

Fix any conficts and commit your code. It is important that your commit message contains the to revisions you merged. I suggest you write the following. That message is important in later merges:

$ svn commit -m ‘Merged branches/1.0-bugfix rev1:rev2′

Following merges from branch

The next time you would like to merge, you execute the following in your working copy of your trunk code to find the revision to merge from:

$ svn log | grep -i merge

This assume that your commit message when merging contains the text merge - as we did in the first case.
The revision to use is the revision you merged into the last time +1.

Ex your log message looks something like this: ‘Merged project/brances/1_2_bugfix r1631:r1682 into head’, the revision to use is 1683.

With that version just repeat the steps from the ‘First merge from a branch’.

I suggest you read here to find more about branching and merging in subversion.

Posted in how to, subversion | 6 Comments »