Demonastery Blog http://demonastery.org Demonastery.org, Blog of Zane.A LogPixels DPI hack http://demonastery.org/76/logpixels-dpi-hack/ Here's a handy tip for those netbook users out there in dire need of more screen estate. You can force a DPI value of lower than 96 by using the Windows registry. To do so open <b>Regedit</b>, navigate to <i>HKEY_CURRENT_CONFIG/Software/Fonts/LogPixels</i> and change the decimal value from <b>96</b> to something lower such as <b>80</b>. Then log out and back in and you will see the changes. I'm using a value of 80 on my netbook and it is about the most that I will drop it while still keeping things (half) readable. You will notice that it really hinders the readability of fonts as well as having some strange bitmap scaling artifacts, but if you're like me and can adjust to it then the extra screen space gained is well worth it :)<br /> <br /> You can view a side by side comparison of the my desktop with LogPixels at 80 and at 96 by viewing this <a href="http://imgur.com/a/9qYTk#0" target="_blank">imgur album</a>.<br /> <br /> <a href="http://i.imgur.com/DKnsW.jpg" target="_blank"><img src="http://i.imgur.com/DKnsWm.jpg" alt="http://i.imgur.com/DKnsWm.jpg" /></a> <a href="http://i.imgur.com/JHrJi.jpg" target="_blank"><img src="http://i.imgur.com/JHrJim.jpg" alt="http://i.imgur.com/JHrJim.jpg" /></a><br /> Wed, 04 Jan 12 23:32:06 +1300 Docstrings in my Chicken? http://demonastery.org/75/docstrings-in-my-chicken/ Here's a little bit of amateur code to enable the use of <a href="http://en.wikipedia.org/wiki/Docstring" target="_blank">docstrings</a> in Chicken Scheme. I haven't written any Scheme in a few months and don't have any formal training in the ninja art of <a href="http://en.wikipedia.org/wiki/Hygienic_macro#explicit_renaming" target="_blank">explicit renaming macros</a> so I'd appreciate any feedback from Scheme veterans:<br /> <br /> <div><br /> ;;; Docstrings for Chicken!<br /> <br /> ;; The hash-table that will contain the procedures and their associated<br /> ;; documentation strings as well as their code for later use.<br /> (define *documentation-hash-table* (make-hash-table))<br /> <br /> ;; Documented define er-macro<br /> (define-syntax (define* form r c)<br /> (let* ((args-form (second form)) ; (proc args)<br /> (proc-name (first args-form)) ; proc<br /> (doc (third form)) ; "The docstring"<br /> (body (drop form 3))) ; (everything else)<br /> (hash-table-set! *documentation-hash-table* proc-name (list doc body)) ; insert the doc and code body<br /> `(,(r 'define) ,args-form ,@body))) ; Define the procedure as normal<br /> <br /> ;; Example of a documented procedure, will print a nice-ish list of documented procedures<br /> (define* (print-docs)<br /> "Print a list of documented procedures"<br /> (hash-table-walk *documentation-hash-table*<br /> (lambda (key val)<br /> (printf "~a => ~a~n ~a~n~n" key (first val) (second val)))))<br /> </div><br /> <br /> Another example of why Scheme is such a fun language to work with :) Sun, 13 Nov 11 17:39:39 +1300 Twitter's Bootstrap http://demonastery.org/74/twitter-s-bootstrap/ To me, one of the most annoying parts of prototyping a new web application is getting a presentable look and feel up quickly. When I'm prototyping stuff I love to have a good looking interface from the start, even if that interface will be changed before going live.<br /> <br /> Recently, Twitter released a wonderful CSS/JS framework named <a href="http://twitter.github.com/bootstrap/" target="_blank">Bootstrap</a> for this exact purpose. As stated it is a toolkit "[...] designed to kickstart development of webapps and sites.". It combines an aesthetically pleasing base styling (based somewhat off of Twitter itself) of HTML elements with an easy to use CSS grid, great browser compatibility, and various optional Javascript modules to extend functionality of things such as Drop-down menus and modal dialogs.<br /> <br /> As for the elements it offers, some of my favourites are:<br /> <br /> * All typical HTML elements are styled, including decent typography<br /> * A top bar to be used for menus and such, with drop-down menus to be activated easily with JS<br /> * Tabs/Pills<br /> * Ability to pretty-print code when used in conjunction with google-code-prettify<br /> * Labels and buttons, with styles for success, warning, notice, etc<br /> * Alert boxes, with corresponding styles, great for showing form submission status etc<br /> <br /> Bootstrap is built on top of the <a href="http://lesscss.org/" target="_blank">LESS CSS preprocessor</a> for ease of extending and integrating into your apps. Personally I found that the precompiled stylesheet was more than enough to begin with however, and I'm more of a fan of the <a href="http://sass-lang.com/" target="_blank">SASS preprocessor</a> anyway. The JS modules are also very easy to integrate with very little code needed to hook them up to their appropriate classes.<br /> <br /> I jumped into Bootstrap shortly after its release, and have been using it ever since for my internal prototypes and eventual applications, including an application in the process of being deployed. Bootstrap played an integral part in getting that project complete under it's tight deadline.<br /> <br /> Highly recommended to all! Fri, 04 Nov 11 15:19:57 +1300 Das Keyboard Ultimate http://demonastery.org/73/das-keyboard-ultimate/ I took the plunge recently and bought my first mechanical keyboard, the <a href="http://daskeyboard.com" target="_blank">Das Keyboard Ultimate</a>. It was very hard to find someone that would ship one to NZ, but eventually I found <a href="http://auspcmarket.com.au" target="_blank">AusPCMarket</a> that ships the Das as well as several other "clicky keyboards". The Das is known for being a bit pricey.. the Ultimate set me back <i>$230NZD</i> (incl shipping and GST) at the current exchange rate and was delivered in just over a week. If you need to justify the price by thinking of it as an investment, then do :)<br /> <br /> With it being my first mechanical keyboard I'm unable to give a fair review in comparison to others of its kind. My previous keyboard was a <a href="http://www.microsoft.com/hardware/en-us/p/comfort-curve-keyboard-2000" target="_blank">Microsoft Comfort Curve 2000</a> keyboard (a much cheaper <i>$40NZD</i>), a brilliant keyboard but of course based around <a href="http://en.wikipedia.org/wiki/Keyboard_technology#Dome-switch_keyboard" target="_blank">rubber dome</a> technology.<br /> <br /> Anyway, it took me a while to adjust to the non-curved layout of the Das, but now that I have I feel that I am touch-typing much MUCH more efficiently than before. It feels great to type on, plus it sounds amazing! Personally I revel in the sound of the Das, and while I wouldn't want to use one around sleeping people, it certainly won't break through any music playing on your headphones and so far doesn't seem to penetrate walls ;)<br /> <br /> Overall a definite thumbs-up from me. If you're in NZ and looking to get a Das, I'd highly recommend also going through <a href="http://auspcmarket.com.au" target="_blank">AusPCMarket</a> as their service was quick and no-bullshit. Wed, 12 Oct 11 19:31:11 +1300 Tiny Memcached Wrapper http://demonastery.org/72/tiny-memcached-wrapper/ No posts in a while huh! Been pretty busy and haven't thought of much to blog about lately. But I've been playing with <a href="http://memcached.org/" target="_blank">Memcache</a> and wanted to share a tiny class I made to add easy caching to my PHP projects. This PHP class just provides a nice simple interface to use by extending the <i>Memcached</i> class:<br /> <br /> <div><br /> // Call the class whatever you want<br /> class MyCache extends \Memcached {<br /> function cache($key, $time, $func) {<br /> if (($val = $this->get($key)) === false) {<br /> $val = $func();<br /> $this->set($key, $val, strtotime($time) - time());<br /> }<br /> return $val;<br /> }<br /> }<br /> </div><br /> <br /> And now to use it, first you summon it in the same way as the regular class:<br /> <br /> <div><br /> $c = new MyCache;<br /> $c->addServer('127.0.0.1', 11211);<br /> </div><br /> <br /> Then where you would like to begin caching (I'm using this very blog as an example, where GeSHi for syntax highlighting is the main bottle-neck for page generation), you call the class like so:<br /> <br /> <div><br /> // Example using my BLACK blog engine (http://github.com/ZaneA/BLACK)<br /> <br /> // Here is the original line<br /> $row['body'] = render($row['body']);<br /> <br /> // And here is a cached version<br /> // As you can see we have a KEY, a TIMEOUT, and a FUNCTION to call for a cache miss<br /> $row['body'] = $c->cache("blog_post_{$row['id']}", '30 minutes', function () use ($row) {<br /> return render($row['body']); // Renders all the post filters, including syntax highlighting<br /> });<br /> </div><br /> <br /> Awesome, for this small tweak on my local test blog (with 4 posts), this takes the page response time down from 14ms to 2ms. Quite a win I'd say :)<br /> <br /> Of course this code requires the <i>memcached</i> PHP extension and a running Memcache server ;) Fri, 12 Aug 11 15:48:43 +1200 Emacs Tip: Vimpulse http://demonastery.org/71/emacs-tip-vimpulse/ One thing I love about Emacs is that it is so extensible. I was an avid Vim user for a long time and it took me several tries to switch to Emacs, but I will never look back. With the <a href="http://gitorious.org/vimpulse" target="_blank">Vimpulse</a> addon to the built-in <b>viper-mode</b>, Emacs becomes a powerful Vim impersonator, capable of being extended with Emacs-Lisp.<br /> <br /> A lot of my time is spent doing web development, and so strong HTML editing ability is essential in any editor I use. Vim has this amazing concept of <a href="http://vimdoc.sourceforge.net/htmldoc/motion.html#text-objects" target="_blank">text objects</a> which allows you to be very efficient when transforming text; one of the most useful when doing web development is therefore the XML/HTML tag text object. I would use this all the time by invoking <b>"cit"</b> to change text between a pair of tags. To demonstrate, here's a piece of text you might have sitting in a file:<br /> <br /> <div><br /> <title>Hello |World</title><br /> </div><br /> <br /> Now with the cursor somewhere in between the tags (visualized above by the pipe, '|') we can go into command mode and type <b>"cit"</b> and the above will be replaced with:<br /> <br /> <div><br /> <title>|</title><br /> </div><br /> <br /> Ready to be edited!<br /> <br /> Well sadly, Vimpulse doesn't have this feature by default, probably one of the very few parts of Vim that it doesn't emulate in fact! (NB. <a href="http://gitorious.org/evil/pages/Home" target="_blank">Evil</a> contains emulation for this already) But not to worry, we can just add it in! This is Emacs after all.<br /> <br /> So how do we instruct Vimpulse to recognise another text object? Turns out it's <i>REALLY</i> easy:<br /> <br /> <div><br /> (vimpulse-define-text-object vimpulse-tag (arg)<br /> "Select a tag"<br /> :keys '("at" "it") ; The keys that will trigger this text object<br /> (vimpulse-inner-object-range ; We're basically defining a range on which to act upon<br /> arg<br /> (lambda (arg) (search-backward ">" nil nil arg) (forward-char)) ; Look to the left for a ">" character<br /> (lambda (arg) (search-forward "<" nil nil arg) (backward-char)) ; Look to the right for a "<" character<br /> )) ; and return the distance between them!<br /> </div><br /> <br /> Note that this isn't a perfect implementation, but for the purposes of this demonstration it will suffice! We can now <b>"cit"</b> and <b>"dit"</b> to our hearts content! Hail Emacs!<br /> <br /> For a more robust implementation it may be worth looking at using <b>sgml-skip-tag-backward</b> and <b>sgml-skip-tag-forward</b> for movement instead.<br /> <br /> Happy Hacking! Thu, 07 Jul 11 23:05:46 +1200 Org-mode Conky Colorizer http://demonastery.org/70/org-mode-conky-colorizer/ Just whipped up a little script to colorize my <a href="http://orgmode.org" target="_blank">org-mode</a> todo lists for display via <a href="http://conky.sourceforge.net" target="_blank">Conky</a>. It's bound to be of use to someone so I thought I'd better share :)<br /> <br /> Here's a <a href="http://i.imgur.com/mqYUG.png" target="_blank">screenshot of it in action</a>, sitting in the corner of my desktop.<br /> <a href="http://i.imgur.com/mqYUG.png" target="_blank"><img src="http://i.imgur.com/mqYUGs.jpg" alt="http://i.imgur.com/mqYUGs.jpg" /></a><br /> <br /> Source is below, to use, place <b>${execp /path/to/org-conky-parser.scm 30}</b> in to your conkyrc. Requires <a href="http://call-cc.org" target="_blank">Chicken Scheme</a>, and remember to <i>chmod +x</i> the script first.<br /> <br /> <div><br /> #!/usr/bin/csi -script<br /> ;; org-conky-parser.scm<br /> ;; Run an org-mode file through some regexes and output colors<br /> ;; Suitable for Conky.<br /> <br /> ; File to read, could be easily grabbed from argv<br /> (define *file* "~/org/day.org")<br /> (define *font* "Liberation Sans")<br /> <br /> ;; Code below<br /> <br /> (use regex-literals)<br /> (set-read-syntax! #\/ read-regex-literal)<br /> <br /> (define ++ string-append)<br /> <br /> (define (color c)<br /> (++ "${color " c "}\\1${color}"))<br /> <br /> (define (font f)<br /> (++ "${font " f "}\\1${font}"))<br /> <br /> (define *replace-list*<br /> (list<br /> (list /^(\*+)/ (color "#555555"))<br /> (list /(TODO)/ (color "#ffaa88"))<br /> (list /(DONE)/ (color "#aaff88"))<br /> (list /(TODO|DONE)/ (font (++ *font* ":style=bold:pixelsize=12")))<br /> (list /(<.*>)/ (color "#aaaaff"))<br /> (list /(<.*>)/ (font (++ *font* ":style=bold:pixelsize=14")))<br /> (list /(.*list.*)/ (font (++ *font* ":style=bold:pixelsize=16")))))<br /> <br /> ; Grab file contents into a list<br /> (define *contents*<br /> (with-input-from-file *file* read-lines))<br /> <br /> ; Colorize a line using above regexes<br /> (define (colorize-line line)<br /> (for-each ; Foreach regex/replacement<br /> (lambda (pair)<br /> (set! line (string-substitute (car pair) (cadr pair) line)))<br /> *replace-list*)<br /> line)<br /> <br /> (define print-colorized-line (compose print colorize-line))<br /> <br /> ; Print colorized lines<br /> (for-each print-colorized-line *contents*)<br /> </div> Sun, 05 Jun 11 21:37:57 +1200 Adding FreeType to our Demo http://demonastery.org/69/adding-freetype-to-our-demo/ Continuing on from my <a href="http://demonastery.org/60/chicken-scheme-and-opengl/" target="_blank">Chicken Scheme, and OpenGL</a> tutorial, I'm going to show you how to extend it to render pretty FreeType text using the <a href="http://homepages.paradise.net.nz/henryj/code/" target="_blank">FTGL</a> library. Follow the code below for details as always; it's really easy! :)<br /> <br /> Users of ArchLinux can get <i>FTGL</i> with a simple <b>sudo pacman -S ftgl</b>. Debian should be something like <b>sudo apt-get install libftgl-dev</b>.<br /> <br /> Alright lets start by loading up the code from last time ...<br /> <br /> ... and scrolling down to the "(inline .." call:<br /> <br /> <div><br /> (inline #<<EOF<br /> #ifndef CHICKEN<br /> ...<br /> #endif<br /> <br /> // Here we're going to add the new stuff for FTGL!<br /> <br /> // Define a constant we're going to use later<br /> const int FTGL_RENDER_ALL = 0xffff;<br /> <br /> // And typedef FTGLfont as void so we can use it and pass it around<br /> typedef void FTGLfont;<br /> <br /> // Notice however that I didn't include the ftgl header, because I<br /> // want to define just the functions we're going to use to make<br /> // things even easier<br /> <br /> FTGLfont* ftglCreatePixmapFont(const char*);<br /> <br /> void ftglSetFontFaceSize(FTGLfont*, int, int);<br /> void ftglRenderFont(FTGLfont*, const char*, int);<br /> void ftglDestroyFont(FTGLfont*);<br /> <br /> // The above are the only ones we will be using for now, but these<br /> // ones below may also be useful, along with the SimpleLayout class<br /> <br /> // Also possible to use ftglCreateTextureFont and<br /> // render as a plain texture too! Using the same render call<br /> //FTGLfont* ftglCreatePixmapFont(const char*);<br /> <br /> //float ftglGetFontLineHeight(FTGLfont*);<br /> //void ftglGetFontBBox(FTGLfont*, const char*, int, float*);<br /> <br /> // Done!<br /> </div><br /> <br /> ... Now skip down to the EOF part:<br /> <br /> <div><br /> EOF<br /> "-lSOIL -lftgl" ; Notice here we have added -lftgl to be linked<br /> )<br /> </div><br /> <br /> ... Now skip down to our old draw-text function, where we're going to replace the GLUT code with our new FTGL render code:<br /> <br /> <div><br /> (define (draw-text text x y #!key (color '(1 1 1 1)))<br /> (apply gl:Color4f color)<br /> (gl:PushAttrib gl:ENABLE_BIT)<br /> (gl:Disable gl:TEXTURE_2D)<br /> (gl:RasterPos2f x y)<br /> ; This line has been replaced with a new one for FTGL<br /> ; FTGL even takes care of rendering for us!<br /> (ftglRenderFont font text FTGL_RENDER_ALL)<br /> (gl:PopAttrib))<br /> </div><br /> <br /> ... and down a bit further to where we loaded the texture last time:<br /> <br /> <div><br /> (define texture (LoadGLTexture "circle_gradient.tga"))<br /> <br /> ; And add a new line for loading the font up<br /> (define font (ftglCreatePixmapFont "pathtoyourfont.ttf"))<br /> ; with minimal error checking<br /> (unless font<br /> (error "Couldn't load font!")<br /> (exit 1))<br /> <br /> ; now set the font size<br /> (ftglSetFontFaceSize font 36 36)<br /> </div><br /> <br /> ... Nearly done! down to the last line now:<br /> <br /> <div><br /> (glut:MainLoop)<br /> <br /> ; Add a call to destroy the font after we're done<br /> (ftglDestroyFont font)<br /> </div><br /> <br /> And that's it! Ah the joys of libraries and high level languages!<br /> If all went well you should have sweet anti-aliased variable-pitch text in place of the standard GLUT stuff before :D Sun, 05 Jun 11 19:09:57 +1200 More Practical Chicken http://demonastery.org/68/more-practical-chicken/ As I love sharing code on my blog, and I love <a href="http://call-cc.org" target="_blank">Chicken Scheme</a>, I'm going to share a couple of handy and practical features that I've made use of recently.<br /> <br /> Anyone that has used C++ for longer than a few minutes has probably noticed that literal constants (<i>numbers and such</i>) often have a suffix attached to them. The most common place that you'll see this is when writing floating-point decimals, ie. <b>1.0f</b>.<br /> <br /> They might seem a little pointless at first, but they have their uses; I swear that I once read of a way to add your own types into the language too.<br /> <br /> But anyway, I searched for a way to do this in Chicken too, and it turns out it's really easy (of course!). Chicken provides a function called <a href="http://wiki.call-cc.org/man/4/Unit%20library#set-parameterized-read-syntax" target="_blank">set-parameterized-read-syntax!</a> that can emulate this functionality quite nicely.<br /> <br /> Here's a real world case that I used recently, I wanted to be able to convert from inches into pixels, based on a known DPI (in this case 180). The code to set this up looks like this:<br /> <br /> <div><br /> ; This lets you type #12i anywhere in your code and have it replaced with 2160<br /> (set-parameterized-read-syntax #\i (lambda (port n) (* n 180)))<br /> </div><br /> <br /> Yeah that's really it, isn't Scheme wonderful :P<br /> <br /> The other really useful feature is the <a href="http://wiki.call-cc.org/eggref/4/regex-literals" target="_blank">regex-literals</a> egg (download it with <b>sudo chicken-install regex-literals</b>), which gives Chicken Scheme the ability to use Ruby/Perl/Javascript style literal regexes; well almost, it allows you to type <b>#/myregexhere/i</b> (notice the leading #) and it will be converted into a <i>regexp</i> object. Luckily we can even take this a step further and remove the hash at the front. Code time!<br /> <br /> <div><br /> ; Import the egg first of all<br /> (use regex-literals)<br /> <br /> ; Lucky for us, regex-literals provides us the function we need to read<br /> ; a full regex literal from a Scheme port, so all we have to do is just<br /> ; hook it up to the "/" character and it will work as expected!<br /> (set-read-syntax! #\/ read-regex-literal)<br /> <br /> ; Now we can write inline regex with a familiar syntax :D<br /> (pp (string-match /.*match[A-Za-z]+me.*/i "hello match world me :D"))<br /> </div><br /> <br /> I know this a measly amount of code to be posting an entry for, but I hope that both of these features (among others) demonstrate just how practical Chicken Scheme can be in many situations, and shows that you don't always have to write a large amount of code to get cool things done! Mint! Thu, 12 May 11 22:24:33 +1200 Org-agenda-sms.el http://demonastery.org/67/org-agenda-sms-el/ So my warmup for today was to rewrite my old <a href="http://demonastery.org/25/automatic-agenda-notification/" target="_blank">org-mode agenda notification code</a> to use Emacs lisp instead of Python.<br /> The aim of this code is to check your <a href="http://orgmode.org" target="_blank">org-mode</a> agenda for any headings with DEADLINEs and create a vcalendar for each, and then send them to your phone via <a href="http://clickatell.com" target="_blank">Clickatell</a>.<br /> <br /> To use it, save the code into your Emacs lib path, and then in your <i>.emacs</i> you'll want something like:<br /> <br /> <div><br /> (require 'org-agenda-sms)<br /> <br /> (setq org-agenda-sms-username "")<br /> (setq org-agenda-sms-password "hunter2")<br /> (setq org-agenda-sms-api-key "")<br /> (setq org-agenda-sms-phone "")<br /> <br /> (run-at-time "7am" nil 'org-agenda-sms)<br /> </div><br /> <br /> The contents of <i>org-agenda-sms.el</i> is below:<br /> <br /> <div><br /> ;;<br /> ;; Org-agenda-sms.el<br /> ;; Allows Emacs to SMS you a vcalendar of appointments each day<br /> ;; Written by Zane Ashby (http://www.demonastery.org)<br /> ;;<br /> ;; Usage: (run-at-time "07am" nil 'org-agenda-sms)<br /> ;;<br /> <br /> (defvar org-agenda-sms-username nil "Clickatell username for SMS")<br /> (defvar org-agenda-sms-password nil "Clickatell password for SMS")<br /> (defvar org-agenda-sms-api-key nil "Clickatell API key for SMS")<br /> (defvar org-agenda-sms-phone nil "Phone number for SMS")<br /> <br /> ;;;###autoload<br /> (defun org-agenda-sms-build-vcal (header timestamp)<br /> "Builds a vcalendar from a header and timestamp"<br /> (let ((vcal-template "BEGIN:VCALENDAR<br /> VERSION:1.0<br /> BEGIN:VEVENT<br /> CATEGORIES:APPOINTMENT<br /> DTSTART:%s<br /> DTEND:%s<br /> SUMMARY:%s<br /> DESCRIPTION:%s<br /> END:VEVENT<br /> END:VCALENDAR")<br /> (time (format-time-string "%Y-%m-%d %H%M"<br /> (apply 'encode-time (org-parse-time-string timestamp)))))<br /> (format vcal-template time time header header)))<br /> <br /> ;;;###autoload<br /> (defun org-agenda-sms-send (text &optional type)<br /> "Send an SMS vcalendar provided by \"text\""<br /> (let* ((text (url-hexify-string text))<br /> (url-format "https://api.clickatell.com/http/sendmsg?user=%s&password=%s&api_id=%s&to=%s&msg_type=%s&text=%s")<br /> (url (format url-format org-agenda-sms-username org-agenda-sms-password org-agenda-sms-api-key org-agenda-sms-phone (if type type "SMS_NOKIA_VCAL") text)))<br /> (message "Retrieving api.clickatell.com/http/sendmsg..")<br /> (url-retrieve-synchronously url)))<br /> <br /> ;;;###autoload<br /> (defun org-agenda-sms ()<br /> "Check for appointments in org-agenda and SMS as vcalendar to phone"<br /> (org-map-entries<br /> (lambda ()<br /> (let ((heading (clean-org-heading (nth 4 (org-heading-components))))<br /> (props (org-entry-properties)))<br /> (cond<br /> ((assoc "DEADLINE" props)<br /> (org-agenda-sms-send (org-agenda-sms-build-vcal heading (cdr (assoc "DEADLINE" props)))))<br /> ((assoc "SCHEDULED" props)<br /> (org-agenda-sms-send (org-agenda-sms-build-vcal heading (cdr (assoc "SCHEDULED" props)))))<br /> ((assoc "TIMESTAMP" props)<br /> (org-agenda-sms-send (org-agenda-sms-build-vcal heading (cdr (assoc "TIMESTAMP" props))))))))<br /> "TIMESTAMP<=\"<+1d>\"|DEADLINE<=\"<+1d>\"|SCHEDULED<=\"<+1d>\""<br /> 'agenda))<br /> <br /> (provide 'org-agenda-sms)<br /> </div><br /> <br /> Seems to work for me, but as always your mileage may vary ;)<br /> Thu, 12 May 11 11:07:22 +1200 FileTools C++ Class http://demonastery.org/66/filetools-c-class/ Here is the source for the FileTools C++ Class promised <a href="http://demonastery.org/63/c-eval-hell-yes/" target="_blank">a few posts back</a>, which uses <a href="http://en.wikipedia.org/wiki/Inotify" target="_blank">inotify</a> to monitor files for changes.<br /> <br /> Again we start off with the class header:<br /> <br /> <div><br /> // FileTools.cpp<br /> <br /> #include <stdio.h><br /> #include <stdlib.h><br /> #include <sys/inotify.h><br /> <br /> typedef class FileTools {<br /> public:<br /> static int addWatch(char *, ...);<br /> static void removeWatch(int);<br /> static bool hasChanged(int);<br /> <br /> private:<br /> static int fd;<br /> } *pFileTools;<br /> <br /> // Parse variable arguments into 'buffer' character array<br /> // This is just a macro I use often in my functions<br /> #define parsevargs(buff, buffer) \<br /> char buffer[128]; \<br /> memset(buffer, 0, sizeof(buffer)); \<br /> va_list ap; \<br /> va_start(ap, buff); \<br /> vsnprintf(buffer, sizeof(buffer), buff, ap); \<br /> va_end(ap);<br /> </div><br /> <br /> And on to the implementation:<br /> <br /> <div><br /> int FileTools::fd = 0;<br /> <br /> int FileTools::addWatch(char *path, ...)<br /> {<br /> // Parse variable arguments into "buffer"<br /> parsevargs(path, buffer);<br /> <br /> // Initialize inotify if need be<br /> if (!FileTools::fd) FileTools::fd = inotify_init();<br /> <br /> printf("Adding Watch for %s..\n", buffer);<br /> <br /> // Return a new watch handle<br /> return inotify_add_watch(FileTools::fd, buffer, IN_CLOSE_WRITE);<br /> }<br /> <br /> void FileTools::removeWatch(int wd)<br /> {<br /> printf("Removing Watch id = %i..\n", wd);<br /> inotify_rm_watch(FileTools::fd, wd); <br /> }<br /> <br /> #define EVENT_SIZE (sizeof(struct inotify_event))<br /> #define BUF_LEN (1024 * (EVENT_SIZE + 16))<br /> bool FileTools::hasChanged(int wd)<br /> {<br /> bool ret = false;<br /> <br /> // Return from select immediately if none available<br /> struct timeval time;<br /> time.tv_sec = 0;<br /> time.tv_usec = 0;<br /> fd_set rfds;<br /> <br /> FD_ZERO(&rfds);<br /> <br /> // Set up our fd_set with our inotify fd<br /> FD_SET(FileTools::fd, &rfds);<br /> <br /> // Do the select<br /> select(FileTools::fd + 1, &rfds, NULL, NULL, &time);<br /> <br /> if (FD_ISSET(FileTools::fd, &rfds)) {<br /> int length = 0;<br /> int i = 0;<br /> char buffer[BUF_LEN];<br /> <br /> length = read(FileTools::fd, buffer, BUF_LEN);<br /> <br /> while (i < length) {<br /> // Got a match<br /> struct inotify_event *event = (struct inotify_event*)&buffer[i];<br /> <br /> if (event->wd == wd &&<br /> event->mask & IN_CLOSE_WRITE) {<br /> // It was a file we were monitoring!<br /> printf("Watched file %i has changed\n", wd);<br /> ret = true;<br /> }<br /> <br /> i += EVENT_SIZE + event->len;<br /> }<br /> }<br /> <br /> return ret;<br /> }<br /> </div><br /> <br /> And that's it! Use to your hearts content, this code and the CodeTools code before it are free to use for whatever purpose you want.<br /> <br /> Sorry for the short post, but I want to post more Scheme (and maybe PHP) instead of cluttering up my blog with C++ ;) Sun, 08 May 11 11:55:43 +1200 CodeTools C++ Class http://demonastery.org/65/codetools-c-class/ As promised <a href="http://demonastery.org/63/c-eval-hell-yes/" target="_blank">a couple of posts back</a>, I will present a C++ class to compile some arbitrary code using <a href="http://en.wikipedia.org/wiki/GNU_Compiler_Collection" target="_blank">GCC</a> and load it into memory.<br /> <br /> The code is pretty simple, we start off with the class header:<br /> <br /> <div><br /> // CodeTools.hpp<br /> <br /> #include <stdio.h><br /> #include <stdlib.h><br /> #include <dlfcn.h><br /> <br /> typedef class CodeTools {<br /> public:<br /> static bool compileString(char*, bool (*callback)(void*));<br /> static bool compileFile(char*, bool (*callback)(void*));<br /> <br /> private:<br /> } *pCodeTools;<br /> </div><br /> <br /> And then on to the <b>compileString</b> method. This method actually just wraps compileFile to avoid code duplication, so it's really just taking in a string and writing it to a temporary file before calling <b>compileFile</b>.<br /> <br /> Here we go:<br /> <br /> <div><br /> // CodeTools.cpp<br /> <br /> bool CodeTools::compileString(char* code, bool (*callback)(void*))<br /> {<br /> // Generate a temporary file name<br /> // (There are better ways to do this!)<br /> char temp[256];<br /> sprintf(temp, "codetools_XXXXXX");<br /> char* tmppath = mktemp(temp);<br /> <br /> // Open temporary file<br /> FILE* fp = fopen(tmppath, "wb");<br /> <br /> if (!fp) {<br /> fprintf(stderr, "Could not open temporary path %s\n", tmppath);<br /> return false;<br /> }<br /> <br /> // Write out string<br /> fwrite(code, strlen(code), sizeof(char), fp);<br /> fclose(fp);<br /> <br /> // Call out to compileFile method<br /> bool ret = compileFile(tmppath, callback);<br /> <br /> // Remove temporary file<br /> unlink(tmppath);<br /> <br /> return ret;<br /> }<br /> </div><br /> <br /> So again, just a small wrapper, which can be reimplemented to your liking.<br /> <br /> Now for the part that does the actual work, this can be cleaned up plenty but seems pretty stable for me:<br /> <br /> <div><br /> bool CodeTools::compileFile(char* path, bool (*callback)(void*))<br /> {<br /> // Increments each time this function is called.<br /> // This is used for the .so path. If the .so path<br /> // doesn't change then our new functions won't<br /> // override the old ones.<br /> static int count = 0;<br /> <br /> // A buffer to hold our command line<br /> char buffer[256];<br /> memset(buffer, 0, sizeof(buffer));<br /> <br /> // The last path used<br /> char sopathLast[256];<br /> memset(sopathLast, 0 , sizeof(sopathLast));<br /> <br /> // The current path to use<br /> char sopath[256];<br /> memset(sopath, 0 , sizeof(sopath));<br /> <br /> sprintf(sopathLast, "./%s.%i.so", path, count - 1);<br /> sprintf(sopath, "./%s.%i.so", path, count++);<br /> <br /> // Please change modify these to your liking! These are what I use<br /> // for my livecoding playground<br /> sprintf(buffer, "g++ -shared -o %s -fPIC -fno-use-cxa-atexit -xc++ -include src/Global.hpp %s -Isrc -I/usr/include/freetype2", sopath, path);<br /> <br /> // Call it!<br /> int ret = system(buffer);<br /> <br /> if (ret != 0) {<br /> fprintf(stderr, "Error in compilation: g++ returned %i\n", ret);<br /> return false;<br /> }<br /> <br /> // Cool, compile was successful!<br /> <br /> // Now, try to get a handle to the last opened .so so we can close it<br /> void* handle = dlopen(sopathLast, RTLD_LAZY | RTLD_NOLOAD);<br /> if (handle) {<br /> fprintf(stderr, "Found current handle %s, closing first\n", sopathLast);<br /> dlclose(handle);<br /> }<br /> <br /> // Open the new .so, LAZY load symbols for speed<br /> handle = dlopen(sopath, RTLD_LAZY);<br /> <br /> if (!handle) {<br /> fprintf(stderr, "Could not load compiled file into memory: %s\n", dlerror());<br /> unlink(sopath);<br /> return false;<br /> }<br /> <br /> printf("Loaded %s\n", sopath);<br /> <br /> // Remove temporary .so<br /> unlink(sopath);<br /> <br /> // Call the user supplied callback passing the .so handle to it<br /> // From there it can load individual functions.<br /> return callback(handle);<br /> }<br /> </div><br /> <br /> And done. This should be all the code needed to use the CodeTools sample from the <a href="http://demonastery.org/63/c-eval-hell-yes/" target="_blank">C++ Eval? Hell yes.</a> post. Have fun! I will be posting the FileTools class shortly too. Sat, 07 May 11 22:13:11 +1200 Fun with Renoise and Fluxus http://demonastery.org/64/fun-with-renoise-and-fluxus/ Amidst my experimentations with livecoding I decided to purchase the amazing <a href="http://www.renoise.com" target="_blank">Renoise</a> Tracker (and overall DAW) while it is on special (30% discount!). My intentions are to play around with Renoise to make music (online and off), and using the built in <a href="http://opensoundcontrol.org/introduction-osc" target="_blank">OSC</a> and <a href="http://jackaudio.org/" target="_blank">JACK</a> support, coordinate the music using <a href="http://www.pawfal.org/fluxus/" target="_blank">Fluxus</a>, and of course be able to respond to it. I am also toying with the idea of using an <a href="http://arduino.cc" target="_blank">Arduino</a> or two as input devices. Fun stuff I reckon :P<br /> <br /> For anyone wondering how to make Fluxus respond to the Renoise audio, it is simple using JACK:<br /> <br /> <div><br /> ; If I remember correctly you may need to connect the Renoise<br /> ; output to the Fluxus input using something like qjackctl first<br /> <br /> (start-audio "renoise:output_01_left" 1024 44100) ; This will tell Fluxus to listen to the left channel..<br /> (gain 1)<br /> <br /> ; .. and later in your render loop, using the "gh" function you can react to the sound<br /> (every-frame<br /> (begin<br /> (scale (vmul (vector (gh 1) (gh 2) (gh 3)) 0.1))<br /> (draw-torus)))<br /> </div><br /> <br /> Pretty neat. Using OSC it is also really simple to control Renoise. First you will want to enable the OSC server in the Renoise preferences, and then you can use the following:<br /> <br /> <div><br /> (osc-destination "osc.udp://localhost:8000") ; With the port you specify in the preferences<br /> (osc-send "/renoise/song/bpm" "i" (list 120)) ; Set the BPM to 120<br /> (osc-send "/renoise/transport/start" "" (list)) ; Start playback<br /> (osc-send "/renoise/transport/stop" "" (list)) ; Stop playback<br /> </div><br /> <br /> Next up is to get Fluxus working nicely with Emacs.. and I promise some more updates will come shortly (including the code I've promised) :) Mon, 02 May 11 21:54:38 +1200 C++ Eval? Hell yes. http://demonastery.org/63/c-eval-hell-yes/ Recently I've been getting back into <a href="http://en.wikipedia.org/wiki/Live_coding" target="_blank">live coding</a>, and as part of that I have been experimenting with a simple livecoding framework in C++.<br /> <br /> One of my experiments involves using C++ as a <i>"scripting language"</i>, by compiling code on the fly (using g++, but any compiler should work) into a shared object, and then <a href="http://en.wikipedia.org/wiki/Dynamic_loading" target="_blank">dlopen</a>-ing the resultant file and hooking up the necessary functions.<br /> <br /> By doing this I can have full access to the engine/framework and speed is never a concern. It also means I can modify it later to load any arbitrary shared object (ie. generated via C or any other language, perhaps Chicken?).<br /> <br /> The workflow I desired to achieve was to have an OpenGL context open, blank at first. From there I could open the editor of my choice, hack on some high level C++/OpenGL, and when I saved the file, the engine would recompile the file and load it, causing its rendering function to be overridden with the new one.<br /> <br /> I'm happy to say I've achieved what I was after!<br /> <br /> <i>I will be posting the relevant source to do this in the next post</i>, but for now I will say that it involves a very simple class called <b>FileTools</b> that wraps <a href="http://en.wikipedia.org/wiki/Inotify" target="_blank">inotify</a> on the Linux operating system (so it will need to be ported for other OS's, or a generic polling solution could be used very easily, by simply resorting to <a href="http://en.wikipedia.org/wiki/Stat_(Unix)" target="_blank">stat</a>), which allows one to watch a file with some simple code that looks like this:<br /> <br /> <div><br /> int fd = FileTools::addWatch("test.cpp");<br /> <br /> while (mainloop) {<br /> if (FileTools::hasChanged(fd)) { // Uses select internally<br /> // Cool!<br /> }<br /> }<br /> <br /> FileTools::removeWatch(fd);<br /> </div><br /> <br /> For my engine to extend this to include recompilation, I have another class called <b>CodeTools</b>, which wraps <b>system</b> and <b>dlopen</b>.<br /> This is also very easy to use, it looks like this:<br /> <br /> <div><br /> if (FileTools::hasChanged(fd)) {<br /> CodeTools::compileFile("test.cpp", [](void* handle) {<br /> Renderer::renderp render = (Renderer::renderp)dlsym(handle, "render");<br /> if (render) // Hook 'er up<br /> ::engine.renderer->userRender = render;<br /> });<br /> }<br /> </div><br /> <br /> Here we are passing a path to a file to compile, and a function (I'm using <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions" target="_blank">C++0x lambdas</a> here) that takes a valid handle from <i>dlopen</i>.<br /> <br /> Using this class it is also possible to using <i>compileString</i> to compile a string via temp files.<br /> <br /> Oh and <b><a href="http://i.imgur.com/64M4d.png" target="_blank">a screenshot</a></b> for those wanting to see it in action! Sat, 16 Apr 11 12:02:34 +1200 Change GTK display on the fly http://demonastery.org/62/change-gtk-display-on-the-fly/ While working on my <a href="http://demonastery.org/59/acer-aspire-one-d255e/" target="_blank">netbook</a> away from my desktop machine, I pondered how I could view my email clients display (<a href="http://claws-mail.org" target="_blank">claws-mail</a>, a GTK app), without having to resort to something such as <a href="http://en.wikipedia.org/wiki/Virtual_Network_Computing" target="_blank">VNC</a>.<br /> <br /> I know this can be done using utilities such as <a href="http://en.wikipedia.org/wiki/Xmove" target="_blank">xmove</a>, which essentially act as a proxy X server that can detach a client from one display and move it to another. But this requires you to start xmove before the application, and to tell the application to launch with its display on xmove.<br /> <br /> Nah. <i>We need something cooler than this.</i><br /> <br /> After using some Google fu it became apparent that the GTK library has a function named <b>gtk_window_set_screen</b> which is demonstrated in the <i>gtk-demo</i> application that comes with the GTK sources. This function allows the application to switch X11 display on the fly.. provided the application has a way to do so (which none do, because why would they bother).<br /> <br /> So I decided to look into ways of doing <i>code injection</i> in Linux, as a way of being able to call that function inside our target application. Turns out this is easy as pie using <a href="http://en.wikipedia.org/wiki/GNU_Debugger" target="_blank">GDB</a>.<br /> <br /> First of all, we need to create a small library that contains our code. This will be loaded into memory and executed by us later. The code I hacked together looks like this (no guarantees whatsoever that this will work on your machine):<br /> <br /> <div><br /> // Include the headers we will need<br /> #include <stdio.h><br /> #include <gtk/gtk.h><br /> <br /> // Now write the function we will be executing.<br /> // This one takes a string containing the display to connect to<br /> void change_display(char *display_str)<br /> {<br /> GdkDisplay *display = gdk_display_get_default();<br /> GtkWidget *toplevel = NULL;<br /> <br /> GdkWindow *window = NULL;<br /> GtkWidget *widget = NULL;<br /> <br /> // Not 100% necessary but gives you time before the line below this one runs<br /> sleep(5);<br /> <br /> // This line gets the GDK window below the cursor<br /> window = gdk_display_get_window_at_pointer(display, NULL, NULL);<br /> if (window) {<br /> gdk_window_get_user_data(window, (gpointer)&widget);<br /> <br /> toplevel = gtk_widget_get_toplevel(widget);<br /> <br /> GdkDisplay *new_display = gdk_display_open(display_str);<br /> if (new_display)<br /> gtk_window_set_screen(GTK_WINDOW(toplevel), gdk_display_get_screen(new_display, 0));<br /> else<br /> fprintf(stderr, "Could not connect to display \"%s\"\n", display_str);<br /> } else {<br /> fprintf(stderr, "No window found\n");<br /> }<br /> <br /> // By this point the window should have moved itself to the display you passed in<br /> }<br /> </div><br /> <br /> Cool. So now we just need to compile it and we're a step closer to <i>winning</i>:<br /> <br /> <div>gcc -shared -fPIC -o lib lib.c `pkg-config --libs --cflags gtk+-2.0`</div><br /> <br /> Now we should be left with our library sitting in our current directory. Now we can actually inject the code. For this part, we will fire up <b>GDB</b>, attaching to the program we wish to move:<br /> <br /> <div>gdb attach `pidof claws-mail`</div><br /> <br /> A bunch of lines will scroll by, which you can largely ignore for this exercise, but you should be left with a nice <b>(gdb)</b> prompt. Now it's time to inject our code!<br /> <br /> <div>(gdb) print (void*)dlopen("/path/to/your/current/directory/lib", 2)</div><br /> <br /> Yep, GDB has now loaded our library into the memory space of the application. Now we can run our function :)<br /> <br /> <div>(gdb) print change_display("192.168.1.2:0")</div><br /> <br /> If we now quickly move our cursor over to the window of the application. After a few seconds the window should successfully move to the proper display.<br /> <br /> Pretty easy huh? :D There are plenty more things you can achieve with simple code injection like this, and for the purpose of this exercise, we could have written a GTK module instead. But this is just <i>cool</i>. Sat, 09 Apr 11 13:54:45 +1200