Webkit: Canvas and background-size performance problems

by Developer @ pebbl.co.uk on Sunday, 2 October 2011

At last...! I've been searching through my code for Pebbl to try and find a specific Webkit performance drain, focussing mainly on the JavaScript, to see if I was doing anything odd. Due to the nature of Pebbl (being a HTML5 Canvas game) I was assuming that the problem was something that I had introduced in to my js Library CanvasTheory. So - trial and error I went - disabling, enabling, profiling, stepping through the code... nothing I removed or added made a blind bit of difference. It never occured to me (well actually obviously it did eventually) to look at the css style options I was using elsewhere on the page.


The problem I was getting was on this underwater scene. (It's not finished yet, the game is totally in progress). Whenever Chrome or Safari loaded this scene, they would go from 1 frame every 12 milliseconds to 1 every 25 in Safari and 1 every 80!! on Chrome. FireFox handled this page perfectly, not even flinching. The only thing that was different to many other scenes in the game, was that this one uses quite a full on blue background... but what made me completely ignore this fact was that I had other scenes with full graphic backgrounds that gave no problems for any of the browsers.


Eventually I spotted one difference that I hadn't considered. To save rendering time, and to get the browsers to use their routines rather than my s(lowly) javascript code, instead of painting the scene backgrounds in the canvas (clearing and then redrawing every frame) I am setting the background on a div that floats behind the canvas tag. With the canvas tag mainly being transparent it all works as expected. Now this I thought was quite an obvious thing to do. However, In order to render my background image to the right size for the underwater scene (compared to the other scenes) I was using "background-size" set to 100% 100%. The second I removed this styling, Chrome and Safari were back to flying along at a decent speed. It seems, for whatever reason, webkit doesn't cache the resized version of the image. So each time Chrome or Safari had to re-render the background image because my canvas tag had trashed it by drawing on top, it seems that they both had to resample/rescale the image again. Rather ridiculous really... as usual hats off to FireFox for doing what you'd expect.


Unfortunately despite working out what the problem is, I don't really have a nice solution. My only options are to fallback to the old method of stetched background images (an image tag with 100% dimensions) and see if that works differently. Or if that fails, use another canvas tag layered behind my first one and specifically paint the background to the right size. I could create a php script that would render the background image to the right size "on request" but that seems a little overkill for what is essentially a mood setting backdrop.


Yet another thing to be disappointed about in terms of Webkit. Don't get me wrong, I love the fact that Webkit is there for so many people / programs and devices to use. I was blown away slightly the first time i saw Flash Air with it's own built in browser... and I love using my Kindle 2 browsing around whereever I want... But I just keep coming across really obscure bugs and it's winding me up :)

Drupal 7 - check

by Developer @ pebbl.co.uk

Don't ask me why but I've just finished installing the latest recommend version of Drupal 7. I'd been hearing quite a bit of chatter about it recently (after the initial buzz at the beginning of the year (and after the constant comments on the dev channel the year before that)). So I decided that maybe now would be a good time to see what improvements had been made - In my opinion there was a lot needing to be done from Drupal 6...


Before getting started however I did a little bit of research to see what others were saying, and it seemed unanimous really:


  1. Drupal 7 is cleaner and more though-out than D6
  2. Scalability is better, but performance is slightly worse.
  3. There are a lot of modules that have been ported (D7 promise), but many useful ones are still at alpha/beta stages.
  4. Module Installation and dashboard are +1 by all

From my point of view it only took me about 30 minutes this morning to get a clean install working using SQLite with my "must have" modules installed (Views,CTools,Panels). Which is far better than my experiences before with D6. I quickly created some new Views (like the new interface for Views!), tied those in to new pages controlled by Panels (Panels is now even more extensive!) exposed via Blocks (Blocks are blocks). I got Drupal's basic search working (I haven't looked in to anything more complicated like FuzzySearch altho I am currently looking in to Google Custom Search). And I then customised the main menu to be as I wanted. So all in all, good, and needed minimal time to look things up. However, I always found this to be the case really with Drupal. It's very quick to put together the large, general bits and pieces of a site... Your time just gets eaten up by editing or fixing the more smaller and specific issues which take forever to find.


Anyway, I haven't had too much time to play around now. Nothing from the code point of view. But so far the admin/front-end is a lot cleaner but totally re-arranged and I will admit to getting a little/lot lost. At least there is the feeling that once I've learned the interface it will be clearer and quicker to navigate than D6. The most annoying thing for me with D6 is that nothing was where I'd expected it to be.. whether that's because non-techy people just have very strange thought processes ;) or D6 just was very strange in itself. So D7 is an improvement... I just expect things in D6 places and haven't found everything yet ;)


