Showing posts with label hackery. Show all posts
Showing posts with label hackery. Show all posts

Saturday, April 03, 2010

Controlling the Kokokaka Interactive Piano

Here's some fun I had with an afternoon hack session.

The start

To start, look at this video. Play with it. It's an interactive piano. Wait for the whole video to load, and then click the piano keys with your mouse. You'll see that clicking a key moves the video's position to the spot where that note is played. In other words, you get to play the piano on the YouTube video by clicking keys.



That was fun; I wanted to automate playing the piano with a script. Could I do it? Well, yes. For the most part.

Controlling the Mouse

This turned out to be rather difficult, and in the end I could not get it quite right. But it's good enough.

Since this was a Mac workstation, I assumed it would be an easy matter to get AppleScript to do this, but I gave up after about 45 minutes of trial and error. I couldn't even find an API, let alone a reliable one. (This also included a short foray into experimenting with the Automator. Nope, it wasn't going to work.)

I finally found an answer on Mac OSX Hints with a full example of how to build a command-line binary that positions and clicks the mouse.

The secret sauce of this example was the Quartz Events method CGPostMouseEvent.

Did it work? Yes. No. Not really. Calling ./click -x x -y y certainly sent the mouse to the correct position, but it didn't seem to actually generate the correct click event. Do you know what worked instead? Calling it twice. Yep.

./click -x x -y y ; ./click -x x -y y works.

Most of the time.

I tried all sorts of things, like creating delays in between the clicks, or delays between the mouse-down and mouse-up events. No luck. Anyway, this was the simplest correct solution. That's what they call elegance, you know: the simplest, correct solution. Doesn't feel like it.

I noticed CGPostMouseEvent was deprecated and replaced with the pair of methods CGEventCreateMouseEvent and CGEventPost. I replaced the code with the newer methods, which resulted in no reasonable change to the application. But I didn't switch back.

The major problems with this solution were not only that there could be a risk of skipping, it also, the browser seemed to get overwhelmed by these fake mouse events, enough so that the video would stop playing. The mouse click events would continue to be delivered, and the video would be repositioned in time to the correct spot, but the video was paused; so no music came out. The faster the music played, the more likely the video would halt. Too bad.

A final comment about mouse control. I found that this only worked with Safari. It didn't work well (or at all) with Firefox or Chrome.


// File: 
// click.m
//
// Compile with: 
// gcc -o click click.m -framework ApplicationServices -framework Foundation
//
// Usage:
// ./click -x pixels -y pixels 
//
// additional data found at
// http://stackoverflow.com/questions/2369806/simulating-mouse-clicks-on-mac-os-x-does-not-work-for-some-applications

#import <Foundation/Foundation.h>
#import <ApplicationServices/ApplicationServices.h>

// Read more: http://www.faqs.org/faqs/unix-faq/faq/part4/section-6.html#ixzz0k416qomt

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSUserDefaults *args = [NSUserDefaults standardUserDefaults];

  int x = [args integerForKey:@"x"];
  int y = [args integerForKey:@"y"];

  CGPoint pt;
  pt.x = x;
  pt.y = y;

  CGEventRef evt = CGEventCreateMouseEvent(
      NULL, kCGEventLeftMouseDown, pt, kCGMouseButtonLeft);
  CGEventPost(kCGHIDEventTap, evt);

  evt = CGEventCreateMouseEvent(
      NULL, kCGEventLeftMouseUp, pt, kCGMouseButtonLeft);
  CGEventPost(kCGHIDEventTap, evt);

  [pool release];
  return 0;
}

Finding positions

Now I had a relatively reliable procedure for generating mouse click events. Where should I click the mouse?

This was easy to solve. I put the browser in the upper left corner and used Grab to get a shot of the full screen. Then I loaded the image in Gimp and used the cursor position indicator. Given a full screen snapshot, the cursor position on the loaded screenshot image would correspond with a mouse position click event.

From there I could generate positions on the display that, when clicked, would generate the correct results.


my %points =  (
    toggle => [18, 580],
    c => [20, 500],
    cs => [40, 300],
    d => [80, 500],
    ds => [120, 300],
    e => [140, 500],
    f => [220, 500],
    fs => [240, 300],
    g => [280, 500],
    gs => [320,  300],
    a => [360, 500],
    as => [400,  300],
    b => [430, 500],
    C => [500, 500],
    Cs => [530, 300],
    D => [560, 500],
    Ds => [610, 300],
    E => [620, 500]
  );

Scripting the result

Coding up the controller wasn't very hard. I went through several versions, and settled on this:

#!/opt/local/bin/perl

use strict;

# system("gcc -o click click.m -framework ApplicationServices -framework Foundation");

my $tempo = 1;

sub _nap ($) {
 select undef, undef, undef, $_[0];
}

sub nap ($) {
 _nap($_[0] * $tempo);
}

sub note {
  my ($x, $y) = @_;
  system("./click -x $x -y $y");
  _nap .05;
  system("./click -x $x -y $y");
}

