<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Lqd&#039;s Journal</title>
	<atom:link href="http://lqd.hybird.org/journal/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://lqd.hybird.org/journal</link>
	<description>It&#039;s actually pronounced liquid!</description>
	<lastBuildDate>Fri, 02 Apr 2010 16:58:44 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Shizzle, a CSS selector engine for Java and Swing</title>
		<link>http://lqd.hybird.org/journal/?p=309</link>
		<comments>http://lqd.hybird.org/journal/?p=309#comments</comments>
		<pubDate>Fri, 02 Apr 2010 16:58:44 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=309</guid>
		<description><![CDATA[*tap tap tap* Is this thing on ?

Der Plan &#8211; Part one
I&#8217;d like to present another piece of the big UI puzzle I&#8217;m slowly putting together. Shizzle is a query engine for Java and Swing that supports the CSS selector syntax.
It started one or two years ago as a straight port of Sizzle (jQuery and [...]]]></description>
			<content:encoded><![CDATA[<p>*tap tap tap* Is this thing on ?<br />
<br/></p>
<h3>Der Plan &#8211; Part one</h3>
<p>I&#8217;d like to present another piece of the big UI puzzle I&#8217;m slowly putting together. Shizzle is a query engine for Java and Swing that supports the CSS selector syntax.</p>
<p>It started one or two years ago as a straight port of <a href="http://sizzlejs.com/">Sizzle </a>(jQuery and other libs&#8217; selector engine) to Java. More for fun than, say, because it&#8217;s a clever idea: it just isn&#8217;t.<br />
For fun, at some point I also started adding more selectors to Ben Galbraith and Dion Almaer&#8217;s <a href="http://code.google.com/p/swing-clarity/">Clarity</a>. In the end, when this became something I wanted to complete, I restarted from scratch, TDD style.<br />
<br/></p>
<h3>Why ?</h3>
<p>Querying allows you to remove member variables for inner components you rarely use. Just look at a Matisse-generated panel to see what I&#8217;m talking about.<br />
Shizzle shines used with composites (which I&#8217;ve already <a href="http://lqd.hybird.org/journal/?p=46">talked about</a>), and APIs tailored for chaining. Allowing you to have really concise, simple and expressive code, obviously very similar to what you do in jQuery. You&#8217;ll see some of this in the download, because I used it in the tests, but the main part has been removed so we have something to talk about next time!<br />
<br/></p>
<h3>How to use it</h3>
<p>We have a lot to talk about, most of CSS selectors are supported. The ones that aren&#8217;t follow the same rationale as Sizzle, they&#8217;re just <a href="http://ejohn.org/blog/selectors-that-people-actually-use/">not useful</a>. However, I sometimes went overboard and implemented some features and selectors that people will probably never use. </p>
<p>You use it like this. Create a Query like this <strong>new Query (&#8220;my awesome query&#8221;)</strong>, and call the <strong>matches()</strong> method with the containers you want to look into. That&#8217;s it.</p>
<p>I&#8217;ll quickly describe what Shizzle supports, if you want more comprehensive (and normative) explanations, the official W3C spec can be found at <a href="http://www.w3.org/TR/css3-selectors">http://www.w3.org/TR/css3-selectors</a>.<br />
<br/></p>
<h3>Supported features</h3>
<p><br/></p>
<h4>0 &#8211; Universal selector</h4>
<p>&#8220;<strong>*</strong>&#8221; matches everything!</p>
<h4>1 &#8211; Type selectors</h4>
<p>A query &#8220;<strong>Type</strong>&#8221; will match every Java object of the Type class. Note that it works on classes&#8217; short names (ie, no package) and that it does not take inheritance into account. It just checks if an object&#8217;s class has the same name, so &#8220;<strong>JComponent</strong>&#8221; won&#8217;t match JPanels and so on. Common examples include &#8220;<strong>JPanel</strong>&#8221; &#8220;<strong>JButton</strong>&#8221; &#8220;<strong>JLabel</strong>&#8221; and so on.</p>
<h4>2 &#8211; Id selectors</h4>
<p>JComponents can have a name, and this selector targets it. &#8220;<strong>#name</strong>&#8221; will match every component that has been named &#8220;name&#8221;. Since there can be more than one component with the same name, this query can return more than one result (which is not the case with HTML). In practice, it doesn&#8217;t change anything.</p>
<h4>3 &#8211; Style classes</h4>
<p>HTML has the concept of classes, a multivalued (usually space-separated) property that labels an element with a string, which you then style using CSS. Here this concept uses a client property (&#8220;HTk.style&#8221;) to store the class values (which I&#8217;ve dubbed style classes, because just talking about classes would be confusing). The query &#8220;<strong>.style</strong>&#8221; will match every component that has our client property where one of the style classes is &#8220;style&#8221;. As you&#8217;ll see in the code, HTk helps in adding, removing, and getting the value of this style property. You won&#8217;t have to manage it manually, don&#8217;t worry.</p>
<h4>4 &#8211; Attribute selectors</h4>
<p>These selectors involve properties (getters only) and their value for matching purposes. This one is rather complex as you can check whether a property exists or not, check its value or compare it, and so on. </p>
<p>The query &#8220;<strong>[property]</strong>&#8221; will match every object that has a readable property named &#8220;property&#8221; (ie a &#8220;getProperty&#8221; method). I&#8217;m guessing you won&#8217;t be using it that much.</p>
<p>Values can be checked too, like this &#8220;<strong>[name=id]</strong>&#8220;. Which show how we could describe the id selectors we talked about earlier, as attribute selectors checking the value of the &#8220;name&#8221; property, using the &#8220;getName&#8221; method on each component. The &#8220;=&#8221; is the first of many operators, checking of course the property has exactly the specified value.</p>
<p>There are some microsyntaxes and types are &#8220;automatically&#8221; converted, for that purpose I&#8217;ve built a class for conversion. I&#8217;ve followed Tim Boudreau&#8217;s <a href="http://weblogs.java.net/blog/2009/05/01/converting-objects-b-and-back-there-ought-be-library">pragmatic rules</a> about it (Dozer or Morph being way too complicated for what I needed here). You can compare floats to double and Strings to ints, and so on. Strings can be defined with single or double quotes, or, as just demonstrated, without quotes at all. You&#8217;ll see this in more (excruciating) detail in the unit tests.</p>
<p>[Aside: I've also included one example converter for Dates (eg "<strong>2009.12.01 12:45:12</strong>") , and a more realistic one converting colors (accepting diverse formats such as the hex style "<strong>#FF0000</strong>" "<strong>#FF0000FF</strong>" "<strong>0xFF0000</strong>" "<strong>0xFF0000FF</strong>" "<strong>#F00</strong>", constants in the Color class such as "<strong>red</strong>" or "<strong>RED</strong>" or "<strong>Color.red</strong>", and finally the ones we often see in CSS like "<strong>rgb(255,0,0)</strong>", "<strong>rgba (255, 0, 0, 255)</strong>", "<strong>Color.rgb (255, 0, 0)</strong>" or "<strong>Color.rgba (255, 0, 0, 255)</strong>" variations).<br />
I'm releasing this conversion "framework" (such a big word for one class) under the WTFPL, the <strong>Do Whatever The Fuck You Want Public License</strong>, in hopes we'll stop having so many of them]</p>
<p>Common examples would be &#8220;<strong>[visible= false]</strong>&#8221; (notice the boolean conversion) or &#8220;<strong>[background=blue]</strong>&#8221; (using the Color conversion we just talked about)</p>
<p>The next operators involve checking the value of a String property. &#8220;<strong>^=</strong>&#8221; checks whether the String property starts with the specified value, &#8220;<strong>$=</strong>&#8221; whether the property ends with the value, &#8220;<strong>*=</strong>&#8221; whether the property contains the value, &#8220;<strong>~=</strong>&#8221; whether the property has one word being the value, &#8220;<strong>|=</strong>&#8221; is used with hyphen-separated values.</p>
<p>Now we&#8217;ll leave the regular CSS world, and go into the ease of use world. There&#8217;s no &#8220;different&#8221; or &#8220;greater than&#8221; operator, to negate tests, they use a special pseudoclass, which we&#8217;ll see later. I&#8217;ve decided to add &#8220;<strong>!=</strong>&#8221; &#8220;<strong>></strong>&#8221; &#8220;<strong><</strong>&#8221; &#8220;<strong>>=</strong>&#8221; &#8220;<strong><=</strong>&#8220;, and these special Java ones &#8220;<strong>==</strong>&#8221; and &#8220;<strong>!==</strong>&#8221; (the &#8220;<strong>=</strong>&#8221; ending up using equals, where &#8220;<strong>==</strong>&#8221; is the &#8220;same as&#8221; operator and uses the regular == in Java. It happens this is not that useful by the way, it&#8217;s one of those times where I&#8217;ve already said I went overboard). The comparison operators use the Comparable interface, so you&#8217;ll be able to make queries with comparisons for any class that implements it.</p>
<p>Common examples are checking the bounds or location of a component &#8220;<strong>[x<=10.5]</strong>&#8221; and the likes.</p>
<p>While I was at it, I decided to throw in support for client properties here. So while we&#8217;ve been talking about attribute selectors for properties, know that the same applies to client properties. &#8220;<strong>[foo=bar]</strong>&#8221; will match any component that has a &#8220;foo&#8221; client property with a &#8220;bar&#8221; value.</p>
<h4>5 &#8211; Pseudo classes</h4>
<p>Pseudoclasses are usually used to check some specific state. While there are some predefined states in HTML/CSS such as &#8220;<strong>:checked</strong>&#8221; &#8220;<strong>:enabled</strong>&#8220;, there aren&#8217;t any Swing specific yet. What I did is add support for boolean properties as pseudoclasses. &#8220;<strong>:visible</strong>&#8221; is equivalent to &#8220;<strong>[visible=true]</strong>&#8221; and thus, will match any component whose <strong>isVisible()</strong> method returns true.</p>
<p>There&#8217;s also other selectors using the pseudoclasses syntax, but they have their own semantics, so they really are apart.</p>
<h4>6 &#8211; Multiple selectors</h4>
<p>Now that we&#8217;ve seen the most common selectors it&#8217;s time to talk about the fact that they can be combined. &#8220;<strong>JPanel#details</strong>&#8221; combining a type selector for JPanels and an id selector for the &#8220;details&#8221; name. Depending on the selector you could have some of the same type. Other examples could be &#8220;<strong>JPanel#link[visible=false]</strong>&#8220;, &#8220;<strong>[x=10][y=20][width=30][height=40]</strong>&#8220;, &#8220;<strong>[name=id][opaque=false]</strong>&#8220;, &#8220;<strong>.style.style2</strong>&#8221; and so on.</p>
<h4>7 &#8211; Position selectors</h4>
<p>Position selectors involve checking the index of the component, and allows you, when combined with other selectors, to ask for the first element (&#8220;<strong>:first</strong>&#8220;), like the first JPanel of the UI (&#8220;<strong>JPanel:first</strong>&#8220;), or the last one (&#8220;<strong>:last</strong>&#8220;), or the 5th one (&#8220;<strong>:eq(5)</strong>&#8221; or &#8220;<strong>:nth(5)</strong>&#8220;) or every other one (&#8220;<strong>:even</strong>&#8221; and &#8220;<strong>:odd</strong>&#8220;), or why not the ones after the 4th element (&#8220;<strong>:gt(4)</strong>&#8220;) or before it (&#8220;<strong>:lt(4)</strong>&#8220;), or all the ones between two values (&#8220;<strong>:range(2, 5)</strong>&#8220;). Those are coming from jQuery, they don&#8217;t exist in CSS.</p>
<h4>8 &#8211; Structural pseudo classes</h4>
<p>Similar to position selectors, structural pseudo classes are a little richer, as they apply to elements in regards to their parents, the number of other children they have, etc.</p>
<p>&#8220;<strong>:first-child</strong>&#8221; and &#8220;<strong>:last-child</strong>&#8221; will only match components that are the first and last child of their parents.<br />
&#8220;<strong>:only-child</strong>&#8221; matches only elements that don&#8217;t have any siblings.<br />
&#8220;<strong>:nth-child()</strong>&#8221; is used for matching the index, like these simple selectors &#8220;<strong>:nth-child(1)</strong>&#8221; or &#8220;<strong>:nth-child(odd)</strong>&#8221; or &#8220;<strong>:nth-child(even)</strong>&#8220;. It&#8217;s also possible to use a <strong>2n+a</strong> formula: &#8220;<strong>:nth-child(2n)</strong>&#8221; are all the children with an even index, &#8220;<strong>:nth-child(2n+1)</strong>&#8221; match the odd ones, &#8220;<strong>:nth-child(-n+2)</strong>&#8221; matches the first 2 children, &#8220;<strong>:nth-child(3n)</strong>&#8221; matches every 3rd child. Look at the tests to see some more concrete examples.</p>
<h4>9 &#8211; Special pseudoclasses</h4>
<p>There are two other pseudoclasses, namely &#8220;<strong>:has</strong>&#8221; and &#8220;<strong>:not</strong>&#8220;. </p>
<p>&#8220;<strong>:has()</strong>&#8221; helps you match components having children matching a specific rule, for example &#8220;<strong>:has(JPanel)</strong>&#8221; matches any component that has a child that matches the &#8220;JPanel&#8221; rule, any container having at least a JPanel child will match this rule.</p>
<p>The &#8220;<strong>:not()</strong>&#8221; reverses results of a specific rule, for example &#8220;<strong>:not(JPanel)</strong>&#8221; will match any component that is not a JPanel. In CSS it&#8217;s interesting to ahve because there&#8217;s only affirmative checking on attributes for instance. There&#8217;s some specifics in CSS, you can&#8217;t have a complex selector inside, like another :not. I decided not to bother with these, so you can go wild and nest 15 :not if you want.</p>
<h4>10 &#8211; Combinators</h4>
<p>While you can combine selectors just by adding them together, you can also combine groups of selectors.</p>
<p>The simplest combinator is a space character &#8221; &#8220;. It&#8217;s the descendant combinator, so you can have components matching a rule, who also have descendants (or parents, depending on how you look at it) matching another rule. &#8220;#parent #match&#8221; will match any component named &#8220;match&#8221; that has an ascendant named &#8220;parent&#8221;. </p>
<p>The child combinator &#8220;>&#8221; is used for immediate parents and children (whereas descendants and ascendants go anywhere in the component tree). &#8220;<strong>JPanel > JLabel</strong>&#8221; will match any label that has a JPanel parent. &#8220;<strong>JPanel > .style2 > JLabel</strong>&#8221; will match any JLabel having a parent with the &#8220;style2&#8243; style class, which in turn has a parent that is a JPanel.</p>
<p>The adjacent sibling combinator &#8220;+&#8221; is used to test the component immediately preceding the one being tested. &#8220;<strong>JLabel + JPanel</strong>&#8221; will match any JPanel that has a JLabel sibling immediately preceding it in any parent.</p>
<p>The general sibling combinator &#8220;~&#8221; is similar but applies to any preceding sibling, not just the one immediately preceding the component being tested. &#8220;<strong>JLabel ~ JPanel</strong>&#8221; will match any JPanel having a JLabel sibling before him, regardless of its position.</p>
<p>Adding &#8220;,&#8221; is equivalent to creating another query and doing an union of the two result sets. &#8220;<strong>JLabel,JPanel</strong>&#8221; will match JLabels and JPanels. &#8220;<strong>:not(JLabel,JPanel)</strong>&#8221; won&#8217;t match any JLabel or JPanel. And so on.</p>
<p>Looking at the unit tests you&#8217;ll be able to see real Swing panels and components being created and queried (and with a nice &#8220;<strong>JPanel.HPanel#h1[name^=h] > JPanel:not(.HPanel):nth-child(2) JLabel.HLabel[name^=l][visible!=true][text*=Hello]:only-child:first-child:last-child</strong>&#8221; query for instance)</p>
<p><br/></p>
<h3>License</h3>
<p>Since I ported some of Sizzle&#8217;s regular expressions, I&#8217;ve included its BSD license. Shizzle itself also is released under BSD, as usual.</p>
<p><br/></p>
<h3>Next steps</h3>
<p>This project definitely needs more documentation and tutorials.<br />
Right now, there&#8217;s very little error handling at the query syntax level, and definitely needs to be improved.</p>
<p>I&#8217;d also probably add a visual tool to test queries on a live UI some time in the future.</p>
<p>The performance could be enhanced, even if it&#8217;s good enough for my uses. Right now the whole Swing UI is flattened into a list, which is then checked for matches. The matching could be done while traversing the tree for most of the selectors, so there&#8217;s another nice improvement to memory usage that could be done here. The queries could be cached, and modified or invalidated when components are dynamically added, etc</p>
<p>I&#8217;m currently looking at scenegraphs, to replace Scenario. So far I&#8217;ve &#8220;ported&#8221; (hacked) Pulpcore to the desktop (removing the dependencies on Applets), and tried Piccolo2d. So expect Shizzle to be ported to one of those, or some other scenegraph, when I find the one I want to use.</p>
<p>Maybe it&#8217;d be interesting to port it to other platforms such as Android, or to other toolkits, like SWT or Pivot.</p>
<p>Of course, extensibility for parsing, microsyntaxes, operations and so on, is definitely something that I&#8217;ll do too.</p>
<h3>Conclusion</h3>
<p>Shizzle comes with quite extensive unit tests (which wasn&#8217;t that hard, since it was TDD&#8217;ed), that show you running examples, and make up a little for the lack of docs. I also &#8220;ported&#8221; a subset of the official CSS selector spec test suite, with all this I&#8217;m confident it works nicely.<br />
You can also look at a subset of HTk, a set of API wrappers which we&#8217;ll talk about in more detail in the future, for now let&#8217;s just say it contains methods to help set the name, the style classes, etc (the HComponents themselves are not added to the Swing hierarchy, they&#8217;re just builders of JComponents).</p>
<p>Here&#8217;s the <a href="http://lqd.hybird.org/files/ui/shizzle-0.1-src.zip">zipped Eclipse project</a>.</p>
<p>I&#8217;d love to get feedback on this, you can find me at <a href="http://twitter.com/lqd">twitter.com/lqd</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=309</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uncovering an invisible button on the iPhone, with sound</title>
		<link>http://lqd.hybird.org/journal/?p=292</link>
		<comments>http://lqd.hybird.org/journal/?p=292#comments</comments>
		<pubDate>Wed, 16 Dec 2009 16:52:18 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[interaction]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mockup]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=292</guid>
		<description><![CDATA[I&#8217;d like to explain the idea I had last summer on how to &#8220;add a new button&#8221; to the iPhone, thanks to the microphone, as an interaction design mockup. I initially wanted to do that in an article dedicated to interaction design strategies for iPhone games, but it doesn&#8217;t look I&#8217;ll be able to do [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d like to explain the idea I had last summer on how to &#8220;add a new button&#8221; to the iPhone, thanks to the microphone, as an interaction design mockup. I initially wanted to do that in an article dedicated to interaction design strategies for iPhone games, but it doesn&#8217;t look I&#8217;ll be able to do that soon, so here goes the 1st of them. It&#8217;ll be clearer than 140 characters at a time on <a href="http://twitter.com/lqd">twitter</a>.</p>
<p>I thought about this a week after <a href="http://labs.laan.com/blog/2009/08/sonar-ruler-iphone-app-measure-with-sound/">Sonar Ruler</a> (the site was down when I tried to find a link, so here&#8217;s a demo on <a href="http://vimeo.com/6068060">Vimeo</a>) was released. This app made me think of other uncommon uses of the microphone. While using your voice has become a 1st class citizen in the interaction landscape (or close to it) probably starting with Science-Fiction a while back, I was trying to focus on sound in an indirect way, as a side-effect or by-product of the interaction. </p>
<p><br/></p>
<h3>The &#8220;Sonic Button&#8221;</h3>
<p>I never really thought about a name for this, but SonicButton and sonic tapping is probably descriptive enough (suggestions are welcome and appreciated).</p>
<p>The concept, as the name and the title of this post suggest, is using the microphone to listen to the sound of interactions with the iPhone, effectively turning it into a button: listen to taps, and especially taps made using a nail. The great thing about this is it works anywhere on the phone: front, back or the sides, the whole surface is available for the interaction. In turn, this allows great flexibility for the users, any finger can be used, in any orientation, you handle the phone regularly and use the finger you want to tap wherever you want. You can even tap with the nail on the screen itself, and not register a finger touch. As I said, the *whole* surface is available for you to use. </p>
<p>Of course, this is applicable to any phone and not just the iPhone, provided it has a microphone (pretty much all of them except the ones used by mimes) usable from an API (far less common). Android comes to mind as an additional platform, and surely you could name others. However, I only tested the microphone behavior on my iPhone 3G.</p>
<p><br/></p>
<h3>Mechanics</h3>
<p>While I&#8217;m not an iPhone or Android developer (yet) I did the best I could to test this theory by using existing applications. I used the <a href="http://www.faberacoustical.com/products/iphone/soundmeter/">SoundMeter</a> app to see how the microphone reacted to this interaction, under different conditions: portrait and landscape orientations, holding the phone with one and two hands, for regular use and games (where the grip is usually different), and in calm and noisy environments.</p>
<p>The typical sonic tap will obviously manifest itself as a short spike in the audio stream. Depending on the noise conditions, where and how you tap (with the nail or a fingertip), the intensity will of course be different, but in a calm room, hitting with a nail, I usually get between 25 and 35 dB for a soft-to-regular-strength sonic tap.</p>
<p>Something interesting happens using a &#8220;game grip&#8221; (your hands, thumbs and 1st fingers pretty much covering every side of the phone). The microphone is obstructed and picks up sounds at a high level (80-90 dB, out of, what I think the maximum is, around 105dB or so). Even here, with the microphone completely blocked, a sonic tap registers a spike in I believe the same way as people hear their own voice, even when they block their ear canals with their fingers: with sound travelling through the skull rather than from the outside in (note: my biology knowledge is pretty limited, so this might be wrong). Here I think the sonic tap travels inside the phone and the mic picks it up.</p>
<p>This is actually something that can be taken advantage of, in a noisy room, where a sound spike coming from the environment would be considered a sonic tap, you can block the microphone deliberately and still use this interaction.</p>
<p><br/></p>
<h3>Analysis</h3>
<p>To my eyes, the most interesting part of this is the fact that it allows to interact with something other than the screen. Even though it&#8217;s only one button, the fact that it&#8217;s a button that can be used without obscuring the view is really nice.</p>
<p>It&#8217;s also a discrete and simple event, and in that sense would be far easier to use than the accelerometer for instance (which depending on the use case can be seen as rather imprecise, and breaking down when using it for two dimensions). It&#8217;s not that it&#8217;s hard to tilt your phone, it&#8217;s that it&#8217;s hard to tilt just the amount you need to do what you want, (said amount is also app-dependent), whereas a tap is a tap, in every app. Sure, the variety of the environments, of the implementation thresholds can turn this into the same non-deterministic behavior, but a strong sonic tap should generate a high-enough spike to be detected in most implementations. We&#8217;ll see.</p>
<p>Just like with the accelerometer, a problem is that it would probably require calibration to match the user&#8217;s behavior and environment, even though sensible defaults could be chosen regarding strength, and an app could detect a noisy environment and take appropriate action, be it changing thresholds or notifying the user to switch his grip for instance.</p>
<p>It&#8217;s also about as hard to discover as it gets, otherwise I wouldn&#8217;t be talking about it. However, I don&#8217;t feel discoverability to be such an issue, the usual in-app &#8220;tutorial&#8221; solves those kind of problems with ease most of the time, and even if it&#8217;s rare to see them in utility apps rather than games, any app with a different enough UI offers one. </p>
<p>The initial (really short) learning curve passed, I feel an interaction like this one would be fun and useful, and should offer a great experience to the users, which is what the iPhone spirit is all about.</p>
<p>I would see this being used in immersive apps (like games and such) for local consumption only, ie I don&#8217;t think it would be useful to broadcast the sonic tap event over the network, other than maybe if you wanted to do a mini-drums simulator that&#8217;d work remotely from the back of your phone, or a human metronome, who knows. </p>
<p><br/></p>
<h3>The possible interactions</h3>
<p>The most common way to hold a phone is (in my own experience, and limited testing with real people) in portrait mode, with one hand. This can be seen as a vertical handling of the position called &#8220;the dealer&#8217;s grip&#8221; in the card-playing world. In this position, the 1st finger is almost not used for holding, resting most of the time close to the lock button (using the left hand; this button is not located here by chance) or on the back (and probably not lower than the Apple logo) while the others are touching the sides. This is the simplest case to hit the SonicButton, on the back side of the phone. It&#8217;s also possible to use the 2nd finger, however it&#8217;s not as comfortable, so it didn&#8217;t look as good a choice in my tests (I only tested with a handful of people, though). As I said before, letting the users choose will end up naturally on the most comfortable choice and position for them, in practice I found this to be pretty powerful.</p>
<p>Using both hands in portrait mode can happen when the user is typing, on the web or writing a mail or SMS, and only if the user is skilled at typing on the virtual keyboard (the small number of beginners I know type approximatively the same way, by holding the phone with one hand and either hitting the keyboard with the holding hand&#8217;s thumb or with the 1st finger of the other hand. The latter being more common, and this also held true for the ones having a phone with a physical portrait keyboard, sliding up or down, or with clamshell phones). In this position, a very interesting situation comes up where you can still use your thumbs but hit the glass *under* the screen, at the left or right of the Home button. I did say you could sonic tap anywhere. </p>
<p>In landscape mode, people rarely use it with a single hand, but it can happen. If the user&#8217;s holding the phone and not interacting with it, reading or watching a movie, his fingers aren&#8217;t in front of the screen and he can sonic tap on the back. If he&#8217;s interacting with the phone, it&#8217;s usually with the thumb and here a sonic tap to the sides of the screen around the top speaker or home button, or once again on the screen with the nail only, is doable. In practice, I didn&#8217;t see this behavior in my limited testing. Still works if you do use it that way.</p>
<p>When they use the phone with both hands in landscape mode, the grip matters (in blocking the microphone) but basically you can sonic tap with your thumbs on the sides of the screen on the front, or with your 1st fingers on the back of the phone. Using the &#8220;game grip&#8221; you can also use your 1st fingers on the top edge, or depending on the user&#8217;s dexterity the 2nd fingers on the lower part of the back side, close to the bottom edge.</p>
<p>As with regular taps, you can have a multiple sonic taps, even though I suspect filtering will modify the way to detect the following taps.</p>
<p>What&#8217;s also interesting with this, is it allows eye-free interactions like a real physical button, even though the environment noisiness could be an issue, a double tap might be the gesture to use. It&#8217;s not that interesting in practice because it&#8217;d mean an app would have to run when the phone is in a pocket, unlocked, and with the microphone and sound processing the battery probably wouldn&#8217;t last long. </p>
<p><br/></p>
<h3>Implementation</h3>
<p>As this is an interaction concept, the only pointers I could give would be the Audio Queue Services inside CoreAudio, for the iPhone, and also <a href="http://www.stephencelis.com/2009/03/02/now-i-just-need-an-audience.html">Stephen Celis&#8217;</a> <a href="http://github.com/stephencelis/sc_listener">sc_listener</a> which seems to be the perfect candidate for the job.<br />
I don&#8217;t know if you can get a live stream on Android, but the <a href="http://developer.android.com/guide/topics/media/index.html">AudioRecord, MediaRecorder</a>, and this <a href="http://www.benmccann.com/dev-blog/android-audio-recording-tutorial/">tutorial</a> certainly could be a start.</p>
<p><br/></p>
<h3>In conclusion</h3>
<p>This sonic button is closely related to Chris Harrison&#8217;s <a href="http://www.chrisharrison.net/projects/scratchinput/">ScratchInput</a>: I actually read his project page when it came out, and I remembered it and looked it up again after coming up with this. The mechanics are roughly the same and use the exact same principles, but in ScratchInput the listening to scratching on surfaces is done via custom hardware (because scratching is a lot softer than tapping), and could be adapted into mobile phones, turning them into passive listening devices (that can broadcast data over the local WiFi network) used to turn a regular surface into a scratch-enabled one; whereas in what I presented here, the interaction is focused on taps and happening on the phone itself (and not a wall or desk) and the input data is actively used by the iPhone and its apps to enable new features. So in my mind, they&#8217;re really close and part of the same interaction family, but I wouldn&#8217;t say they&#8217;re exactly the same.</p>
<p>I&#8217;d love to get feedback on the concept, you can me find a <a href="http://twitter.com/lqd">twitter.com/lqd</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=292</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mockup for short links on Twitter</title>
		<link>http://lqd.hybird.org/journal/?p=239</link>
		<comments>http://lqd.hybird.org/journal/?p=239#comments</comments>
		<pubDate>Tue, 15 Dec 2009 12:25:14 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[design]]></category>
		<category><![CDATA[mockup]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=239</guid>
		<description><![CDATA[And now for something a little different: most if not all of my posts here have been code-related even though a big part of my work and interests are design-related, something with which you might be familiar if we&#8217;re friends on twitter
Recently Chris Messina offered a suggestion on how Twitter could better integrate short links.
]]></description>
			<content:encoded><![CDATA[<p>And now for something a little different: most if not all of my posts here have been code-related even though a big part of my work and interests are design-related, something with which you might be familiar if we&#8217;re friends on <a href="http://twitter.com/lqd">twitter</a></p>
<p>Recently Chris Messina offered a suggestion on how Twitter could better integrate short links.</p>
<p><a href="http://www.flickr.com/photos/factoryjoe/4176724903/"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/chrismessinaproposal.png" alt="Chris&#039; proposal" title=""Chris&#039; proposal" width="536" height="199" class="size-full wp-image-246" /></a></p>
<p><br/></p>
<p>This prompted me to <a href="http://www.flickr.com/photos/48188729@N00/4185522194/">summarize my thoughts</a> on the problem they introduce in the UX. The Twitter Fan wiki <a href="http://twitter.pbworks.com/Short-Links">page on short links</a> explains those technical and design problems, and lists current practices and alternative solutions, including the one I&#8217;ll present here today. Even though I&#8217;ll offer several different ideas, they&#8217;re sequential in my mind. I see them as different versions of a solution, as part of the design process, rather than different solutions. </p>
<p>For reference, this is how Twitter displays links at the moment. <br/><br />
<a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-original.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-original.png" alt="short links on Twitter right now" title="short links on Twitter right now" width="654" height="90" class="aligncenter size-full wp-image-252" /></a><br/><br/></p>
<p>The most obvious thing to do is integrate expansion on demand as exists on the Twitter search (ex-Summize) page. The version A is exactly that.<br/><br />
<a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-expandA.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-expandA.png" alt="expand Button version A" title="expand Button version A" width="673" height="90" class="aligncenter size-full wp-image-257" /></a><br/><br/></p>
<p>The version B is a modification I made to make the expansion process secondary (and it&#8217;s the one I use at the moment in our own unreleased client, but this will change).<br/><br />
<a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-expandB.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-expandB.png" alt="expand Button version B" title="expand Button version B" width="674" height="90" class="aligncenter size-full wp-image-259" /></a><br/></p>
<p>The expand buttons (possibly underlined) would be slightly transparent in order to blend in better but would have full opacity on mouse hover.<br />
However those 2 versions only show the information you&#8217;re looking for when you interact with the expand buttons. This interaction is pure excise.<br/><br/></p>
<p>So, the next version, &#8220;With Host&#8221;, adds feedforward on the short link by showing the host/domain it points to. It&#8217;s only slightly better, but offers reassurance if the site is one you trust and visit frequently.</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-withHost.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-withHost.png" alt="Showing the domain" title="Showing the domain" width="655" height="90" class="aligncenter size-full wp-image-261" /></a><br/><br/></p>
<p>However, in my mind short links are a hindrance to the experience and shouldn&#8217;t be a focal point in the tweet — the real links are actually more important in the message. The next version, &#8220;Inverting the polarity&#8221;, keeps the feedforward of the previous version, but shows more info and puts the expanded link in the tweet itself. The short link being relegated to the sideline here.<br/><br />
<a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-invertingPolarity.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-invertingPolarity.png" alt="The expanded link inline" title="The expanded link inline" width="668" height="90" class="aligncenter size-full wp-image-263" /></a><br/></p>
<p>I strongly think the expanded URL shouldn&#8217;t be shown fully here, the links people shorten are often huge; they would offer little added value (what can you tell from a 150-character link you couldn&#8217;t from a 100-character one), they&#8217;d mess up the layout, etc. So only the first X characters would be shown, say 20 or so as I used here, and an ellipsis if the whole URL was cut off.<br/><br/></p>
<p>Continuing in that direction, the last version &#8220;Bye-bye short link&#8221; removes the obscure short link from the main content altogether.</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-byebyeShortLink.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/shortlinks-byebyeShortLink.png" alt="Bye-bye ugly short link" title="Bye-bye ugly short link" width="657" height="90" class="aligncenter size-full wp-image-265" /></a><br/></p>
<p>In those last 2 versions, you could add an expand button (I originally designed the ellipsis to be this expand button but I feel it&#8217;d be a hard-to-hit target—even with more space between the link and the ellipsis, which is not shown here—but I don&#8217;t think we&#8217;d need one, for a simple reason. There already exists an interaction for knowing where a link points to: put the mouse cursor over it, and look in the browser&#8217;s status bar. Of course, just adding this to the other versions (including the one Twitter uses) would shed some light on the short link black hole, even though hijacking the status text like this has to take accessibility into consideration.</p>
<p>Of course, a tooltip window similar to Chris&#8217; could be another direction, however I feel that just using &#8220;link&#8221; could be seen as giving even less information than the already obscure short link.<br />
It could go really well with the &#8216;Bye-bye short link&#8217; design, where the tooltip window would show the original short link url (and who knows maybe also some stats, even though I suppose they&#8217;re probably only used by a tiny fraction of people)</p>
<p>I don&#8217;t feel the URL expansion being slow is a problem, provided it&#8217;s done *before* showing the tweet in the timeline. Be it on the twitter.com website or in a client, I believe users have no easy way to tell they received a tweet 30 seconds later than they were &#8220;supposed to&#8221; (this could be the maximum timeout allowed for the URL expansion to succeed). If the link wasn&#8217;t already expanded in the tweet (last 2 versions), the Summize style expansion would here be immediate.</p>
<p>Even though my personal opinion has no value compared to user testing, removing the short link altogether is my favorite :) These different versions all evolved into removing it, and this last version represents my current thoughts on the problem.</p>
<p>Shortly after I tweeted this, Chris came up with another redesign blending several ideas. I&#8217;m happy with the direction and feel we&#8217;re getting somewhere interesting.</p>
<p><a href="http://www.flickr.com/photos/factoryjoe/4185010345/"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/12/chrismessinaredesign.jpg" alt="Chris' redesign" title="Chris' redesign" width="500" height="375" class="aligncenter size-full wp-image-247" /></a></p>
<p>I&#8217;d love to get some feedback, tweet about this using the #shortlink hashtag. You can find me at <a href="http://twitter.com/lqd">twitter.com/lqd</a> </p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=239</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom GLSL/HLSL pixel shaders for Java2D, Swing &amp; JavaFX</title>
		<link>http://lqd.hybird.org/journal/?p=196</link>
		<comments>http://lqd.hybird.org/journal/?p=196#comments</comments>
		<pubDate>Tue, 01 Sep 2009 15:03:49 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[demo]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[decora]]></category>
		<category><![CDATA[scenario]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=196</guid>
		<description><![CDATA[Introduction
Welcome to part 2 of our experiments on hardware accelerated effects in Java. Today&#8217;s weather forecast: 70% chance of&#8230; pixel shaders.
Remember last time, when I said I wouldn&#8217;t probably do custom effects and would wait for Sun to provide it to us ? Well&#8230;
I lied.
Actually, I changed my mind, but let&#8217;s not argue semantics here [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Welcome to part 2 of our experiments on hardware accelerated effects in Java. Today&#8217;s weather forecast: 70% chance of&#8230; pixel shaders.</p>
<p>Remember <a href="http://lqd.hybird.org/journal/?p=165">last time</a>, when I said I wouldn&#8217;t probably do custom effects and would wait for Sun to provide it to us ? Well&#8230;</p>
<p>I lied.</p>
<p>Actually, I changed my mind, but let&#8217;s not argue semantics here :]</p>
<p>We&#8217;ll see two things in this article. First, we&#8217;ll generalize what we did last time and get something usable from plain Java2D, and use that in our Swing support classes. And secondly, I&#8217;ll show you how to make your own custom effects/pixel shaders in GLSL &#038; HLSL.</p>
<p>Before we start, a disclaimer: like a lot of the things I do around here, this is going to use some internal APIs, so 1) they might change in the future, 2) I might use them badly (as I think I did in the previous article, it should be cleaned up now hehehe) &#8211; 3) there are some things I don&#8217;t understand in the APIs, after all there&#8217;s so much I can do with undocumented bytecode and without the source really, 4) all this is possible thanks to an ugly hack I won&#8217;t bother explaining, because it&#8217;s not really interesting.</p>
<p>That being said, I did my best to hide the ugliness behind easy to use API. I can&#8217;t be sure this code will work in future releases of Decora, or if it would be doable to adapt it then, though. If that happens, let&#8217;s hope Sun provides an officially supported way for custom effects and pixel shaders (which could be as simple as giving access to decora&#8217;s compiler and JSL, as I said last time).</p>
<h3>Java2D &#038; Swing</h3>
<p>There are now 3 ways to use decora effects: 2 for Java2D, and one for Swing with help from JXLayer (which, of course, uses the Java2D ones).</p>
<p>The first one is DecoraEffectRenderer and allows you to draw an Image with an effect applied, on a specific Graphics. This class delegates rendering to some decora utility methods I found not long ago (and might not have been present in decora when I initially wrote this experiment, last december), and renders manually when those can&#8217;t be used (&#8220;context hijacking&#8221;, which I use in the JXLayer support &#8211; ie when applying effects on non Java2D-managed images). It contains 3 or 4 drawImage methods (that mirror the ones in Graphics2D). The second one is DecoraEffectImageOp, which as the name suggests is a BufferedImageOp implementation. Those two classes should help you use decora almost like you use Graphics and software effects today in Java2D, so pretty familiar territory for you if you&#8217;re reading these lines. The last class is the JXLayer DecoraLayerEffect, from last time, but now just uses a DecoraEffectRenderer internally.</p>
<h3>Custom effects / pixel shaders</h3>
<p>And now on to the good stuff. Even if the basic concept was easy to code after I got the idea on how to do it, the longest part was coming up with a coherent API I wouldn&#8217;t mind using, making sure it worked with GLSL, HLSL, on windows and linux (both using java 6), and so on (unfortunately i couldn&#8217;t test on a Mac, I have hopes it will work there, but I have no idea &#8211; I think the closest i can get to the Mac environment is java 5 under linux, but decora/JavaFX only run on java 6 there, since they rely on the RSL).</p>
<p>I also want to note the work I did here needs signing in webstart, a requirement I have high hopes of removing when Decora/JavaFX 1.2.1 is released, because of a bug that was recently fixed there. Unsigned webstart is not really a hard requirement for me, but it might be for you. In any case, the method I use for hijacking shaders into decora works unsigned; some files will need to be moved around, but I think that&#8217;s basically it. We&#8217;ll see how it goes when I can test it, and see if i&#8217;m right.</p>
<p>As I said last time, decora has a number of backends because it runs on quite a diverse set of platforms/hardware/software/gpu drivers/etc. What I did here is basically a small subset of what the decora compiler does: only for the gpu backends, and requires manual coding. With JSL you&#8217;d code a single file describing your effect, and have the compiler generate all the support classes; here we&#8217;ll need to do &#8220;everything&#8221; manually, and I&#8217;ve succeeded in making this task pretty small: one java file, and two pixel shaders, for OpenGL &#038; Direct3D &#8211; and of course one of those might be optional, depending on your target platform. For an effect called X, you&#8217;ll have in the same package X.java, X.glsl and X.obj (compiled from an HLSL file, using the fxc tool that comes with DirectX SDK)</p>
<p>Let&#8217;s see how to make a custom effect. We&#8217;ll stay at the global overview level, assuming you can read my code, samples and demos for down and dirty specifics if need be.</p>
<p>As JFXLayer has shown, we&#8217;ll need a class extending decora&#8217;s Effect. Here to create your custom effect, you&#8217;ll extend a helper class I did, called, you guessed it, CustomEffect. And it&#8217;ll basically look like this:</p>
<h3>Custom effect structure</h3>
<pre class="brush: java">
public class BlingBling extends CustomEffect&lt;BlingBling&gt;
{

// TODO: insert bling here

// ----- Bling controlling -----

@Override
protected Class&lt;? extends ShaderController&lt;BlingBling&gt;&gt; getShaderControllerClass ()
{
        return BlingBlingController.class;
}

public static final class BlingBlingController
   extends Abstract/*Stuff we&#039;ll talk about later*/ShaderController&lt;BlingBling&gt;
{
    public final void updateShader (BlingBling effect, Shader shader)
    {
        shader.setConstant (&quot;bling&quot;, effect.getBling());
    }
}
}
</pre>
<p>Hello less-readable-but-safer-because of/thanks to-generics code. Most of this will be generated by your IDE anyway.</p>
<p>The BlingBling java class is the effect implementation. You&#8217;ll create instances of this, pass them to DecoraEffectRenderer or DecoraLayerEffect, set parameters, variables and so on. The inner class is the shader controlling part, ie setting variables on the shader, whose values are coming from the BlingBling effect itself. Pretty clean and simple for something that&#8217;s quite complicated if you think about it really.</p>
<h3>Shader controlling and the shader itself</h3>
<p>The shader controlling is grouped by the number of samplers the shader uses: 0, 1 or 2 &#8211; because that&#8217;s the way decora does it. The shader controller will most of the time extend Abstract[NumberOfSamplers]ShaderController: AbstractZeroSamplerShaderController, AbstractOneSamplerShaderController, AbstractTwoSamplerShaderController. The whole hierarchy is more complex, there are other abstract classes and interfaces you can extend/implement, those are the ones that provide the most help, but you can read the code and figure this out yourself, it&#8217;s pretty simple.</p>
<p>Let&#8217;s start with what&#8217;s common between all of them, the shader structure itself. I won&#8217;t obviously explain anything about coding pixel shaders here, and only focus on what&#8217;s needed to use and create your own.</p>
<p>I&#8217;ll say that there&#8217;s more flexibility when using GLSL code &#8211; because they can be parsed, composed, and messed with at runtime, which is not easily doable with HLSL &#8211; and I&#8217;ve called this &#8220;prettify-ing&#8221; the shader. A &#8220;pretty&#8221; decora GLSL shader will look like this, a regular GLSL shader:</p>
<pre class="brush: java">
// bling related variables and samplers

void main()
{
 // bling computing using the mentioned variables and copious texture2D calls

 gl_FragColor = bling;
}
</pre>
<p>While a real decora GLSL shader actually looks like this:</p>
<pre class="brush: java">
uniform float jsl_pixCoordYOffset;
vec2 pixcoord = vec2 (gl_FragCoord.x, jsl_pixCoordYOffset-gl_FragCoord.y);
uniform vec2 jsl_posValueYFlip;

vec4 jsl_sample (sampler2D img, vec2 pos)
{
    pos.y = (jsl_posValueYFlip.x - pos.y) * jsl_posValueYFlip.y;
    return texture2D (img, pos);
}

// bling related variables and samplers

void main()
{
 // bling computing using the mentioned variables and copious jsl_sample calls

 gl_FragColor = bling;
}
</pre>
<p>As you can see there&#8217;s a little more boilerplate, and the helper classes basically turn the pretty GLSL shaders into the regular ones. Prettifiying GLSL shaders is optional (but is set to true by default), and also comes with a perk, you don&#8217;t have to tell the shader controller the names of the samplers (unless you want to or need to control the IDs), something you have to do with regular decora GLSL &#038; HLSL shaders.</p>
<p>The HLSL shader will look like this skeleton:</p>
<pre class="brush: java">

// bling related variables and samplers

void main (/* TEXCOORD0 UVs for each sampler */, in float2 pixcoord : VPOS,
   inout float4 color : COLOR0)
{
 // bling computing using the mentioned variables

 color = bling;
}
</pre>
<p>This is how you&#8217;d compile that last HLSL shader to an obj (you could use another file extension if you wanted to, like the more common .ps &#8211; but decora uses .obj and that would be mandatory for sandboxed access, so I&#8217;ve let it be the default): fxc /nologo /T ps_3_0 BlingBling.hlsl /Fo BlingBling.obj</p>
<p>Now you know why decora (and thus JavaFX) requires a graphics card that supports at least the Shader Model 3.</p>
<h3>*-sampler shaders</h3>
<p>Let&#8217;s look at the different types of supported shaders &#038; shader controllers, what they are useful for, and talk about the included samples, which will show you the exact pixel shader structure you need to follow here.</p>
<p>One-sampler shaders are probably the most common ones, as they represent the kind of effects used in image processing. I provided a sample effect, a basic clone of the SepiaTone decora effect, imaginatively called SepiaToneClone. [Abstract]OneSamplerShaderController offers a way to get the sampler&#8217;s name, and whether it is using bilinear or nearest neighbor filtering. To give you an idea, in Decora, the blur, brightpass, and color adjustment effects are all effects using one sampler effects. These shaders would be useful if you wanted to implement some image processing effects for instance, such as the ones you find in Jerry Huxtable&#8217;s jhlabs filter library.</p>
<p>Two-sampler shaders, most of the time either mix the two source images, or use one as parameters to apply an effect to the other input image. [Abstract]TwoSamplerShaderController also provides a way to get the samplers&#8217; name, and the filtering to use. Examples of these in Decora are the various Photoshop Blend modes and displacement map effects. I provided a sample effect for that too, which is a clone of the multiply blend mode. These shaders would be useful if you wanted to implement transitions effects for instance, such as the ones you can find in Jeremy Wood&#8217;s transitions/transitions2d library.</p>
<p>And lastly, zero-sampler shaders. These, I think, would be the kind of shaders you&#8217;d use for procedural textures, like the ubiquitous checkerboard or brick patterns, or the Mandelbrot/Julia fractals for instance, up to the more modern procedural shaders you see in some farbrausch productions (like .kkrieger/.theprodukkt), the game Spore, or the Substance Air tech from my compatriots Allegorithmic. In practice, however, and the reason why I just said &#8220;I think&#8221; is because you&#8217;d probably need UVs for anything worth looking at, and I&#8217;m not sure if that&#8217;s provided in decora here, since there are no zero-sampler effects in the whole library. That&#8217;s why I didn&#8217;t provide any sample here, and I started doing my own procedural shaders using one-samplers. So your mileage may vary here.</p>
<p>The java code for the effects, shader controllers &#038; glsl and hlsl shaders (provided in the zip at the end of this article) will probably need to be looked at in more detail to really be able to make a custom effect, but the basic principles have all been described here, and you should be good to go.</p>
<h3>Animayshion, man</h3>
<p>While the pixel shader support is blazing fast for static images/UIs, be sure to test your target platforms thoroughly if you&#8217;re intending to animate those effects, there&#8217;s a lot of image data moving from the cpu to the gpu and back here, complicated effects become slow on big images or live UIs because of that. With great power comes great responsiblity, as the great philosopher once said &#8211; or maybe it was spiderman, i&#8217;m not sure.</p>
<p>I think/hope that the Prism renderer, coming in the next JavaFX release, will solve that. The public info on this is that it will add image caches for any node in the scenegraph: those being on the gpu, animations and pixel shaders should be faster. I&#8217;m not sure however that it will allow custom shaders, I doubt it to be honest, and this is part of the reason I changed my mind and coded it myself, however bad and inefficient my code would be &#8211; taking into consideration the conditions under which I&#8217;m doing this. Plus, Flash (in a sense) and Silverlight already offer this, and I find this lacking in the Java world &#8211; Java2D/Swing, not JOGL obviously.</p>
<h3>JavaFX support</h3>
<p>As for JavaFX support, I&#8217;ll start with another disclaimer: I don&#8217;t do JavaFX script at all, so take this code with a pinch of salt; if anyone wants to improve it, or correct it because it&#8217;s most likely bad, let me know (not to mention I mostly succeeded in crashing the openjfx compiler with those 10 lines). It works like this, you do what&#8217;s needed for general java support, and also create a JavaFX class extending my javafx.scene.effect.custom.CustomEffect, to specify and control the custom java effect. This will allow you to use your JavaFX effect like the regular ones.</p>
<p>An example JavaFX effect using the SepiaToneClone sample effect:</p>
<pre class="brush: java">
package javafx.scene.effect.custom.sepia;

import javafx.scene.effect.custom.CustomEffect;

public class SepiaToneClone extends CustomEffect
{
    public var level : Float = 1.0 on replace
    {
        delegate().setLevel (level);
    }

    protected override function createDecoraEffect() : com.sun.scenario.effect.Effect
    {
        return new org.hybird.decora.effect.sepia.SepiaToneClone();
    }

    function delegate() : org.hybird.decora.effect.sepia.SepiaToneClone
    {
        return decoraEffect as org.hybird.decora.effect.sepia.SepiaToneClone;
    }
}
</pre>
<h3>Crappy demos</h3>
<p>I can&#8217;t write an article without demos, you know that by now. Unfortunately, they won&#8217;t be particularly impressive today, since the point of the article is to show how *you* could do pixel shaders. The sample effects I coded, being mostly clones of existing decora effects, won&#8217;t be really new obviously. In any case, here they are, the first one uses the decora renderer to apply a clone sepia color adjustment on a screenshot of the displacement map test demo I talked about on twitter.</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/09/ImageProcessingDemo.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/09/ImageProcessingDemo-150x150.png" alt="ImageProcessingDemo" title="ImageProcessingDemo" width="150" height="150" class="aligncenter size-thumbnail wp-image-220" /></a></p>
<p><a href="http://lqd.hybird.org/apps/demos/jfxlayer/0.2/ImageProcessing.jnlp"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/webstart.png" alt="Launch the Image Processing demo" title="Image Processing demo" width="88" height="23" class="size-full wp-image-153" /></a></p>
<p><br/></p>
<p>The second uses the JFXLayer decora effect and is once again a simplified version of JXLayer&#8217;s LockableDemo. Here, a gaussian blur &#038; the clone sepia color adjustment are applied on Swing UI when locking the panel, using the blend multiply clone.</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/09/SwingUIDemo.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/09/SwingUIDemo-150x150.png" alt="SwingUIDemo" title="SwingUIDemo" width="150" height="150" class="aligncenter size-thumbnail wp-image-221" /></a></p>
<p><a href="http://lqd.hybird.org/apps/demos/jfxlayer/0.2/SwingUI.jnlp"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/webstart.png" alt="Launch the Swing UI demo" title="Swing UI demo" width="88" height="23" class="size-full wp-image-153" /></a></p>
<p><br/></p>
<p>And the last one, is a JavaFX text label over a blue rectangle to which the sepia effect is applied. Clicking will lower threshold. Seriously impressive stuff, i expect George Lucas to call me for help on the next Star Wars, based purely on the aesthetic of this last one. True story.</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/09/JavaFXEffectDemo.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/09/JavaFXEffectDemo-150x79.png" alt="JavaFXEffectDemo" title="JavaFXEffectDemo" width="150" height="79" class="aligncenter size-thumbnail wp-image-222" /></a></p>
<p><a href="http://lqd.hybird.org/apps/demos/jfxlayer/0.2/JavaFXEffect.jnlp"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/webstart.png" alt="Launch the JavaFX Effect demo" title="JavaFX Effect demo" width="88" height="23" class="size-full wp-image-153" /></a></p>
<p><br/></p>
<h3>(Famous) Last words + Download</h3>
<p>Of course I wanted to provide more polished demos, with a GLSL editor to play with, for instance, but this article is already getting too long, and I don&#8217;t have any more time to make it shorter, or longer &#8211; I want to finish it quickly to keep my incredible one-post-a-month average.</p>
<p>Some time in the future we&#8217;ll probably see how to make a custom effect that&#8217;s actually useful, most likely from one of the &#8220;These would be useful if&#8221; ones I mentioned here, a transition for example. *Those* would be/will be worth demoing.</p>
<p>You can find the whole project <a href="http://lqd.hybird.org/apps/demos/jfxlayer/0.2/jfxlayer-0.2-src.zip">here</a>, with all the support classes, samples, shaders, etc (the whole shebang is under BSD as usual).</p>
<p>Till next time, take care. By the way, you should follow me on twitter <a href="http://www.twitter.com/lqd">here</a>.</p>
<p>PS: this is why I only post once a month, I think I actually aged while writing this 2500-word long article :]</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=196</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Hardware Accelerated Effects in Swing with JXLayer and Decora</title>
		<link>http://lqd.hybird.org/journal/?p=165</link>
		<comments>http://lqd.hybird.org/journal/?p=165#comments</comments>
		<pubDate>Wed, 08 Jul 2009 20:42:42 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[demo]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[decora]]></category>
		<category><![CDATA[scenario]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=165</guid>
		<description><![CDATA[Learn how to use Decora to add hardware accelerated effects to your Swing UIs, as usual with open source code and demos]]></description>
			<content:encoded><![CDATA[<p><strong>Update (August, 31st)</strong>: I released version 0.2 of this library, fixing a couple of problems, and adding the possibility of making your own custom pixel shaders. You can find the second part of this series on pixel shaders <a href="http://lqd.hybird.org/journal/?p=196">here</a>.</p>
<h3>The Olive Branch</h3>
<p>A lot has been said about Swing and JavaFX recently, in a seemingly unending flame war between fans of each side. Both have merits and flaws, and as you&#8217;ve seen over time, i&#8217;m advocating a 3rd way, which i decided to pompously call The Olive Branch for no reason whatsoever, which is using the best of both worlds.</p>
<p>The plan is to use, directly from java, scenario and decora -the graphics libraries that power the javafx runtime, and which i love probably more than my girlfriend, but don&#8217;t tell her (: &#8211; (btw if you don&#8217;t like crappy jokes, you better stop reading now, and grab a taco or something) . Of course, things have changed since their release, what was once an open source public API (albeit destined to change heavily) is now an internal proprietary one, which means danger, will robinson. So, the plan is to have the community build things that are so cool, and innovative, that Sun will allow us to do just that and make scenario/decora public and usable from java, as they said they would, like with a jnlp extension or something. I think when things have stabilized a little, they&#8217;ll get to it. But at the moment, i have succeeded in doing that, at a level of 2% (and i&#8217;ve mailed Sun telling them everything i&#8217;ve done with scenario in the last 18 months &#8211; which is quite a bit in retrospect). Let&#8217;s see if we can crank that baby up.</p>
<h3>Introducing jfxlayer</h3>
<p>I&#8217;ve started this a long time ago, i wanted to help people use scenario and decora in swing, not only in a pure scenario scene as with Scenile, but from regular, real world swing, because some tasks are better handled by scenario and decora, and vice versa. The best of both worlds. I never got around to releasing it because i haven&#8217;t gotten to a satisfying point in this endeavour (+ i&#8217;m lazy), i&#8217;ve just planned the whole shebang, and coded the first little step, how to use hardware accelerated decora effects in plain old swing. It&#8217;s like 30 lines of code, that i kept in sync with every JavaFX release. I&#8217;ll get to the other planned features eventually, in the meantime, here&#8217;s the result of this piece of work. Hopefully, it&#8217;s interesting enough for regular Swing java users, or more &#8220;exotic&#8221; ones, like them groovy folks (:</p>
<p>It&#8217;s almost nothing code and work-wise. However, this opens a *huge* realm of possibilities for swing apps, and i hope you&#8217;ll see that too.</p>
<p>The concept is simple: add decora&#8217;s effects to the BufferedImageOps effects that jxlayer allows.</p>
<p>Decora. OpenJFX. JXLayer. JFXLayer.</p>
<h3>Decora ?</h3>
<p>Decora is Chris Campbell&#8217;s baby, if you don&#8217;t know who that is, you can stop reading now, bye. This library is arguably the smallest, the easiest to use and most powerful one you&#8217;ll ever come across if you&#8217;re dealing with effects, image processing, and shaders. A decora effect is made with a JSL file (Java Shader Language) which is basically a mix between Java (in order to get/set parameters and control the effect) and GLSL/HLSL ie, a generic high level OpenGL/DirectX shader language. This JSL file is then &#8220;compiled&#8221; (by a code generation utility) into a specific effect for each supported backend. The backends are mutually exclusive branches of code that target a specific architecture/3D API, etc. Depending on your software and hardware configuration, decora will choose the backend that will perform the best on your computer, whether you&#8217;re on windows mac or linux for instance. You have a regular &#8220;software&#8221; backend in pure java, one using JNI, one targetting OpenGL, another one OpenGL ES2 for mobile devices, another one Direct3D, and one targeting Prism, the next gen JavaFX graphics renderer, which will allow 3D and more perf, which is about as far as everyone knows. Back in the open source decora days, i&#8217;ve also written a backend myself, which multithreaded the regular Java backend, so that effects would use all your available cpus/cores.</p>
<p>All that from one tiny JSL file, they really are small, check the old open source version you&#8217;ll see. For the user, it&#8217;s of course transparent, you create an instance of the effect you want, and use it, decora handles the rest behind the scenes.</p>
<p>Sure, there aren&#8217;t that many effects yet (in fact there haven&#8217;t been any new ones since it was released, the work is done on the architecture, perf, backends, for the existing effects, which is very logical if you think about it) compared to, say, what Jerry Huxtable offers in his jhlabs filters library. In practice, it&#8217;s enough, for instance you have blurs and shadows, a perspective effect (think coverflow), color transforms, etc and a way to mix and chain all of the effects. If we had access to the compiler (or if we reverse engineered and forward ported that to the open source version) we could add new effects, but it&#8217;s not the case anymore. I think it&#8217;s doable if you really want it, especially for GLSL shaders which&#8217;ll be very interesting once Prism is released, if the compiler isn&#8217;t available at that time. I haven&#8217;t felt the need to create new effects until this week where i needed a better displacement effect than the one provided. So we&#8217;ll see how it goes but i&#8217;m not planning on doing it anytime soon.</p>
<h3>How do i use it in swing ?</h3>
<p>Enough about decora. In your Swing app, use JXLayer, and use the JFXLayer effect bridge with stock decora effects. It&#8217;s very simple:</p>
<pre class="brush: java">
BufferedLayerUI ui = ...; // your regular JXLayer LayerUI
Effect decoraEffect = ...; // your regular decora effect
// like GaussianBlur, Bloom, DropShadow, etc
ui.setLayerEffects (new DecoraLayerEffect  (effect));
</pre>
<p>Compare that with using JOGL and pixel shaders directly as Romain did in the Filthy Rich Clients book (the sample is like 500 lines long, and which are mostly low level code for setting everything up for rendering, here it takes 5 at most, thanks Chris!)</p>
<h3>Demos. Finally! I&#8217;m as tired reading this awfully long blog post as you are writing it</h3>
<p>I know you&#8217;re all about demos and eye candy, and today, i have 3 of them for you. Not one, but three, and if you call right now with your credit card number, i&#8217;ll add a set of Ginsu2000 knifes for only 3 easy payments of 9.99$, they can cut a shoe, you know ?</p>
<p>Since this post is about hardware accelerated effects, you&#8217;ll obviously need a decent graphics card with up to date drivers.</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/07/basicdemo.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/07/basicdemo-150x150.png" alt="basicdemo" title="basicdemo" width="150" height="150" class="aligncenter size-thumbnail wp-image-176" /></a></p>
<a href="http://lqd.hybird.org/apps/demos/jfxlayer/basic.jnlp"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/webstart.png" alt="Launch the basic demo" title="Basic demo" width="88" height="23" class="size-full wp-image-153" /></a>
<p>The first one is pretty basic, it&#8217;s two buttons. Pushing each one starts an animation (using the same code that powers the eMotionBlur demo of last time) that progressively blurs the component (but remains live). The button on the left is using a jhlabs blur filter, while the one on the right is using decora&#8217;s one. At the default size, it&#8217;s really close, but maximize the window and you&#8217;ll see the difference, and possibly start to envision the possibilities this offers. Who knows maybe it can be used to power screen transitions (even though i&#8217;m still not fully satisfied with the perf yet &#8211; maybe Alexander Potochkin, or Dmitri Trembovetski can help us out here, pajalusta (or whatever it&#8217;s spelled in cyrillic (: &#8211; you&#8217;ll see it&#8217;s decent enough for me to release it) &#8211; Mark, you can keep us updated on that (:</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/07/lockabledemo.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/07/lockabledemo-150x150.png" alt="lockabledemo" title="lockabledemo" width="150" height="150" class="aligncenter size-thumbnail wp-image-177" /></a></p>
<a href="http://lqd.hybird.org/apps/demos/jfxlayer/lockable.jnlp"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/webstart.png" alt="Launch the LockableUI demo" title="LockableUI demo" width="88" height="23" class="size-full wp-image-153" /></a>
<p>The second one is a modified demo from the JXLayer distribution, using the LockableUI, here also you can compare blurs. On my machine it&#8217;s almost instantaneous with decora.</p>
<p><a href="http://lqd.hybird.org/journal/wp-content/uploads/2009/07/twimber2demo.png"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/07/twimber2demo-150x150.png" alt="twimber2demo" title="twimber2demo" width="150" height="150" class="aligncenter size-thumbnail wp-image-178" /></a></p>
<p><a href="http://lqd.hybird.org/apps/demos/jfxlayer/twimber2.jnlp"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/webstart.png" alt="webstart" title="Twimber2 demo" width="88" height="23" class="aligncenter size-full wp-image-153" /></a></p>
<p>And finally the 3rd one is a modified version of Twimber, my tiny twitter provider for Kirill&#8217;s great Amber project. I&#8217;ve hacked animated blooms, blurs, and color transforms into it in a matter of an hour, where it would have probably taken me days fiddling with jogl. Bear in my mind this demo is *heavy* with animated effects, and absolutely not optimized at all (for instance the repaints are too big, the effects target components that are too big, etc) and might run slowly (it does a little on my machine) or quite possibly crash your vm (which it does on another machine, probably a bug in my graphics card driver that crashes everything)<del datetime="2009-07-10T18:55:20+00:00">, plus there are some deadlocks somewhere between Amber and the latest releases of Trident, that i haven&#8217;t tried to remove, maybe Kirill can help us with that, if need be. If that happens, you can only close the webstart window by killing the process, sorry about that, guys.</del> Hopefully, we fixed the problem, it stll won&#8217;t be optimized though ^^</p>
<h3>Is it safe to use ?</h3>
<p>Sure, using internal APIs is going to be a pain in the neck, it already has been for me. But, all in all, Decora&#8217;s API did not change much in the last 18 months, and especially not the effects&#8217;. And as the saying goes, no pain no gain. Plus they work fine with JavaFX 1.2 and JFXLayer right now, you don&#8217;t have to use the next version if you don&#8217;t want to have to modify them.</p>
<h3>Downloads and source</h3>
<p><strong>Update (August, 31st)</strong>: As mentioned earlier, I released version 0.2 of this library, fixing a couple of problems, and adding the possibility of making your own custom pixel shaders. You can find the second part of this series on pixel shaders <a href="http://lqd.hybird.org/journal/?p=196">here</a>. I didn&#8217;t change the code linked here for archive purposes though.</p>
<p>You can find JFXLayer <a href="http://lqd.hybird.org/apps/demos/jfxlayer/jfxlayer-0.1.jar">here</a> (<a href="http://lqd.hybird.org/apps/demos/jfxlayer/jfxlayer-0.1-src.zip">zipped source project + demos</a>), and twimber2 <a href="http://lqd.hybird.org/apps/demos/jfxlayer/Twimber2-src.zip">here</a> (zipped source project).</p>
<p>Let me know what you think, if the demos run well, or whatever in the comments, or sooner on <a href="http://www.twitter.com/lqd">twitter</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=165</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Animation speed and dynamic motion blur in Swing with JavaFX&#8217;s Scenario</title>
		<link>http://lqd.hybird.org/journal/?p=147</link>
		<comments>http://lqd.hybird.org/journal/?p=147#comments</comments>
		<pubDate>Mon, 15 Jun 2009 17:21:09 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[demo]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[scenario]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=147</guid>
		<description><![CDATA[Introduction
In the last article about triggers, i mentioned a use case which was very interesting to me, and would allow handling the motion blur automatically in an animation. This pretty simple addition, as you&#8217;ll see, makes a big difference in the dynamism and realism of an animation. Let&#8217;s see how to do that. And of [...]]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>In the last article about triggers, i mentioned a use case which was very interesting to me, and would allow handling the motion blur automatically in an animation. This pretty simple addition, as you&#8217;ll see, makes a big difference in the dynamism and realism of an animation. Let&#8217;s see how to do that. And of course, there&#8217;s a hopefully cool demo+source that comes with it.</p>
<p>Speed (instantaneous speed) is easy to calculate: it&#8217;s a delta between two values, divided by the delta of time it took to get from the first to the second value. (We often think of the values in space, for motion, but this formula ca be applied to any dimension, since it relates to the speed of any change). Cue timing events, and all you have to do is find the difference between the last value of the property you&#8217;re animating and the current one, and the difference between the times at which the events occured.</p>
<pre class="brush: java">
float delta = Math.abs (currentValue - previousValue);
long deltaTime = elapsedTime - previousElapsedTime;

float speed = delta  / deltaTime; // speed per ms
</pre>
<p>I said it was going to be easy! Plus i&#8217;ve built a speedometer class to help you with statistics, filtering events, and calculating the speed.</p>
<p>Once you have the speed, you need to find a way to use it. What i wanted was a relationship between that speed, and the motion blur itself: the faster the animation, the bigger the motion blur radius.</p>
<p>We&#8217;ll tackle the specific speed trigger next time (because i thought about it a little more, and the concept is pretty powerful. Triggers shouldn&#8217;t be in an animation library but directly in the core libraries or in a ui tk, at the very least, so next time we&#8217;ll see what i came up with), today we&#8217;ll use a component of that equation to make a fully dynamic motion blur: we&#8217;ll use the delta values as a basis for the blur radius.</p>
<h3> Demo </h3>
<p>The demo looks like originally like this.</p>
<p><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/emotionblur-300x211.png" alt="The basic demo" title="emotionblur" width="300" height="211" class="size-medium wp-image-148" /></p>
<p>Not much going on. There&#8217;s a white surface on which the animations take place. It comes with 3 presets. Each preset launches an animation with a different duration and spline interpolator (which changes the speed for each one), the text goes from top to bottom. You can also click the surface, and the text will smoothly move there, motion blurred and all (look at the code to know how to calculate an angle involving a mouse click).</p>
<p>You&#8217;d be impressed by how fast a little animation goes; in the demo, some of them go from 0.3 to 29k+ pixels per second. Obviously with that much of a gap, it&#8217;s almost impossible to get to a good looking animation by hand coding and eye balling. I had to build a little editor to make the presets i just talked about. It&#8217;s activated by clicking the &#8220;animation editor&#8221; button, no kidding, and looks like this. </p>
<p><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/emotionblur-editor.png" alt="emotionblur-editor" title="emotionblur-editor" width="640" height="490" class="aligncenter size-full wp-image-149" /></p>
<p>The editor obviously allows you to change everything in the animation, from the text, its color (using jeremy wood&#8217;s colorpicker), font (using connectica&#8217;s font picker), the motion blur settings (used here by the play button, or when clicking on the white surface), to modifying the spline interpolator (using a slightly modified version of the one romain guy did in the timingframework, to adapt it to scenario and other things) by dragging the round anchors or using the template selector, and also allows you to see the actual graph representing the animation speed, if the animation were to be run with the current settings.</p>
<p>Try the demo, i think it&#8217;s cute, note however that hardware acceleration is going to be a must-have here. There&#8217;s really no way you can animate a 60px radius blur effect smoothly and easily without it<br/><br/> <a href="http://lqd.hybird.org/apps/demos/eMotionBlur/eMotionBlur.jnlp"><img src="http://lqd.hybird.org/journal/wp-content/uploads/2009/06/webstart.png" alt="webstart" title="webstart" width="88" height="23" class="alignnone size-medium wp-image-153" /></a></p>
<p>Download the source (zipped eclipse project) <a href="http://lqd.hybird.org/apps/demos/eMotionBlur/eMotionBlur-src.zip">here</a>. The stuff i wrote is under BSD as always.</p>
<p>PS: The demo is using the scenario library that powers JavaFX. I&#8217;ve used the recently released version 1.2, which should work on all platforms, but i&#8217;ve only tested it under windows and linux so your mileage may vary. The demo&#8217;s name was in direct relation to the mythical 4th preset (which you can see in the screenshots but only try if you download the code), blurring emotions as well as pixels on screen, you can think of that as poetry if you will.</p>
<p>My own emotions were actually blurred too when updating to v1.2, since a lot of things i relied upon in the scenario framework since its public release 18 or so months ago, were either moved to fx script or removed altogether. I&#8217;m slowly bringing them back to life, piece by piece, i&#8217;ll make a post about using scenario 1.2 in java in the near future, and maybe win the 500$ sun is offering for their latest blog challenge in the process hehehe (:</p>
<p>Let me know what you think here or on <a href="http://twitter.com/lqd">twitter</a>.<br />
See ya.</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=147</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Swing event triggers for Trident animations</title>
		<link>http://lqd.hybird.org/journal/?p=129</link>
		<comments>http://lqd.hybird.org/journal/?p=129#comments</comments>
		<pubDate>Thu, 21 May 2009 10:19:20 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[trident]]></category>
		<category><![CDATA[triggers]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=129</guid>
		<description><![CDATA[Helper classes, ported from the AnimationFramework, saving precious lines of code and fingertips skin, to start, stop and reverse your Trident animations when specific events occur
]]></description>
			<content:encoded><![CDATA[<h3>Trigger happy ?</h3>
<p>Starting and stopping animations is usually related to events occuring somewhere in your ui. Writing those event listeners can be verbose and tedious at times. <a href="http://graphics-geek.blogspot.com/">Chet Haase</a> (one of the great, we miss you buddy) solved this problem in his <a href="https://timingframework.dev.java.net/">TimingFramework</a> animation library by providing a small core of extensible classes dealing with events: triggers (example <a href="https://timingframework.dev.java.net/source/browse/timingframework/demos/src/org/jdesktop/animation/timing/examples/Triggers.java?rev=1.4&#038;view=markup">here</a>).</p>
<p>They allow you to say: start this timeline when the user interacts with this button, or start this timeline when the mouse enters that component and reverses it when it exits, and so on.</p>
<p>While testing <a href="http://www.pushing-pixels.org/">Kirill&#8217;s</a> <a href="http://kenai.com/projects/trident">Trident</a> library, i thought this feature could be nice to have, so i ported Chet&#8217;s trigger code over to support it. </p>
<h3>Meet the cast</h3>
<p>Triggers are useful for one-shot events, like action events, but some events have an &#8220;opposite&#8221; event (pressing and releasing the mouse, entering and leaving a component, etc). The good thing is you can create an &#8220;autoreverse&#8221; trigger that will play the timeline backwards when this opposite event occurs: the values will smoothly be animated back to their original value. This is great for hover animations for instance.</p>
<p>Almost all of the original triggers have been ported except for the ones that didn&#8217;t make sense in this new context (TF uses triggers on animations to group them, in sequence or in parallel &#8211; eg start this animation when this one stops &#8211; and Trident supports that use case with timeline scenarios, so i didn&#8217;t feel they were needed here, feel free to comment on those)</p>
<p>Specifically, the supported event triggers are:</p>
<ul>
<li>Mouse triggers: enter, exit, press, release, click</li>
<li>Action triggers: supporting actionPerformed</li>
<li>Focus triggers: gain, loss</li>
</ul>
<h3>The How</h3>
<p>In the zip file linked at the bottom, you&#8217;ll find the simplest Trident demo modified to show how you&#8217;d use triggers. With that, the javadoc and the simple API, everything should be self explanatory.</p>
<p>Here is the one liner you just need to write to have a hover animation &#8211; while the mouse is over a button.</p>
<pre class="brush: java">
MouseTrigger.addTrigger (button, timeline,
    MouseTriggerEvent.ENTER, true);
</pre>
<p>And here&#8217;s the one starting a timeline when the button is pushed.</p>
<pre class="brush: java">
ActionTrigger.addTrigger (button, timeline);
</pre>
<p>Pretty simple. Thanks Chet ! (:</p>
<p>In the future, it might be possible to have triggers apply automatically to the object you&#8217;re animating. I&#8217;m not sure you can get that object back from the timeline right now, but it could be interesting to have for this very reason, and also to have callbacks that know about the main object without needing to give it to them (saves some code for repaints for instance). We&#8217;ll see with Kirill about that.</p>
<h3>Extensibility, and porting existing triggers</h3>
<p>Triggers are definitely an interesting concept, and the better thing is they can be extended easily. Maybe one could need triggers for other events. Feel free to ask, or do it yourselves (and maybe we&#8217;ll backport them to TF too, then).</p>
<p>For instance triggering animations on mouse wheel or drag and drop events, property changes, or maybe virtual events resulting from other changes. Those could be really useful for saying: start this animation when the mouse dragged this widget more than 10 pixels to the left, or my favorite (kinda hard to do at the moment, but i&#8217;m working on it) fade in and grow the radius of this motion blur when this widget is moving faster than x pixels/second and reverse that when it slows down (Those are the kind of features you usually only see in SFX tools like After Effects and the like, and i&#8217;d love to have that kind of power in Java too).</p>
<p>If you have an existing TF trigger, or if you find one you like on the intertubes and would want to use it with Trident, about the only thing you&#8217;ll need to do is replace the references to TF&#8217;s Animator to Trident&#8217;s Timeline, and that should be it since i&#8217;ve kept the API exactly the same (except renaming the focus constants, a subjective change, i thought FocusTriggerEvent.GAINED was more natural than FocusTriggerEvent.IN, could be better as FocusTriggerEvent.GAIN since the mouse&#8217;s are MouseTriggerEvent.ENTER and not ENTERED for instance, definitely something we can talk about). Let me know if you run into problems. </p>
<p>Creating one should be really easy too, just looking at the code for the core ones should convince you of that.</p>
<h3>Okay, i&#8217;m sold, sir, where do i sign ?</h3>
<p>Binaries <a href="http://lqd.hybird.org/files/trident/trident-triggers-0.1.jar">here</a>, source <a href="http://lqd.hybird.org/files/trident/trident-triggers-0.1-src.zip">here</a> (eclipse project, also includes the latest available trident jar as of right now, rev 42), sign here, credit card there, thanks mam and have a nice day.</p>
<p>As you probably know if you&#8217;ve read my previous posts, i&#8217;m more involved with Scenario at the moment (the über cool java thingy hidden under the arguably less cool javafx script thingy in the javafx runtime) and its animation support (based on evolving TF). However, I strongly encourage you to look at Trident, and its demos (+ Amber and Onyx) if you plan on adding animations to your java/swing apps (which you should, for basic usability reasons &#8211; hello, transitions! &#8211; at the very least).</p>
<p>Both Trident and TF are great animation libraries, the advantages Trident has, even though it&#8217;s probably less mature, is that the project is alive (TF&#8217;s state is not really clear, dormant, dead, spending spring break in Cancun, i don&#8217;t know), has some features TF is missing, and that it&#8217;s made by Kirill. TF&#8217;s are that it&#8217;s older and for that, probably used more, it has features Trident is missing, is more documented (the most recent doc is in a <a href="http://filthyrichclients.org/">book</a>, printed on real paper ! but you have to pay for it) and is made by Chet. Scenario&#8217;s animation support is good but has problems, mainly the license and the fact that it&#8217;s dead for the open source version, and the license and Oracle in the picture for the proprietary version (+ it&#8217;s proprietary i just said it).</p>
<p>So, triggers huh ? Hope you like it, see you soon (with something totally unrelated), or <a href="http://twitter.com/lqd">sooner than that on twitter</a>.</p>
<p>xoxoxo<br />
Rémy</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=129</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Hacking Jersey/JAX-RS to run RESTful web services on Google AppEngine/Java</title>
		<link>http://lqd.hybird.org/journal/?p=123</link>
		<comments>http://lqd.hybird.org/journal/?p=123#comments</comments>
		<pubDate>Fri, 10 Apr 2009 22:09:53 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[google appengine]]></category>
		<category><![CDATA[jax-rs]]></category>
		<category><![CDATA[jersey]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=123</guid>
		<description><![CDATA[Update: this article is about Jersey 1.0.2, i&#8217;ll update the modifications i made for the 1.1.0-ea version soon.
Jersey doesn&#8217;t run out of the box on GAE, and since i can&#8217;t wait for a new release to try RESTful services on AppEngine/Java, let&#8217;s modify its servlet container so it will at least run basic samples.
I really [...]]]></description>
			<content:encoded><![CDATA[<p>Update: this article is about Jersey 1.0.2, i&#8217;ll update the modifications i made for the 1.1.0-ea version soon.</p>
<p>Jersey doesn&#8217;t run out of the box on GAE, and since i can&#8217;t wait for a new release to try RESTful services on AppEngine/Java, let&#8217;s modify its servlet container so it will at least run basic samples.</p>
<p>I really find Jersey/JAX-RS compelling, while <a href="http://macstrac.blogspot.com/2009/01/jax-rs-as-one-web-framework-to-rule.html">others think it could be the ultimate framework</a>, and with all the recent buzz about the AppEngine platform, i wanted to try and make the two meet, grab a little dinner, a glass of wine or two, and make sweet web service babies. That didn&#8217;t go as easily as I planned, but after a little hacking i was able to run basic examples, which is probably enough for now, until a later release fixes the issues.</p>
<p>In this post i&#8217;ll describe what i did to make Jersey&#8217;s basic servlet example work (ie. what i broke) and provide you with the code (code + binary <a href="http://lqd.hybird.org/files/appengine/jersey-appengine-container_0.1.zip">here</a>) so you can try it on your own.</p>
<p>AppEngine runs a tight ship with strict security policies, which caused most of the errors you get using Jersey: classes you can&#8217;t access inside their sandbox. I&#8217;ve done my best bypassing those errors, and in doing so i actually removed and broke features, some of which i know about, the others, well, i don&#8217;t (:</p>
<p>The people following my <a href="http://www.twitter.com/lqd">twitter stream</a> know i learned the hard way that the dev server google provides with its eclipse plugin doesn&#8217;t enforce the same security policies as their appspot servers (why is that is a question to which i don&#8217;t have the answer), and the kicker is that Jersey runs fine in their dev server&#8230;.</p>
<p>The first major error you encounter is related to javax.naming.InitialContext, the second one to JAXB binding for WADL generation. I removed both the WADL pregeneration and root resources registration in the JNDI context. I don&#8217;t care much for WADL so it&#8217;s not a big loss anyway, however i&#8217;m not totally sure how the JNDI context is used inside Jersey. This might break something more useful.</p>
<p>A couple more classloader errors, and other tiny issues, and we&#8217;re good to go.</p>
<p>Here&#8217;s how to make the Jersey basic servlet sample (simple-servlet) run on AppEngine (which you&#8217;ll be able to see here for a little while, if you want to test it. It comes with a little ajax ui changing Accept headers, choosing resources to test, etc)</p>
<p>Create a GAE using the Google plugin for Eclipse, add the jersey jars into the war/WEB-INF/lib directory (i used the jersey archive found <a href="https://jersey.dev.java.net/source/browse/*checkout*/jersey/tags/jersey-1.0.2/jersey/dependencies.html">here</a> to get Jersey, its dependencies and the samples), while you&#8217;re at it also add the modified jersey servlet container there, jersey-appengine-container_0.1.jar found in the linked zip file.</p>
<p>Add the modified servlet (org.hybird.appengine.jersey.container.ServletContainer) to web.xml:</p>
<pre class="brush: xml">
&lt;servlet&gt;
        &lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt;
        &lt;servlet-class&gt;org.hybird.appengine.jersey.container.ServletContainer&lt;/servlet-class&gt;
        &lt;init-param&gt;
            &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt;
            &lt;param-value&gt;com.sun.jersey.samples.servlet.resources&lt;/param-value&gt;
        &lt;/init-param&gt;
         &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    &lt;/servlet&gt;
    &lt;servlet-mapping&gt;
        &lt;servlet-name&gt;Jersey Web Application&lt;/servlet-name&gt;
        &lt;url-pattern&gt;/resources/*&lt;/url-pattern&gt;
    &lt;/servlet-mapping&gt;
</pre>
<p>Now you can take the simple-servlet sample, copy its index.html in the war folder, and java source files inside your src. And if i remember correctly, that should be it ^^ and you&#8217;ll get the same app as i have.</p>
<p>Since Jersey has so many features (a lot more than the JAX-RS spec would let you believe), i haven&#8217;t had the time to test a lot of them yet, and i think other security exceptions are probably waiting for us.</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=123</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Fun Friday Trick: Generics type inference + static imports = don&#8217;t wait for Java 7</title>
		<link>http://lqd.hybird.org/journal/?p=98</link>
		<comments>http://lqd.hybird.org/journal/?p=98#comments</comments>
		<pubDate>Mon, 02 Mar 2009 14:36:51 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[fun friday]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=98</guid>
		<description><![CDATA[Welcome to another fun edition of fun friday on a fun monday. 
Today, we&#8217;ll see a very simple trick, that uses the regular generics type inference with a factory method and static imports, to make generics more readable.
Reading the java 7 language &#8220;pre&#8221; proposals (from polls and all), and especially the one about adding more [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to another fun edition of fun friday on a fun monday. </p>
<p>Today, we&#8217;ll see a very simple trick, that uses the regular generics type inference with a factory method and static imports, to make generics more readable.</p>
<p>Reading the java 7 language &#8220;pre&#8221; proposals (from polls and all), and especially the one about adding more type inference on generic objects construction, i remembered a very simple trick i stumbled upon years ago.</p>
<p>What if you named your factory method as a constructor and imported it using the static import feature ? Turns out, i kinda like how it cleans up the code.</p>
<p>Today, we&#8217;re using this, and it&#8217;s a mouthful:<br/> Map&lt;String, List&lt;String&gt;&gt; anagrams = new HashMap&lt;String, List&lt;String&gt;&gt;();</p>
<p>I think the java 7 proposal (when it&#8217;s released, there&#8217;s no draft for it yet, only informal polls, and a starting proposal <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-February/000009.html"> here</a>) will allow to turn it into<br/> Map&lt;String, List&lt;String&gt;&gt; anagrams = new HashMap&lt;&gt;();  </p>
<p>First of, notice the ugly empty &lt;&gt;, it would look cleaner without it, but because of backwards compatibility, it might not be &#8220;possible&#8221;. We&#8217;ll see.</p>
<p>While today&#8217;s trick turns it into this, (assuming it was added to HashMap of course)</p>
<pre class="brush: java">
// in java.util.HashMap for instance
// very common code except for the name
public static &lt;K, V&gt; HashMap&lt;K,V&gt; HashMap()
{
   return new HashMap&lt;K, V&gt;();
}

// in your code, where the magic happens
import static java.util.HashMap.HashMap;

// oooh, pretty
Map&lt;String, List&lt;String&gt;&gt; anagrams = HashMap();
</pre>
<p>It&#8217;s less code. It&#8217;s cleaner without the &lt;&gt;. It looks a little like a C++ constructor &#8211; from a distance (: &#8211; , but it has added perks too, it&#8217;s a real factory method, so you can verify arguments and throw exceptions *without* creating objects, and so on.</p>
<p>The way we&#8217;re doing it today is relatively easy to write since IDEs are helping, so you could see the java 7 proposal as of limited value, but code is written once, and read multiple times. That&#8217;s why i think both the proposal and today&#8217;s trick have value.</p>
<p>The IDEs are however a little less successfull at providing you intellisense for static imports it seems. You can solve that by modifying the default class template, or by typing HashMap.HashMap() and refactoring it to a static import (or soon will be able to do so). </p>
<p>You don&#8217;t have to wait for java 7 for generics to become easier to use, and even though it would be cleaner if the function was in, say, HashMap, you could still have a helper class à la java.util.Collections or google collections&#8217; Lists and Maps, and so on, if you really wanted to.</p>
<p>So, this is really about a way of naming factory methods and importing them statically, making it rather transparent to use today, without waiting for potential language changes. Both are not perfectly clean, but i don&#8217;t think we&#8217;ll be getting a real clean way (full type inference on the variable) any time soon, so, in the meantime, pick your poison.</p>
<p>Next up: more composite tricks, and the real reason why they might be useful to you. Yes, there is a plan behind the randomness.</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=98</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun Friday: Simple java composite tricks</title>
		<link>http://lqd.hybird.org/journal/?p=46</link>
		<comments>http://lqd.hybird.org/journal/?p=46#comments</comments>
		<pubDate>Mon, 02 Feb 2009 17:30:03 +0000</pubDate>
		<dc:creator>lqd</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[fun friday]]></category>

		<guid isPermaLink="false">http://lqd.hybird.org/journal/?p=46</guid>
		<description><![CDATA[Welcome to the first fun friday installment, sometimes on a friday i&#8217;ll post one of those, and sometimes on a monday instead of friday, just like today.
Out first topic is a very simple trick using transparent proxies, looking nice when implementing Composites &#8211; you might have seen it called event sink depending on what kind [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the first fun friday installment, sometimes on a friday i&#8217;ll post one of those, and sometimes on a monday instead of friday, just like today.</p>
<p>Out first topic is a very simple trick using transparent proxies, looking nice when implementing Composites &#8211; you might have seen it called event sink depending on what kind of composite you&#8217;re making. We&#8217;ll use a list of instances and a proxy, both of a specified interface which can be any interface you want.</p>
<p>We&#8217;ll call a method on that proxy, and under the hood we&#8217;ll use that reified call to call the same method but on all the instances of our list, in a somewhat functional style. We&#8217;ll just loop over our elements inside the InvocationHandler used by the proxy and invoke the methods on each of them.</p>
<p>The interesting part here is that we can specify the container we&#8217;ll use to hold those elements (eg a specific collection &#8211; I&#8217;ve built an example with a LinkedList; a custom built collection &#8211; using Callables &#8211; where you can specify your way of creating the collection; or a special thread-safe collection), our own way of looping (from the end or from the beginning of the list; or depending on the type of listeners inside of it, say the ones which are not direct implementors will be called afterwards) and finally our own way of invoking the callback method on each instance (on the regular main thread; on a specified thread, say, EDT *wink*; or why not say that an exception thrown while invoking the callback method will invalidate the listener and remove it from the list of elements). This alllows versatile event handling code here too, and is only a couple hundred lines for the basic support.</p>
<p>Starting from a very simple interface.</p>
<pre class="brush: java">
public interface IComposite &lt;T&gt;
{
   // you can return void
   //  if you don&#039;t want method chaining
   IComposite&lt;T&gt; add (T t);
   IComposite&lt;T&gt; remove (T t);

   T delegate();
}
</pre>
<p>You can gradually build the different composite implementations we just talked about, and get code that looks like this pretty easily (just showing adding one element to the list and slighty reformated for easier reading here, changed some long methods names, etc &#8211; the full source is linked at the end of this post)</p>
<pre class="brush: java">
public class CompositeTest
{

// Totally random listener interface
public static interface IListener
{
   void callback ();
}

//Totally random listener interface too:
//  could have been MouseListener for instance
public static interface ISwingListener
   extends EventListener
{
   void callback (String event);
}

public static void main (String [] args)
{

IComposite&lt;IListener&gt; sink = Composites
 .createLinkedListComposite (IListener.class);
sink.add (new IListener()
{
   @Override
   public void callback ()
   {
      System.out.println (&quot;IListener callback ()&quot;);
   }
});
sink.delegate().callback();

IComposite&lt;ISwingListener&gt; sink2 = Composites
 .createEventComposite (ISwingListener.class);
sink2.add (new ISwingListener()
{
   @Override
   public void callback (String event)
   {
      System.out.println (&quot;ISwingListener (&#039;&quot;
        + event + &quot;&#039;) - on EDT: &quot;
        + SwingUtilities.isEventDispatchThread ());
   }
});
sink2.delegate().callback (&quot;Main thread test&quot;);

// And now with method chaining
IComposite&lt;ISwingListener&gt; sink3 = Composites
 .createEDTComposite (ISwingListener.class)
 .add (new ISwingListener()
{
   @Override
   public void callback (String event)
   {
      System.out.println (&quot;ISwingListener (&#039;&quot;
        + event + &quot;&#039;) - on EDT: &quot;
        + SwingUtilities.isEventDispatchThread ());
   }
});

sink3.delegate().callback (&quot;EDT dispatch test&quot;);

}
}
</pre>
<p>It&#8217;s probably more instructive to do it yourself than using my code, since it&#8217;s very small, but <a href="http://lqd.hybird.org/files/composites/composites-src.zip">here</a> it is anyway (an Eclipse project). You could also imagine special composites that actually use what the callbacks return, like aggregating results or calculating mean min or max values.</p>
<p>See you <del datetime="2009-02-02T16:29:20+00:00">next friday</del>, <del datetime="2009-02-02T16:54:27+00:00">monday</del>, soon enough (:</p>
]]></content:encoded>
			<wfw:commentRss>http://lqd.hybird.org/journal/?feed=rss2&amp;p=46</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