So overall... since my check in January it still seemed to me that for use on a large-scale projects things would probably ok as long as you have time for bespoke modules (or you have flexibility with how things need to work), for smaller and personal CMS projects it would definitely be my choice just because it seems far more thought out than anything else out there. The "install module from URL" feature is very nice, but quite why this didn't exist previously I have no idea... it's hardly a new concept or difficult to implement, especially when you have complete control over where and how your module developers upload their contributions. I don't mean to sound negative but much of what I have seen so far in D7 is just common sense, obviously achieving common sense on a large scale project is quite difficult if you don't start out with that premise. So I'd say the "hats off" achievement isn't so much the actual new features I've come across, it's getting them all ready and working in harmony across such an open network... which is what they've achieved.

Continuation > Collapsible Email

by Developer @ pebbl.co.uk on Saturday, 24 September 2011

I didn't quite get round to finishing my original post about this, it was just at that time that work went a little hectic, and I don't think I've properly stopped since.


Anyways at the time the information was fresh in my memory, it's gone a little stale now unfortunately. I remember there were quite a few things I wanted to write about, so if I do get some spare time (and a reason to look in to it) I'll pick up my collapsible email template again. Before I consign this to the "most probably never" however, there are a few things that I can remember that may help out other people trying to get around particular mail agent inconsistencies.


Outlook 2007/2010


Next to Lotus Notes, Outlook 2007 is almost fun... but compared to the other e-mail clients, it is quite simply a joke. Annoyingly it is a joke that is installed on a large number of machines worldwide. So as per usual, us developers have to find some way of limping on with awful software. In case it helps, here are a few nice style properties, that affect only microsoft products.


mso-hide

If you need to hide a particular element only in Outlook 2007/2010 use the following inline style.


style="mso-hide: all;"

It should work just like display:none; but is Microsoft specific. I've mainly used this on items that really are already hidden, but in some cases their presence still creates padding or spacing issues for Outlook.


mso-table-lspace and rspace

Whilst trying to get my collapsible email to layout nicely I kept getting annoying horizontal spacing appearing between tables in Outlook. Eventually, the only way I could find out what was actually causing it was to send my email to my Outlook 2007 account and grab the raw message content / source. Obviously for most email clients you would assume - logically - that the raw message source would be the same as the e-mail i sent out. As usual though Microsoft do their "magic" and translate the mark-up in to bloated gibberish that is barely recognisable as my original.


After poring over the source for a while I spotted two additional style properties in amongst all the nonsense things that were being dynamically generated. These were "mso-table-lspace" and "mso-table-rspace". Don't ask me why Outlook 2007 thought it prudent to add them, my only guess would be that because the HTML renderer used by OL2007 is primarily designed as a WYSIWYG interface, this extra spacing is added to allow users to click between tables and type content. This however makes no sense from the context of "viewing" an e-mail, so my assumption is that I am 100% correct... Thankfully these properties are not automatically overridden, so all I had to do was specify them on each of my tables, and set them to 0pt.


style="mso-table-lspace: 0pt; mso-table-rspace: 0pt;"

RobinHood Dynamic Video

by Developer @ pebbl.co.uk

Just tested this recent social video system out from the RobinHood tax people - not the most dynamic of dynamic videos I've seen - but at least it all seemed to work and looks good :) Plus I'd say a better "product" than a lot of the more standard advertising campaigns I've seen.




Chrome annoyances

by Developer @ pebbl.co.uk on Friday, 23 September 2011

Having just recently finished my part of quite a large scale multi-lingual campaign, I thought I should write a bit about the browser that caused the most development hassle. And for once it wasn't Internet Explorer. Thankfully for this campaign we had no directive to support IE6, which meant a lot of the usual IE problems went away. No, this time around it was Chrome, which was entirely unexpected... as whenever I've used the browser to test my own more simplified projects I've not come across many problems.

The truth is I don't really use Chrome as a browser, I'm still a FireFox guy (despite it getting slightly cumbersome). There are quite a few reasons for this, but mostly it's down to a few simple differences:


  1. I love the way FireFox's Awsome bar works... in my mind it is the only address bar that does what you'd intuitively expect
  2. I don't like the way Chrome requires the http:// part to be typed in order to find localhost domains
  3. Chrome still has a number of quite visible graphical and UI glitches - i.e. whilst typing an address immediately after boot up, it will ignore the address and open a blank tab.
  4. Chrome handles reposting data to pages (retry, cancel) in a terrible way IMO. It displays an error page on which the user has to refresh before they are asked to resend the data.
  5. Chrome seems to have no "Force Refresh" method that will wipe caches.

As you can see, small gripes. However, it's only from actually using the browser a bit more recently (in testing this project) that other annoyances have sprung up.


Chrome & Caching


For most browsers it is enough to include the following to prevent a page from being cached:


<meta http-equiv="Pragma" content="no-cache" />