my %points =  (
    toggle => [18, 580],
    c => [20, 500],
    cs => [40, 300],
    d => [80, 500],
    ds => [120, 300],
    e => [140, 500],
    f => [220, 500],
    fs => [240, 300],
    g => [280, 500],
    gs => [320,  300],
    a => [360, 500],
    as => [400,  300],
    b => [430, 500],
    C => [500, 500],
    Cs => [530, 300],
    D => [560, 500],
    Ds => [610, 300],
    E => [620, 500]
  );

sub play($) {
  my @notes = split(/;/, $_[0]);
  foreach my $note (@notes) {
      my ($key, $duration) = split(",", $note);
      $duration = 1 unless defined $duration;
      print "$key-$duration- ";
      my $rpoint = $points{$key};
      print "$rpoint ";
      my @point = @$rpoint;
      print @point . $point[0] . $point[1] . "\n";
      note @point;
    nap $duration;
  }
}

sub scale {
 $tempo = .3;
 play ("E;Ds;D;Cs;C;b;as;a;gs;g;fs;f;e;ds;d;cs;c");
}

sub test() {
 $tempo = .2; 
 play ("c;d;e");
}

sub test2() {
 $tempo = .1; 
 play ("E;c;Ds;cs;D;d;Cs;ds;C;e;b;f;as;fs;a;g;gs");
}

sub twinkle {
  $tempo = 1;
  play("c;c;g;g;a;a;g,2;f;f;e;e;d;d;c,2");
}

sub fur_elise {
  $tempo = .5;
  play(
  "E;Ds;E;Ds;E;b;D;C;a,3;c;e;a;b,3;e;gs;b;C,3;e;" .
  "E;Ds;E;Ds;E;b;D;C;a,3;c;e;a;b,3;e;C;b;a,4;" .
  "b;C;D;E,3;a;f;e;d,3;g;E;D;C,3;f;D;C;b,3;e;" .
  "E;Ds;E;Ds;E;b;D;C;a,3;c;e;a;b,3;e;C;b;a,4;");
}

my %songs = (
  scale => \&scale,
  twinkle => \&twinkle,
  test => \&test,
  test2 => \&test2,
  fur_elise => \&fur_elise,
);

my $song = $ARGV[0];
print $song;
my $rsong = $songs{$song};
&$rsong();

Notice that _nap is actually a call to the Perl builtin method 'select'? It's a bit of a hack I read about in a couple of places; this is one.

The final result

Did it work? You tell me!



Success!

Parting thoughts

It's too bad there was no easy way to get a reliable mouse click on the Safari browser. That would make such a difference.

Collecting this data from a script feels a little cheap. I'd much rather have a keyboard send events that control the video. Anyone who has a spare electronic keyboard and a couple of hours of spare time, let me know.

Monday, June 22, 2009

Patch Fragments, Redux

Sorry for those of you who have already read my patch fragment blog posts. I'm re-listing them in this post for the sake of the Planet Eclipse aggregator.

In short, an OSGi fragment is a bundle that attaches to a host bundle [1]. While patch fragments really aren't meant to be use to replace behavior in a host bundle [2], it's the most elegant hackish way to do just that.


The first blog post shows that I was able to make changes to all text editors using a patch fragment.
The second blog post hosts a screencast showing, step by step, how to build a patch fragment.
The third blog post shows the code required to create the effect from the first post.

So if you're coming here from Planet Eclipse, you may find these interesting.


[1] http://static.springframework.org/osgi/docs/1.1.0/reference/html/appendix-tips.html
[2] http://wiki.eclipse.org/FAQ_Can_fragments_be_used_to_patch_a_plug-in%3F

Friday, June 12, 2009

The Code For Two Margins


OK, two posts ago I showed that I could make a double-margin in an editor using Patch Fragments. One post ago I used a screencast to demonstrate the basics of writing your own patch fragment.

In this post I will show the code for the double margin.

While in the screencast I messed with org.eclipse.core.resources, for this case, I wrote a patch fragment for org.eclipse.ui.workbench.texteditor. It's my expectation that you have read those last two posts, since I'm only a specific subset here.

First I imported the org.eclipse.ui.workbench.texteditor plug-in, and made a bundle fragment that lived off it.

In the fragment, I created the java package org.eclipse.ui.texteditor, and copied the entire source file for org.eclipse.ui.texteditor.SourceViewerDecoratorSupport from the source project to the new fragment package.

After much searching, I found the thing in SourceViewerDecoratorSupport responsible for painting the margin. It's MarginPainter. Because MarginPainter implements IPainter and PaintListener I hoped writing a delegate that implemented those interfaces would work. e.g.

class TwoColumnMarginPainter implements IPainter, PaintListener {
  private final MarginPainter delegate;

  public TwoColumnMarginPainter(...) {
    this.delegate = new MarginPainter(...);
  }

  public void initializer() {
    delegate.initialize();
  }

  ...
}

Any method defined by the interfaces would be implemented just like initialize: delegate the call to the delegate MarginPainter.

Next, I replaced all uses of MarginPainter with TwoColumnMarginPainter, a grand total of two locations:

From To
private MarginPainter fMarginPainter; private TwoColumnMarginPainter fMarginPainter;        
private void showMargin() {
...
  if (fMarginPainter == null) {
    if (fSourceViewer instanceof ITextViewerExtension2) {
     fMarginPainter= new MarginPainter(fSourceViewer);
private void showMargin() {
...
  if (fMarginPainter == null) {
    if (fSourceViewer instanceof ITextViewerExtension2) {
      System.err.println("Black Magic!");
      fMarginPainter= new
TwoColumnMarginPainter(fSourceViewer, 20)
;

The part where it prints "Black Magic!" was my cue during testing that the patch fragment was taking control of SourceViewerDecoratorSupport.

Once that worked, it was a matter of doubling up in my delegate. Here's the the final implementation of the painter, in full.

package org.eclipse.ui.texteditor;


import org.eclipse.jface.text.IPaintPositionManager;
import org.eclipse.jface.text.IPainter;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.MarginPainter;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;


public class TwoColumnMarginPainter implements IPainter, PaintListener {
  private final MarginPainter delegate;
  private final MarginPainter sibling;
  private final int offset;


  public TwoColumnMarginPainter(ITextViewer textViewer, int offset) {
    delegate = new MarginPainter(textViewer);
    sibling = new MarginPainter(textViewer);
    this.offset = offset;
  }


  // @Override
  public void setMarginRulerColumn(int width) {
    delegate.setMarginRulerColumn(width);
    sibling.setMarginRulerColumn(width + offset);
  }


  // @Override
  public void setMarginRulerStyle(int lineStyle) {
    delegate.setMarginRulerStyle(lineStyle);
    sibling.setMarginRulerStyle(lineStyle);
  }


  // @Override
  public void setMarginRulerWidth(int lineWidth) {
    delegate.setMarginRulerWidth(lineWidth);
    sibling.setMarginRulerWidth(lineWidth);
  }


  // @Override
  public void setMarginRulerColor(Color color) {
    delegate.setMarginRulerColor(color);
    sibling.setMarginRulerColor(color);
  }


  // @Override
  public void initialize() {
    delegate.initialize();
    sibling.initialize();
  }


  // @Override
  public void deactivate(boolean redraw) {
    delegate.deactivate(redraw);
    sibling.deactivate(redraw);
  }


  // @Override
  public void dispose() {
    delegate.dispose();
    sibling.dispose();
  }


  // @Override
  public void paint(int reason) {
    delegate.paint(reason);
    sibling.paint(reason);
  }


  // @Override
  public void paintControl(PaintEvent e) {
    delegate.paintControl(e);
    sibling.paintControl(e);
  }


  // @Override
  public void setPositionManager(IPaintPositionManager manager) {
    delegate.setPositionManager(manager);
    sibling.setPositionManager(manager);
  }
}

Between this post and the last one you should be able to reproduce the double-margin effect yourself. Let me know if you have any problems or interesting ideas.

Thursday, June 11, 2009

Screencast: Doing Unnatural Things with Eclipse Patch Fragments

In my previous blog post I showed screenshots of a proof-of-concept idea that took advantage of Eclipse Patch Fragments. Based on the original documentation I made this screencast to demonstrate the nuances. Enjoy.

Wednesday, June 10, 2009

Patching

Take a look at this editor window:

What do you see that's different about it? I'll tell you, there are two margin lines. Is this a new feature of the soon-to-be-released Eclipse Galileo? Did I write my own Java editor?

Nope!

I hacked Eclipse to make that second margin.

I added this because I really like having two margins: I consider the first one a 'warning track' indicator. I don't mind writing code longer than 80 characters, but will go to 100, and prefer to stay inside the warning track.

So, how did I do this? I used patch fragments. Some pages on the Eclipse wiki claim that Patch Fragments are a horrific misuse of Eclipse, and one actually taught me how to do it. (It missed one important point, though, that cost me about an hour. The page has been adjusted accordingly.)

Here's the best part, thanks to patch fragments, I was able to perform this surgery at exactly the right place. The same small piece of code (and really, this actual amount of code was shockingly small) provides two margins in any editor, such as the plain-ol text editor:

or the plug-in manifest editor.


Look, there are down-sides to doing this: if I plan to support this patch, I need to apply it with each release of Eclipse. But honestly, how likely do you think it would be for an enhancement like this to make it in to the release? Not very bloody likely.

This is purely a proof-of-concept, but I plan to finish this up and publish it as an EPL contribution.

In a subsequent blog post* I will document how I got it to work, but for now, I'll tell you: as a total hack, I changed about six lines of code in org.eclipse.ui.texteditor.SourceViewerDecorationSupport, and added a sibling class called org.eclipse.ui.texteditor.TwoColumnMarginPainter.

zx, thanks for the offer, I don't need the patch fragment tutorial! :-)

* Googlers, in the draft of this article I accidentally used "changelist" instead of "blog post". Apparently I do "subsequent changelists" a little too often. :)