It seems not so for Chrome, our UAT testers had been having an interesting time with the ability to navigate back after a form submit and being able to resubmit the entire form content again (without any retyping). Now this might sound like a good thing to have for certain forms - depending on their function - however our form is used for the entry to a competition, which utilises file uploads. Once the user has entered with certain content, there is no benefit for them to go back to the previous form and have it retain what they just submitted, in fact there are negative repercussions. All other browsers were doing what they were supposed to do, which is re-request the "navigated back to" page at which point the server redirects them back to the start of the submission process. The only way to get this to work in multiple versions of chrome was the following:


<meta http-equiv="Cache-Control" content="no-store" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

and...


header("Content-type: text/html; charset=utf-8");
header("Cache-Control: no-store, must-revalidate");
header("Expires: Sun, 03 Jan 1982 00:00:00 GMT");

which seems just a little over the top. I'll probably find somewhere that it is actually stated in the standards, or some other nonsense like that... who writes these standards anyway.


Chrome & Session/Cookie setting


Chrome seems to have some problems with setting cookies, either that or Chrome is the only browser following what the actual specifications should be. I'm not sure, and I haven't had time to find out, considering my work hours recently. The same problem occured twice on the same project but for two different developers.


Basically we were getting session problems but only in Chrome. Now, usually if it had been bespoke code that was powering the Session handling I would have assumed programmer error. However we were using CodeIgniter which is a tried and tested code-base. So I went about debbugging everything I could think of that may cause problems with sessions that lay outside of the code. It took... a while... but turned up nothing. Then I stepped through the code function by function.. only to find everything was doing what it should.


By now I was getting rather wound up... all I was left with was trying to debug the browser difference itself. So I tried tracking the actual cookie creation (something that I had assumed would just be working). And guess what...? After all that, Chrome was - for some reason - ignoring the session cookie entirely. It was being sent, Chrome was recieving, but it was just ignoring it.

To cut a long story short... the thing that was causing a problem was the fact that whilst building our site we were accessing the staging server directly by I.P address (not something that i've done in the past) and both myself and the other back-end developer had both done the same thing, we'd automatically followed CodeIgniters advice and implemented something I usually do anyway (as part of security when settings cookies). You'll find the following in CI's config file:


/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path'   =  Typically will be a forward slash
| 'cookie_secure' =  Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix']    = "";
$config['cookie_domain'] = ".".$_SERVER["HTTP_HOST"];
$config['cookie_path']      = "/";

By prefixing the host with a dot, you are making certain that no one else can access/modify your cookie if they have control of a domain that ends with the same name. For example:


If using the following as the host setting for a cookie:

www.pebbl.co.uk

It is possible that the cookie could be hijacked from:

hijackwww.pebbl.co.uk

or even:

pebbl.co.uk

would be hijacked with:

sneakypebbl.co.uk

You should be using the following:

.www.pebbl.co.uk
.pebbl.co.uk

All because hosts are compared from the right, pretty much like an "ends with" match - this is a useful feature that allows you to set cookies that can be accessed across multiple subdomains/CNAMEs. Obviously the first example isn't likely to happen with hijackwww.pebbl.co.uk as I have full control of my nameserver/dns settings and I'm not likely to go hijacking my own site. However on shared domains, or other set-ups this is indeed possible. The second example is also much more likely and can be achieve just by registering the right domain.


This is why CodeIgniter advise "Set to .your-domain.com for site-wide cookies". The prepended dot prevents the comparison from matching. This was all fully understood by me, so I didn't give it a second thought. However, I didn't think about whether this is expected behaviour when the hostname is not a domain name. Which is exactly what we ended up with when accessing the site using an I.P address.


In Firefox, Opera, Internet Explorer and it seems Safari... they all accept cookies from the following (note the prefixed dot):


.11.22.33.44

Chrome however, does not, now I don't now if it should or not... but all I can say is that it was a damnably annoying bug to track down. So whatever the choice, all the browsers should sort it out an do the same thing! Whereas I will always recomend using a proper domain name. We only stuck with the I.P to save time, and in the end it caused more problems than it shoud have done.


After re-reading my post I just realised that I'm not very clear at the end (like a lot of things really) ;) Basically our solution to the problem was to preg_match the HOST. If we were dealing with an I.P. then we don't prefix the cookie's host with a dot. I also made a note to myself to research exactly whether this is a bug in Chrome.

Useful terminal snippets :)

by Developer @ pebbl.co.uk on Thursday, 28 July 2011

If you are anything like me, then you'll see any kind of server maintenance or management as something to be avoided if possible. Not that I'm against keeping things maintained or secure... it's just I'd rather not be the one doing it on a server ;) I'm still confused as to how anyone can actually enjoy the role of "Server Admin".

Anyway, it seems that no matter how hard I try to avoid server positions in my day job, I still somehow end up getting landed with the odd task here and there. So ... usually, after a while of head-scratching, googling, and learning some interesting facts and figures about whatever flavour of Linux I'm using, I'll eventually manage to find a solution to what ever the problem was. And as if by magic all will be right with the World.

... then I'll forget everything that I've just learned...

So in an attempt to avoid the above this time around (and possibly to help out other pseudo server admins out there) I've compiled a list of some useful commands:

Count Unique IPs from Access Log

grep "GET /?ac=" access_log.processed | grep 25/Jan/2010 | awk '{print $1}' | sort -u | wc -l

Touch files recursively

find . -exec touch {} \;

Copy Src to Dst ignoring .svn

- test
rsync -avCn [SRC_PATH] [DST_PATH]

- real
rsync -avC [SRC_PATH] [DST_PATH]

- check by checksum rather than date time
rsync -avcCn [SRC_PATH] [DST_PATH]

Find just .svn folders

find . -name "*.svn" -exec ls -al {} \;

Remove just .svn folders

find . -name ".svn" -exec rm -rf {} \;

Connect to a server with port forwarding

ssh [USER]@[DOMAIN] -p [DOMAIN_PORT] -L:[LOCAL_PORT]:[REMOTE_ADDR]:[REMOTE_PORT] -Y

Fix the MYSQL max allowed packet problem (usual Drupal fix)

set global net_buffer_length=1000000; 
set global max_allowed_packet=1000000000;

Server Copy

scp [FILE] [USER]@[DOMAIN]:[DESTINATION_FOLDER]

AWK - count length of field at particular CSV offset (BEWARE: wont ignore commas inside quotes)

awk 'BEGIN { FS = "," } ; { if (length($1)>12) print $1 }' file
awk 'BEGIN { FS = "," } ; { if (length($2)>6) print $2 }' file

DIFF - compare folders (ignore svn)

diff -rq folder1 folder2 | grep -vE '\.svn|\.DS_Store'

SSHFS

sshfs -p [PORT] [USER]@[DOMAIN]:[REMOTE_PATH] [LOCAL_FOLDER] -o follow_symlinks

Remove the "Downloaded from internet" alert (Mac OSX)

defaults write com.apple.LaunchServices LSQuarantine -bool NO

Line Count

wc -l [FILE]

Upload Using rSync (with exclusions)

rsync -vaucCP --exclude 'db.php' --exclude '.*' --exclude 'local.php' --exclude 'tools/*' --delete-after [SRC_PATH] [DEST_PATH]

Find out about the MySQL service

netstat -tunlp | grep ":3306"

Find out about remaining resources

free -m

Using Backticks?

joe `which [name of something]`
ls -alh `which php`
mysql -e "show status;" > log_`date +%y_%m_%d_%H_%M`

FF6 .. More to combat memory leaks :)

by Developer @ pebbl.co.uk on Sunday, 10 July 2011

If you count yourself as an advanced JavaScripter, then you will have definitely come across these three terms:

  1. Garbage Collection
  2. Closures
  3. Memory Leaks

If not, then you might need to go back to guru school - or at least, stop being so damn flukey with your implementations. In today's scripting world, Memory Leaks seem to be an inevitable side-affect of development getting more rapid, throw-away and high-level. It also seems to be a side-effect of the copy & paste / lazy generation - but then a lot can be blamed on them ;)

However, even the most conscientious coder can propagate memory leaks with their code. For instance, they might not fully understand each JavaScript engine that their work will be deployed on (highly likely) or they may accidently get lost in too many nested closures. Either way the outcome is the same, memory usage creep. The good news is that FireFox 6 has a plan that can help, in the form of Weak References.

Weak, Strong... Reference?

If you haven't heard of weak references before, then it would make sense that you don't refer to your normal variable references as strong... but that is precisely what they are. The difference between weak and strong references is all to do with garbage collection.

A strong reference to any variable, array or object (i shall call these items) will be counted by the garbage collector, only items that have no strong references are ever deleted/garbage collected. Memory Leaks occur when strong references are left pointing to their original items, even when the code that created them has finished. This is because the garbage collector (GC) assumes the referenced items are still in use and so doesn't delete the item and free up the memory.

Weak references however do not increment the garbage collector's reference count, and so when the GC comes to clean up, even if there have been many weak references left lying about the place, the original item will still be deleted. This does mean that an item that is only held by weak references might just suddenly disappear, so you need to be aware of what you want to keep.

WeakMap

FireFox's idea to support weak references is in the form of the WeakMap Object/API.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/WeakMap

By the looks of things WeakMap allows you to store data without the strong reference, it's experimental at the moment, but it should mean that you can store anything that you don't mind loosing. You would normally use this by having one strong reference and all other access to this item as weak, then when you delete the original strong reference the item will become viable for garbage collection.

So no more worrying about data being remembered long after your script has forgotten what it was that it was supposed to be doing.