Index: /rgbkbd/tags/0.1/COPYING
===================================================================
--- /rgbkbd/tags/0.1/COPYING	(revision 72)
+++ /rgbkbd/tags/0.1/COPYING	(revision 72)
@@ -0,0 +1,339 @@
+                    GNU GENERAL PUBLIC LICENSE
+                       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+                            NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
Index: /rgbkbd/tags/0.1/README
===================================================================
--- /rgbkbd/tags/0.1/README	(revision 72)
+++ /rgbkbd/tags/0.1/README	(revision 72)
@@ -0,0 +1,46 @@
+== RGB KBD ==
+`rgbkbd` is a Linux compatible utility for driving the Corsair Gaming K70 RGB keyboard using the ckb-daemon from [https://github.com/bmerrison/ckb ckb]..
+
+Rather than being built around a GUI like `ckb` is, `rgbkbd` is a Python program that allows for rapid prototyping and experimentation with what the [http://www.corsair.com/en-us/landing/k70-rgb K70 RGB keyboard] can do.
+
+== Installation ==
+Run rgbkbd_controller.py from this directory, or package it as an RPM, install it, and run /usr/bin/rgbkbd
+
+== Usage ==
+Make sure that 'ckb-daemon' is running, and that 'ckb' is NOT running.  `rgbkbd` replaces 'ckb's role in driving the keyboard animations, so they will interfere with each other if run concurrently.  Like `ckb`, `rgbkbd` contains the logic behind the operations occuring on the keyboard.
+
+
+`rgbkbd` will initialize the keyboard to a static all-white backlight.
+
+Pressing the light button will toggle the backlight off and on.
+
+Pressing the light button and the Windows lock button together (as a chord), will switch to the keyboard command mode.  Pressing the light button and the Windows lock button again will return you to the previous keyboard mode.
+
+The command mode allows you to select a number of different modes and effects.  Most of the selections involve chording keys.  When a new mode is selected, the keyboard exits command mode and initiates the new keyboard mode.  When in command mode, your key presses are not passed on to currently running programs.
+
+=== Static color lighting ===
+The number keys are illuminated in a variety of colors.  Pressing and releasing one of these keys will switch to a monochome color for the keyboard.  Note that the `~/\`` key to the left of `1` is for black.
+
+=== Random pattern lighting ===
+The `Home` key toggles through a random selection of colors.  Hitting that key in command mode will select a random pair of colors, and a changing random set of keys will toggle between those colors.
+
+You can select the colors for the random key animation.  To do so, press and hold the `Home` key, then press the color selection key on the number row, and release the keys.  Random keys will light with the chosen color on a black background.
+To select the background color as well, press and hold the `Home` key, then tap the color you want for the foreground, then tap the color you want for the background, and release the `Home` key.
+
+=== Color pattern lighting ===
+You can configure the keyboard to cycle through a pattern of colors with a configurable transition.  The media keys show a light pattern in command mode.  The stop button shows alternating colors.  The back button shows a pulse that fades out.  The play and forward buttons show fading colors at different rates.
+Press and hold one of those buttons, then tap a sequence of the color keys, then release the media key.  The entire keyboard will cycle through the select colors using the selected transition.
+
+=== Color motion lighting ===
+You can put the color patterns described above into motion across the keyboard.  To do so, choose your transition type and colors in the same way you would for the color pattern lighting, but before you release the transition selection key, tap a direction key on the number pad.  You can select any of 6 different directions.  Then release the transition key.  The color pattern will now sweep across the keyboard in the direction you chose.
+
+=== Touch-typing mode ===
+The `PrtScn` button selects a touch-typing mode.  Keys are statically backlit in logical groups.  Plus the number row indicates your typing speed in increments of 10WPM (words per minute).  The indicator includes the `-` and the `=` keys to indicate 110WPM and 120WPM, respectively.
+
+As you type, the keys, starting with `1` will light up in white, creating a gwoing bar of white.  This indicates your current typing speed.
+Your peak typing speed from the past is indicated with a yellow backlit key.  If your peak typing speed exceeds 130WPM, the peak indicator will change to red.
+The average typing speed you have maintained over the past minute is indicated by a green backlit key.  If this exceeds 130WPM, the indicator will change to blue.
+
+=== Secret notes mode ===
+The `Scroll Lock` key selects a secret note taking mode.  The lighting will change to a random green-on-black animation, but what you type will be written to a file in your home directory named `.secret-<timestamp>` instead of going to your programs.  This allows you to write a note to yourself for later without displaying what you are typing on the screen.  This can be useful if you have someone sitting near you and you remembered something important but private you wanted to make sure you didn't forget.
+
Index: /rgbkbd/tags/0.1/rgbkbd.spec
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd.spec	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd.spec	(revision 72)
@@ -0,0 +1,35 @@
+Name:		rgbkbd
+Version:	0.1
+Release:	1%{?dist}
+Summary:	User utility to interface with ckb-daemon
+
+Group:		System/Utility
+License:	GPLv2
+URL:		https://retracile.net
+Source0:	rgbkbd.tar.bz2
+
+#BuildRequires:	
+Requires:	ckb
+
+%description
+User utility to drive the lights on RGB keyboards using ckb-daemon
+
+%prep
+%setup -q -n rgbkbd
+
+%build
+true
+
+%install
+mkdir -p %{buildroot}/usr/bin
+mkdir -p %{buildroot}/usr/lib64/python2.7/site-packages
+cp -r rgbkbd %{buildroot}/usr/lib64/python2.7/site-packages/
+cp rgbkbd_controller.py %{buildroot}/usr/bin/rgbkbd
+
+%files
+/usr/bin/rgbkbd
+/usr/lib64/python2.7/site-packages/rgbkbd
+
+%changelog
+* Sat Jan 24 2015 Eli Carter <elicarter@retracile.net> - 0.1-1
+- Initial packaging
Index: /rgbkbd/tags/0.1/rgbkbd/animation.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/animation.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/animation.py	(revision 72)
@@ -0,0 +1,134 @@
+#!/usr/bin/python
+
+import time
+import random
+import math
+
+from core import ColorPattern, MotionPattern, EventHandler
+from color import Color, Colors
+from geometry import key_positions, KeyMatrix, Keys
+
+
+class AlternatingColorPattern(ColorPattern):
+    """Steps through a cycle of colors"""
+    def color(self, t):
+        index = int(round(len(self.colors)*self.phase(t))) - 1
+        return self.colors[index]
+
+
+class BeatColorPattern(ColorPattern):
+    """Linearly fades through a cycle of colors"""
+    def color(self, t):
+        index = int(len(self.colors)*self.phase(t)) % len(self.colors)
+        foreground = self.colors[index]
+        background = self.colors[(index+1)%len(self.colors)]
+        phase = (self.phase(t) * len(self.colors)) % 1
+        return Color.blend(foreground, background, transparency=phase)
+
+
+class ThrobColorPattern(ColorPattern):
+    """Non-linearly (sin wave) fades through a cycle of colors"""
+    def color(self, t):
+        index = (2*int(len(self.colors)*self.phase(t))) % len(self.colors)
+        foreground = self.colors[index]
+        background = self.colors[(index+1)%len(self.colors)]
+        phase = (self.phase(t) * len(self.colors)) % 1
+        intensity = (1 + math.sin(2 * math.pi * phase)) / 2
+        return Color.blend(foreground, background, transparency=1-intensity)
+
+
+class PulseColorPattern(ColorPattern):
+    """Pulses a color on, then fades to the next color, through a cycle of
+    colors
+    """
+    def color(self, t):
+        index = (2 * int(len(self.colors)*self.phase(t))) % len(self.colors)
+        foreground = self.colors[index]
+        background = self.colors[(index+1)%len(self.colors)]
+        phase = (self.phase(t) * len(self.colors)) % 1
+        return Color.blend(foreground, background,
+            transparency=phase)
+
+
+class AngleMotionPattern(MotionPattern):
+    """Applies a phase offset across the keyboard at a specified angle and
+    stretched a specified distance.  (Makes for something of a wave effect.)
+    """
+    def __init__(self, angle=0.0, size=50, *args, **kwargs):
+        super(AngleMotionPattern, self).__init__(*args, **kwargs)
+        self.angle = angle
+        self.size = size
+
+    def phase_offset(self, x, y):
+        # The pixels for the keyboard geometry are not square; so account for
+        # their shape by doubling the Y value.
+        return (- x * math.cos(self.angle) - 2 * y * math.sin(self.angle)) / self.size
+
+
+# Lighting animations
+class RandomAnimation(EventHandler):
+    """Light up a randomly selected subset of keys"""
+    tick_rate = 0.1
+
+    def __init__(self, foreground=Colors.WHITE, background=Colors.BLACK,
+            quantity=40, *args, **kwargs):
+        super(RandomAnimation, self).__init__(*args, **kwargs)
+        self.foreground = foreground
+        self.background = background
+        self.quantity = quantity
+        self.lit_keys = []
+
+    def tick(self):
+        """Handler for the periodic events"""
+        # We don't enforce a strict rate here.  If you are typing, the random
+        # updating of keys will occur more frequently.  If this is getting
+        # called as part of a group of event handlers where another event
+        # handler has a lower value for tick_rate, this animation will toggle
+        # keys faster.  Given the intent of this animation, that isn't a
+        # problem.
+        if len(self.lit_keys) > self.quantity:
+            key = self.lit_keys.pop(0)
+            self.keyboard.set_keys(key, self.background)
+        key = random.choice(list(set(Keys.ALL.split(',')) - set(self.lit_keys)))
+        self.lit_keys.append(key)
+        self.keyboard.set_keys(key, self.foreground)
+
+
+class ColorAnimation(EventHandler):
+    """Given a color pattern, apply that pattern to the keyboard"""
+    def __init__(self, color_pattern=None, keys=Keys.ALL, *args, **kwargs):
+        super(ColorAnimation, self).__init__(*args, **kwargs)
+        self.keys = keys
+        self.color_pattern = color_pattern
+
+    def tick(self):
+        color = self.color_pattern.color(time.time())
+        self.keyboard.set_keys(self.keys, color)
+
+
+class MotionAnimation(EventHandler):
+    def __init__(self, color_pattern=None, motion_pattern=None, keys=Keys.ALL,
+            *args, **kwargs):
+        super(MotionAnimation, self).__init__(*args, **kwargs)
+        self.keys = keys.split(',')
+        self.color_pattern = color_pattern
+        self.motion_pattern = motion_pattern
+
+        # pre-calculate the points we will have to color
+        self.points = []
+        for key in self.keys:
+            self.points.extend(key_positions[key])
+
+    def tick(self):
+        matrix = KeyMatrix()
+        for x,y in self.points:
+            color = self.color_pattern.color(time.time() + self.motion_pattern.t_offset(x, y))
+            matrix.set_pixel(x, y, color)
+        colors = {}
+        for key in self.keys:
+            color = matrix.get_key(key)
+            colors.setdefault(color, []).append(key)
+        key_colors = []
+        for color, keys in colors.items():
+            key_colors.append((','.join(keys), color))
+        self.keyboard.set_many_keys(key_colors)
Index: /rgbkbd/tags/0.1/rgbkbd/color.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/color.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/color.py	(revision 72)
@@ -0,0 +1,81 @@
+#!/usr/bin/python
+
+import random
+
+class Color(object):
+    """Represents a color for the keyboard"""
+    def __init__(self, red=None, green=None, blue=None, rgb=None):
+        # Expects integer values, no floats
+        if rgb is None:
+            rgb = (red, green, blue)
+        else:
+            rgb = tuple(rgb)
+        if None in rgb:
+            raise Exception("bad value in %r" % rgb)
+        for name, value in zip(['red' , 'green', 'blue'], rgb):
+            if not 0 <= value < 256:
+                raise Exception("Bad value %s for %s" % (value, name))
+        self.rgb  = rgb
+
+    @classmethod
+    def blend(cls, c1, c2, transparency):
+        """Given two colors, return a color based on a weighted combination"""
+        blended = [a+b for a, b in zip([(1 - transparency) * x for x in c1.rgb],
+            [transparency * x for x in c2.rgb])]
+        return cls(rgb=blended)
+
+    @classmethod
+    def average(cls, colors):
+        """Return the mean color among the given colors"""
+        return cls(rgb=[sum(x)/len(colors) for x in zip(*[c.rgb for c in colors])])
+
+    @classmethod
+    def fromstring(cls, hexstring):
+        """Convert a 6-digit hex string into a Color object"""
+        r = int(hexstring[0:2], 16)
+        g = int(hexstring[2:4], 16)
+        b = int(hexstring[4:6], 16)
+        return cls(r, g, b)
+
+    @classmethod
+    def random8(cls, exclude=None):
+        """Returns a random color from the 8 basic colors, optionally excluding
+        a choice.
+        """
+        while True:
+            candidate = cls(rgb=[random.choice([0,255]) for _n in range(3)])
+            if not exclude or candidate != exclude:
+                return candidate
+
+    def __str__(self):
+        """6-hex-digit representation of the color
+
+        This is the representation used by ckb-daemon
+        """
+        return '%02x%02x%02x' % self.rgb
+
+    def __cmp__(self, other):
+        return cmp(self.rgb, other.rgb)
+
+    def __eq__(self, other):
+        return self.rgb == other.rgb
+
+    def __hash__(self):
+        return hash(self.rgb)
+
+
+class Colors(object):
+    """Pre-defined colors"""
+    WHITE = Color.fromstring('ffffff')
+    GREY = Color.fromstring('808080')
+    DARK_GREY = Color.fromstring('404040')
+    BLACK = Color.fromstring('000000')
+
+    RED = Color.fromstring('ff0000')
+    GREEN = Color.fromstring('00ff00')
+    BLUE = Color.fromstring('0000ff')
+    PURPLE = Color.fromstring('ff00ff')
+    YELLOW = Color.fromstring('ffff00')
+    CYAN = Color.fromstring('00ffff')
+    DARKCYAN = Color.fromstring('004040')
+    ORANGE = Color.fromstring('ff8000')
Index: /rgbkbd/tags/0.1/rgbkbd/core.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/core.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/core.py	(revision 72)
@@ -0,0 +1,247 @@
+#!/usr/bin/python
+import os
+import time
+
+from color import Colors
+from geometry import Keys
+
+
+class Keyboard(object):
+    """Object representing an attached keyboard; communicates with the
+    ckb-daemon process.
+    """
+
+    def __init__(self, num=None, device=None):
+        if device is not None:
+            self.num = int(device[-1])
+            self.cmdfile = '%s/cmd' % device
+        elif num is not None:
+            self.num = num
+            self.cmdfile = '/dev/input/ckb%s/cmd' % num
+
+    def _cmd(self, command):
+        # FIXME: handle the driver daemon shutting down and eliminating this pipe
+        open(self.cmdfile, 'w').write(command + '\n')
+
+    def clear(self, color=Colors.BLACK):
+        """Clears the colors of the keyboard to a solid color; black by
+        default.
+        """
+        self._cmd("rgb %s" % color)
+
+    def lights(self, on=True):
+        """Turns the keyboard lights on or off"""
+        if on:
+            self._cmd("rgb on")
+        else:
+            self._cmd("rgb off")
+
+    def unbind(self, keys="all"):
+        self._cmd("unbind %s" % keys)
+
+    def rebind(self, keys="all"):
+        self._cmd("rebind %s" % keys)
+
+    def set_keys(self, keys, color):
+        """Sets the color of a set of keys"""
+        self._cmd('rgb %s:%s' % (keys, color))
+
+    def set_many_keys(self, key_colors):
+        """Sets the colors of multiple set of keys"""
+        self._cmd('rgb %s' % ' '.join('%s:%s' % c for c in key_colors))
+
+    def alloc_notify(self):
+        """Allocate a notification pipe from ckb-daemon"""
+        n = 1
+        while os.path.exists('/dev/input/ckb%s/notify%s' % (self.num, n)):
+            n += 1
+        if n > 9: # Catch the driver limitation
+            raise Exception("Too many notification nodes in use")
+        notify_filename = '/dev/input/ckb%s/notify%s' % (self.num, n)
+        self._cmd('notifyon %s' % n)
+        self._cmd('@%s notify all:on' % n)
+        timeout = time.time() + 2
+        while not os.path.exists(notify_filename) and time.time() < timeout:
+            time.sleep(0.01)
+        if not os.path.exists(notify_filename):
+            raise Exception("Failed to create notification pipe")
+        return (n, notify_filename)
+
+    def free_notify(self, num):
+        """Release a notification pipe from ckb-daemon"""
+        self._cmd('notifyoff %s' % num)
+
+
+# Lighting stuff
+class StaticLighting(object):
+    """Keys have a set color"""
+
+    def __init__(self, keyboard, profile=None):
+        self.keyboard = keyboard
+        if profile is None:
+            profile = []
+        self.profile = profile
+
+    def start(self):
+        """Initializes key colors"""
+        if self.profile is not None:
+            self.keyboard.set_many_keys(self.profile)
+
+
+class Monochrome(StaticLighting):
+    """Static lighting where all keys are one color"""
+    def __init__(self, keyboard, color=Colors.WHITE):
+        super(Monochrome, self).__init__(keyboard, profile =[(Keys.ALL, color)])
+
+
+class ColorPattern(object):
+    """Object which returns a color given a time
+
+    Abstract base class; subclasses must implement color(time).
+    """
+
+    def __init__(self, colors, period=5):
+        self.colors = colors
+        self.period = period
+
+    def foreground(self):
+        """Utility function to get the foreground color"""
+        return self.colors[0]
+
+    def background(self):
+        """Utility function to get the background color, defaulting to black"""
+        if len(self.colors) > 1:
+            background = self.colors[1]
+        else:
+            background = Colors.BLACK
+        return background
+
+    def phase(self, t):
+        """Returns a float value in [0, 1] indicating where in the period the
+        given time is.
+        """
+        return (t % self.period) / self.period
+
+    def color(self, t):
+        """Given a time t, return a color"""
+        raise NotImplementedError
+
+
+class MotionPattern(object):
+    """Object which returns a time offset given an x,y position
+
+    Abstract base class; subclasses must implement phase_offset(x, y).
+    """
+
+    def __init__(self, period=5):
+        self.period = period
+
+    def t_offset(self, x, y):
+        """Turns a phase offset into a time offset"""
+        return self.phase_offset(x, y) * self.period
+
+    def phase_offset(self, x, y):
+        raise NotImplementedError
+
+
+class EventHandler(object):
+    """Object to receive keyboard events from the Manager object
+
+    By default does nothing with events.
+    """
+
+    tick_rate = 0.03 # seconds
+
+    def __init__(self, keyboard):
+        self.keyboard = keyboard
+
+    def tick(self):
+        """Override this method for periodic events"""
+        pass
+
+    def event(self, key, state):
+        """Override this method for key up/down events"""
+        pass
+
+    def chord_event(self, chord):
+        """Override this method for key-chord events
+
+        chord is a list of keys pressed in the chord, in order
+        single keys are sent as a single element list
+        """
+        pass
+
+
+# Keyboard Modes
+class KeyboardMode(object):
+    """A keyboard mode represents a set of behaviors for the keyboard,
+    including lighting schemes and reactions to key presses.
+    """
+
+    def __init__(self, manager, keyboard, static_lighting, animations=None):
+        self.manager = manager
+        self.keyboard = keyboard
+        self.static_lighting = static_lighting
+        if animations is None:
+            animations = []
+        self.animations = animations
+
+        self.lights_on = True
+
+        # Use fastest tick rate of the provided animations
+        tick_rate = None
+        for animation in animations:
+            if animation.tick_rate is not None:
+                if tick_rate is None:
+                    tick_rate = animation.tick_rate
+                else:
+                    tick_rate = min(tick_rate, animation.tick_rate)
+        if not tick_rate:
+            tick_rate = None
+        self.tick_rate = tick_rate
+        #print "Tick rate of animations is: %r" % tick_rate # DEBUG
+
+    def start(self, previous_mode=None):
+        """Initializes the lighting effects and resets the key bindings."""
+        self.keyboard._cmd("rebind all")
+        self.static_lighting.start()
+        for animation in reversed(self.animations):
+            animation.tick()
+
+    def tick(self):
+        """Passes tick events on to each animation in its stack of animations.
+        """
+        for animation in reversed(self.animations):
+            animation.tick()
+
+    def is_command_toggle(self, chord):
+        """Utility function to check if we're supposed to break out to command
+        mode.
+        """
+        value = sorted(chord) == ['light', 'lock']
+        #print "is_command_toggle: %s" % value # DEBUG
+        if value:
+            #print "active modes: %r" % self.manager.active_modes # DEBUG
+            pass
+        return value
+
+    def event(self, key, state):
+        """Passes key events on to each animation in its stack of animations.
+        """
+        for animation in reversed(self.animations):
+            animation.event(key, state)
+
+    def chord_event(self, chord):
+        """Passes chord events on to each animation in its stack of animations.
+
+        Also handles the light toggle and breaking out to command mode
+        """
+        #print "chord %s" % chord # DEBUG
+        for animation in reversed(self.animations):
+            animation.chord_event(chord)
+        if chord == ["light"]:
+            self.lights_on = not self.lights_on
+            self.keyboard.lights(self.lights_on)
+        elif self.is_command_toggle(chord):
+            self.manager.mode_return()
+
Index: /rgbkbd/tags/0.1/rgbkbd/geometry.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/geometry.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/geometry.py	(revision 72)
@@ -0,0 +1,398 @@
+#!/usr/bin/python
+"""Describes the physical layout of the keyboard"""
+
+from color import Color, Colors
+
+# Keys are described by the "pixels" they cover
+# Y is in rows, the 0 row has the space bar, the the 5 row has the function
+# keys, and the 6 row has the light, lock, and mute buttons
+# Column values; there are 2 columns per normal width key.  This isn't exact,
+# but I think it would be close enough.  There are 22 key widths, so 44 columns
+# in the grid.
+# FIXME: Should add a column for the empty space on either side of the cursor
+# keys, making it 46 columns total.
+
+def _key_row(left, row, keys):
+    """Utility function to reduce how many hardcoded numbers are required in
+    the key positions description.
+    """
+    entries = []
+    for n, key in enumerate(keys):
+        entries.append( (key, [(left+2*n, row), (left+2*n+1, row)]) )
+    return entries
+
+
+key_positions = dict(
+    # Top row
+    [
+    ("light", [(30, 6), (31, 6)]),
+    ("lock", [(32, 6), (33, 6)]),
+
+    ("mute", [(38, 6), (39, 6)]),
+    #("volup", [(41, 6), (42, 6)]), # Volume scrollwheel does not have a backlight
+    #("voldn", [(41, 6), (42, 6)]),
+
+    # Function key row
+    ("esc", [(0, 5), (1, 5)]),
+
+    ] + _key_row(4, 5, [
+    "f1",
+    "f2",
+    "f3",
+    "f4",
+    ]) + [
+
+    ] + _key_row(13, 5, [
+    "f5",
+    "f6",
+    "f7",
+    "f8",
+    ]) + [
+
+    ] + _key_row(22, 5, [
+    "f9",
+    "f10",
+    "f11",
+    "f12",
+    ]) + [
+
+    ] + _key_row(30, 5, [
+    "prtscn",
+    "scroll",
+    "pause",
+    ]) + [
+
+    ] + _key_row(36, 5, [
+    "stop",
+    "prev",
+    "play",
+    "next",
+    ]) + [
+
+    # Number row
+    ] + _key_row(0, 4, [
+    "grave",
+    "1",
+    "2",
+    "3",
+    "4",
+    "5",
+    "6",
+    "7",
+    "8",
+    "9",
+    "0",
+    "minus",
+    "equal",
+    ]) + [
+    ("bspace", [(26, 4), (27, 4), (28, 4), (29, 4)]),
+
+    ] + _key_row(30, 4, [
+    "ins",
+    "home",
+    "pgup",
+
+    "numlock",
+    "numslash",
+    "numstar",
+    "numminus",
+    ]) + [
+
+    # QWERTY row
+    ("tab", [(0, 3), (1, 3), (2, 3)]),
+    ] + _key_row(3, 3, [
+    "q",
+    "w",
+    "e",
+    "r",
+    "t",
+    "y",
+    "u",
+    "i",
+    "o",
+    "p",
+    "lbrace",
+    "rbrace",
+    ]) + [
+    ("bslash", [(27, 3), (28, 3), (29, 3)]),
+
+    ] + _key_row(30, 3, [
+    "del",
+    "end",
+    "pgdn",
+
+    "num7",
+    "num8",
+    "num9",
+    ]) + [
+    ("numplus", [(42, 3), (43, 3), (42, 4), (43, 4)]), # Note this extends into the row below
+
+    # Home row
+    ("caps", [(0, 2), (1, 2), (2, 2)]),
+    ] + _key_row(3, 2, [
+    "a",
+    "s",
+    "d",
+    "f",
+    "g",
+    "h",
+    "j",
+    "k",
+    "l",
+    "colon",
+    "quote",
+    ]) + [
+    ("enter", [(26, 2), (27, 2), (28, 2), (29, 2)]),
+
+
+    ] + _key_row(36, 2, [
+    "num4",
+    "num5",
+    "num6",
+    ]) + [
+
+    # Shift row
+    ("lshift", [(0, 1), (1, 1), (2, 1), (3, 1)]),
+    ] + _key_row(4, 1, [
+    "z",
+    "x",
+    "c",
+    "v",
+    "b",
+    "n",
+    "m",
+    "comma",
+    "dot",
+    "slash",
+    ]) + [
+    ("rshift", [(24, 1), (25, 1), (26, 1), (27, 1), (28, 1), (29, 1)]),
+
+    ("up", [(32, 1), (33, 1)]),
+
+    ] + _key_row(36, 1, [
+    "num1",
+    "num2",
+    "num3",
+    ]) + [
+    ("numenter", [(42, 1), (43, 1), (42, 0), (43, 0)]), # Extends into row below
+
+    # Bottom row
+    ("lctrl", [(0, 0), (1, 0), (2, 0)]),
+    ("lwin", [(3, 0), (4, 0)]),
+    ("lalt", [(5, 0), (6, 0), (7, 0)]),
+    ("space", [(x, 0) for x in range(8, 20)]),
+    ("ralt", [(20, 0), (21, 0), (22, 0)]),
+    ("rwin", [(23, 0), (24, 0)]),
+    ("rmenu", [(25, 0), (26, 0)]),
+    ("rctrl", [(27, 0), (28, 0), (29, 0)]),
+
+    ] + _key_row(30, 0, [
+    "left",
+    "down",
+    "right",
+    ]) + [
+
+    ("num0", [(36, 0), (37, 0), (38, 0), (39, 0)]),
+    ("numdot", [(40, 0), (41, 0)]),
+
+    # The K70 does not have the extra keys
+    #("g1", [(x, y), (x, y)]),
+    #("g2", [(x, y), (x, y)]),
+    #("g3", [(x, y), (x, y)]),
+    #("g4", [(x, y), (x, y)]),
+    #("g5", [(x, y), (x, y)]),
+    #("g6", [(x, y), (x, y)]),
+    #("g7", [(x, y), (x, y)]),
+    #("g8", [(x, y), (x, y)]),
+    #("g9", [(x, y), (x, y)]),
+    #("g10", [(x, y), (x, y)]),
+    #("g11", [(x, y), (x, y)]),
+    #("g12", [(x, y), (x, y)]),
+    #("g13", [(x, y), (x, y)]),
+    #("g14", [(x, y), (x, y)]),
+    #("g15", [(x, y), (x, y)]),
+    #("g16", [(x, y), (x, y)]),
+    #("g17", [(x, y), (x, y)]),
+    #("g18", [(x, y), (x, y)]),
+
+    #("mr", [(x, y), (x, y)]),
+    #("m1", [(x, y), (x, y)]),
+    #("m2", [(x, y), (x, y)]),
+    #("m3", [(x, y), (x, y)]),
+    ]
+)
+
+
+class KeyMatrix(object):
+    """(X,Y)<->Key mapping object to allow treating the keyboard as an image
+    grid.
+    """
+    x = 44
+    y = 7
+    def __init__(self, background=Colors.BLACK):
+        # 2-dimensional array addressible as self.data[x][y]
+        self.data = [[background for y in range(self.y)] for x in range(self.x)]
+
+    def set_pixel(self, x, y, color):
+        """Sets a pixel to a particular color."""
+        try:
+            self.data[x][y] = color
+        except IndexError, error:
+            print "Failed dereferencing (%s,%s)" % (x, y)
+
+    def set_key(self, key, color):
+        """Sets all pixels for a key to a particular color."""
+        for x, y in key_positions[key]:
+            self.set_pixel(x, y, color)
+
+    def get_key(self, key):
+        """Returns the average color of the pixels for a key."""
+        colors = [self.data[x][y] for x,y in key_positions[key]]
+        # There is also a case for taking the mode instead of the mean
+        # However, for that to make a meaningful difference, we'd probably need to
+        # allocate more pixels to each key
+        return Color.average(colors)
+
+
+class Keys(object):
+    """Shortcut names for logical groups of keys on a keyboard"""
+    ALL = ','.join(key_positions.keys())
+
+    HOME = "a,s,d,f,j,k,l,colon"
+    WASD = "w,a,s,d"
+    FUNCTION = "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12"
+    NUM_PAD = \
+        "num0," \
+        "num1," \
+        "num2," \
+        "num3," \
+        "num4," \
+        "num5," \
+        "num6," \
+        "num7," \
+        "num8," \
+        "num9," \
+        "numdot," \
+        "numenter," \
+        "numlock," \
+        "numminus," \
+        "numplus," \
+        "numslash," \
+        "numstar"
+    MEDIA = \
+        "mute," \
+        "stop," \
+        "prev," \
+        "play," \
+        "next"
+    MACRO = \
+        "g1," \
+        "g2," \
+        "g3," \
+        "g4," \
+        "g5," \
+        "g6," \
+        "g7," \
+        "g8," \
+        "g9," \
+        "g10," \
+        "g11," \
+        "g12," \
+        "g13," \
+        "g14," \
+        "g15," \
+        "g16," \
+        "g17," \
+        "g18"
+    ARROW = \
+        "up," \
+        "left," \
+        "down," \
+        "right"
+    HOME_GROUP = \
+        "ins," \
+        "home," \
+        "pgup," \
+        "del," \
+        "end," \
+        "pgdn"
+    NAV = ','.join([ARROW, HOME_GROUP])
+    MOD = \
+        "lctrl," \
+        "lwin," \
+        "lalt," \
+        "lshift," \
+        "rmenu," \
+        "rctrl," \
+        "rwin," \
+        "ralt," \
+        "rshift"
+    # Typing keys are the keys that should count for WPM calculations
+    TYPING = \
+        "grave," \
+        "1," \
+        "2," \
+        "3," \
+        "4," \
+        "5," \
+        "6," \
+        "7," \
+        "8," \
+        "9," \
+        "0," \
+        "minus," \
+        "tab," \
+        "q," \
+        "w," \
+        "e," \
+        "r," \
+        "t," \
+        "y," \
+        "u," \
+        "i," \
+        "o," \
+        "p," \
+        "lbrace," \
+        "a," \
+        "s," \
+        "d," \
+        "f," \
+        "g," \
+        "h," \
+        "j," \
+        "k," \
+        "l," \
+        "colon," \
+        "quote," \
+        "z," \
+        "x," \
+        "c," \
+        "v," \
+        "b," \
+        "n," \
+        "m," \
+        "comma," \
+        "dot," \
+        "slash," \
+        "space," \
+        "f12," \
+        "rbrace," \
+        "bslash," \
+        "enter," \
+        "equal," \
+        "numslash," \
+        "numstar," \
+        "numminus," \
+        "numplus," \
+        "numenter," \
+        "num7," \
+        "num8," \
+        "num9," \
+        "num4," \
+        "num5," \
+        "num6," \
+        "num1," \
+        "num2," \
+        "num3," \
+        "num0," \
+        "numdot"
Index: /rgbkbd/tags/0.1/rgbkbd/manager.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/manager.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/manager.py	(revision 72)
@@ -0,0 +1,72 @@
+#!/usr/bin/python
+from rgbkbd.core import Keyboard
+from rgbkbd.geometry import Keys
+
+# Keyboard Modes
+from rgbkbd.modes.basicmodes import StaticMode
+from rgbkbd.modes.commandmode import CommandMode
+
+
+class KeyboardManager(object):
+    def __init__(self, device):
+        self.keyboard = Keyboard(device=device)
+
+        self.active_modes = []
+        # Initialize variables for key chord tracking
+        self.key_state = {}
+        self.chord = []
+
+        self.notifier_number, notify_filename = self.keyboard.alloc_notify()
+        self.notifier = open(notify_filename)
+
+        # CommandMode is always the last thing available
+        self.mode_start(CommandMode(self, self.keyboard))
+        # Setup default keyboard mode and start it.
+        self.mode_start(StaticMode(self, self.keyboard))
+
+    def shutdown(self):
+        # Set the keyboard to a reasonable default mode
+        self.mode_start(StaticMode(self, self.keyboard))
+        self.keyboard.free_notify(self.notifier_number)
+
+    def mode_return(self):
+        """Discards the currently active KeyboardMode mode and initializes the
+        previously active mode.
+        """
+        prev_mode = self.active_modes.pop()
+        self.current_mode().start(prev_mode)
+
+    def mode_start(self, mode):
+        """Makes the given mode the current mode and initializes it"""
+        self.active_modes.append(mode)
+        self.current_mode().start()
+
+    def current_mode(self):
+        """Returns the currently active KeyboardMode object"""
+        # Never goes empty because the CommandMode doesn't go away
+        return self.active_modes[-1]
+
+    def key_event(self, key, state):
+        """Dispatches key up, key down, and chord events to the current mode.
+        """
+        #print key, state # DEBUG
+        # Directly pass on up/down key events
+        self.current_mode().event(key, state)
+
+        # Then track key chords.  (Individual typed keys count as a single-key
+        # chord.)
+        self.key_state[key] = state
+        if state == '+': # key down
+            self.chord.append(key)
+        else: # key up
+            if set(self.key_state.values()) != set('-'):
+                # There are still keys that are being held down, so this is an
+                # incomplete chord
+                return
+            # All keys are up
+            chord = self.chord
+            self.chord = []
+            self.current_mode().chord_event(chord)
+
+    def tick_rate(self):
+        return self.current_mode().tick_rate
Index: /rgbkbd/tags/0.1/rgbkbd/modes/anglemotionmode.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/modes/anglemotionmode.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/modes/anglemotionmode.py	(revision 72)
@@ -0,0 +1,16 @@
+#!/usr/bin/python
+from rgbkbd.core import Monochrome, KeyboardMode
+from rgbkbd.color import Colors
+from rgbkbd.animation import AngleMotionPattern, MotionAnimation
+
+# Keyboard Mode
+def AngleMotionMode(manager, keyboard, colors=(Colors.WHITE, Colors.BLACK),
+        period=5, color_pattern_cls=None, angle=0.0, size=50):
+    """Keyboard mode to apply a color pattern with a linear motion"""
+    color_pattern = color_pattern_cls(colors=colors, period=period)
+    motion_pattern = AngleMotionPattern(angle=angle, size=size, period=period)
+    animation = MotionAnimation(keyboard=keyboard, color_pattern=color_pattern,
+        motion_pattern=motion_pattern)
+    return KeyboardMode(manager, keyboard,
+        static_lighting=Monochrome(keyboard, color=colors[-1]),
+        animations=[animation])
Index: /rgbkbd/tags/0.1/rgbkbd/modes/basicmodes.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/modes/basicmodes.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/modes/basicmodes.py	(revision 72)
@@ -0,0 +1,35 @@
+#!/usr/bin/python
+from rgbkbd.core import Monochrome, KeyboardMode
+from rgbkbd.color import Color, Colors
+from rgbkbd.animation import RandomAnimation, ColorAnimation
+
+# Keyboard Modes
+def StaticMode(manager, keyboard, foreground=Colors.WHITE,
+        background=Colors.BLACK):
+    return KeyboardMode(manager, keyboard,
+        static_lighting=Monochrome(keyboard, color=foreground),
+        animations=[])
+
+
+def RandomMode(manager, keyboard, foreground=None, background=None):
+    """Keyboard mode for RandomAnimation"""
+    if foreground is None:
+        foreground = Color.random8(exclude=background)
+    if background is None:
+        background = Color.random8(exclude=foreground)
+
+    return KeyboardMode(manager, keyboard,
+        static_lighting=Monochrome(keyboard, color=background),
+        animations=[
+            RandomAnimation(foreground=foreground, background=background, keyboard=keyboard),
+        ])
+
+
+def ColorMode(manager, keyboard, colors=(Colors.WHITE, Colors.BLACK),
+        period=5, color_pattern_cls=None):
+    """Keyboard mode to apply a stationary color pattern"""
+    color_pattern = color_pattern_cls(colors=colors, period=period)
+    animation = ColorAnimation(keyboard=keyboard, color_pattern=color_pattern)
+    return KeyboardMode(manager, keyboard,
+        static_lighting=Monochrome(keyboard, color=colors[-1]),
+        animations=[animation])
Index: /rgbkbd/tags/0.1/rgbkbd/modes/commandmode.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/modes/commandmode.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/modes/commandmode.py	(revision 72)
@@ -0,0 +1,166 @@
+#!/usr/bin/python
+import math
+
+from rgbkbd.core import StaticLighting, KeyboardMode
+from rgbkbd.color import Color, Colors
+from rgbkbd.geometry import Keys
+from rgbkbd.animation import \
+    AlternatingColorPattern, \
+    BeatColorPattern, \
+    ThrobColorPattern, \
+    PulseColorPattern, \
+    ColorAnimation
+
+# Keyboard Modes
+from rgbkbd.modes.basicmodes import StaticMode, RandomMode, ColorMode
+from rgbkbd.modes.typingmode import TypingMode
+from rgbkbd.modes.secretnotesmode import SecretNotesMode
+from rgbkbd.modes.anglemotionmode import AngleMotionMode
+
+
+class CommandMode(KeyboardMode):
+    """Keyboard mode for selecting a keyboard mode"""
+    _color_modes = [
+        ("grave", Colors.BLACK),
+        ("1", Colors.DARK_GREY),
+        ("2", Colors.GREY),
+        ("3", Colors.WHITE),
+        ("4", Colors.RED),
+        ("5", Colors.PURPLE),
+        ("6", Colors.BLUE),
+        ("7", Colors.CYAN),
+        ("8", Colors.GREEN),
+        ("9", Colors.YELLOW),
+        ("0", Colors.ORANGE),
+    ]
+    _color_mode_keys = [k for k, _c in _color_modes]
+    _color_mode_by_key = dict(_color_modes)
+
+    def __init__(self, manager, keyboard):
+        static_key_lighting = [
+            (Keys.ALL, Colors.BLACK), # black out everything not otherwise set
+            ("light,lock", Colors.WHITE), # exit command mode
+            ("scroll", Colors.GREEN), # discrete writing mode
+
+            ("prtscn", Colors.WHITE), # typing mode
+        ] + self._color_modes
+
+        static = StaticLighting(keyboard, profile=static_key_lighting)
+        animations = [
+            # Key for random pattern of lit keys
+            ColorAnimation(keys="home", keyboard=keyboard,
+                color_pattern=AlternatingColorPattern(colors=[Color.random8() for n in range(50)], period=0.8*50)),
+
+            # Animation control panel
+            ColorAnimation(keys="stop", keyboard=keyboard,
+                color_pattern=AlternatingColorPattern(colors=[Colors.WHITE, Colors.BLACK], period=3)),
+            ColorAnimation(keys="prev", keyboard=keyboard,
+                color_pattern=PulseColorPattern(colors=[Colors.WHITE, Colors.BLACK], period=3)),
+            ColorAnimation(keys="play", keyboard=keyboard,
+                color_pattern=ThrobColorPattern(colors=[Colors.WHITE, Colors.BLACK], period=3)),
+            ColorAnimation(keys="next", keyboard=keyboard,
+                color_pattern=BeatColorPattern(colors=[Colors.WHITE, Colors.BLACK], period=3)),
+
+            # Direction control
+            ColorAnimation(keys="num5", keyboard=keyboard,
+                color_pattern=ThrobColorPattern(colors=[Colors.BLACK, Colors.WHITE], period=3)),
+            ColorAnimation(keys="num1,num2,num3,num4,num6,num7,num8,num9",
+                keyboard=keyboard,
+                color_pattern=ThrobColorPattern(colors=[Colors.WHITE, Colors.BLACK], period=3)),
+        ]
+        super(CommandMode, self).__init__(manager, keyboard, static, animations)
+        self.previous_mode = None
+
+    def start(self, previous_mode=None):
+        """Initialize the keyboard for command mode"""
+        #print "Starting command mode" # DEBUG
+        super(CommandMode, self).start()
+        self.previous_mode = previous_mode
+        self.keyboard.unbind()
+
+    def chord_event(self, chord):
+        """Handle chords as commands"""
+        if chord == ["light"]:
+            # Allow turning off the lights
+            self.lights_on = not self.lights_on
+            self.keyboard.lights(self.lights_on)
+        elif sorted(chord) == ['light', 'lock']:
+            # exit command mode back to the previous mode
+            #print "Exiting command mode" # DEBUG
+            self.keyboard.rebind()
+            self.manager.mode_start(self.previous_mode)
+        # There are a few keyboard modes that don't take or need color modifiers
+        elif chord == ["scroll"]: # SecretNotes mode
+            self.manager.mode_start(SecretNotesMode(manager=self.manager, keyboard=self.keyboard))
+        elif chord == ["prtscn"]: # Typing speed mode
+            self.manager.mode_start(TypingMode(manager=self.manager, keyboard=self.keyboard))
+        elif chord == ["home"]: # Random mode with random color selection
+            self.manager.mode_start(RandomMode(manager=self.manager, keyboard=self.keyboard))
+        # Modes that support color modifiers
+        elif set(self._color_mode_keys).intersection(chord):
+            # They hit at least one of the color mode keys
+            directions = {
+                "num6": (0.0  * math.pi, 50),
+                "num9": (0.25 * math.pi, 30),
+                "num8": (0.5  * math.pi, 10),
+                "num7": (0.75 * math.pi, 30),
+                "num4": (1.0  * math.pi, 50),
+                "num1": (1.25 * math.pi, 30),
+                "num2": (1.5  * math.pi, 10),
+                "num3": (1.75 * math.pi, 30),
+                "num5": (None, None), # No motion; might want it to be a circular pattern?
+            }
+            mode_types = {
+                "home": RandomMode,
+            }
+            color_pattern_types = {
+                "stop": AlternatingColorPattern,
+                "prev": PulseColorPattern,
+                "play": ThrobColorPattern,
+                "next": BeatColorPattern,
+            }
+            direction = None
+            mode_type = StaticMode
+            colors = []
+            color_pattern = None
+            for key in chord:
+                if key in mode_types.keys():
+                    mode_type = mode_types[key]
+                elif key in self._color_mode_keys:
+                    colors.append(self._color_mode_by_key[key])
+                elif key in directions.keys():
+                    # Just take the last direction
+                    direction, size = directions[key]
+                elif key in color_pattern_types.keys():
+                    # Just take the last pattern
+                    color_pattern = color_pattern_types[key]
+                else:
+                    # ERROR: an unrecognized key was pressed
+                    return
+            foreground = colors[0]
+            if len(colors) > 1:
+                background = colors[1]
+            else:
+                colors.append(Colors.BLACK)
+                background = Colors.BLACK
+
+            self.keyboard.rebind()
+
+            if color_pattern is None:
+                #print "No color pattern"
+                mode = mode_type(manager=self.manager, keyboard=self.keyboard,
+                    foreground=foreground, background=background)
+            else:
+                if direction is None:
+                    #print "No direction" # DEBUG
+                    mode = ColorMode(manager=self.manager,
+                        keyboard=self.keyboard, colors=colors, period=15,
+                        color_pattern_cls=color_pattern)
+                else:
+                    #print "Direction is %s" % direction # DEBUG
+                    mode = AngleMotionMode(manager=self.manager,
+                        keyboard=self.keyboard, colors=colors, period=15,
+                        color_pattern_cls=color_pattern, angle=direction, size=size*len(colors)/2)
+
+            self.manager.mode_start(mode)
+        # Ignore unrecognized chord events
Index: /rgbkbd/tags/0.1/rgbkbd/modes/secretnotesmode.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/modes/secretnotesmode.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/modes/secretnotesmode.py	(revision 72)
@@ -0,0 +1,89 @@
+#!/usr/bin/python
+import os
+import time
+
+from rgbkbd.core import Monochrome, KeyboardMode
+from rgbkbd.color import Colors
+from rgbkbd.animation import RandomAnimation
+
+
+class SecretNotesMode(KeyboardMode):
+    """A KeyboardMode that will unbind all keys so the OS does not see what is
+    typed, but it saves what is typed to a file in the user's home directory
+    called .secret-<unixepochtime>.  In other words, this gives a discrete
+    note-taking application.
+    """
+    # A mapping to give more readable output for the note taking files
+    key_maps = {
+        "common": { # same shift or no shift
+            "enter": "\n",
+            "numenter": "\n",
+            "space": " ",
+            "tab": "\t",
+            "bspace": "\b",
+        },
+        False: { # no shift
+            "bslash": "\\",
+            "colon": ";",
+            "comma": ",",
+            "dot": ".",
+            "equal": "=",
+            "grave": "`",
+            "lbrace": "[",
+            "minus": "-",
+            "quote": "'",
+            "rbrace": "]",
+            "slash": "/",
+        },
+        True: { # shift
+            "bslash": "|",
+            "colon": ":",
+            "comma": "<",
+            "dot": ">",
+            "equal": "+",
+            "grave": "~",
+            "lbrace": "{",
+            "minus": "_",
+            "quote": "\"",
+            "rbrace": "}",
+            "slash": "?",
+        },
+    }
+    for c in "abcdefghijklmnopqrstuvwxyz":
+        key_maps[False][c] = c
+        key_maps[True][c] = c.upper()
+    for n, c in zip("1234567890", "!@#$%^&*()"):
+        key_maps[False][n] = n
+        key_maps[True][n] = c
+
+    def __init__(self, manager, keyboard):
+        super(SecretNotesMode, self).__init__(manager, keyboard,
+            static_lighting=Monochrome(keyboard, color=Colors.BLACK),
+            animations=[
+                RandomAnimation(foreground=Colors.GREEN, background=Colors.BLACK, keyboard=keyboard),
+            ])
+        self.out = None
+        self.state = {
+            "shift": False,
+        }
+
+    def start(self, previous_mode=None):
+        """Initialize the keyboard mode"""
+        super(SecretNotesMode, self).start()
+        # disable all keys so the OS doesn't see the keypresses
+        self.keyboard.unbind()
+        filename = os.path.expanduser("~/.secret-%s" % int(time.time()))
+        self.out = open(filename, 'a')
+
+    def event(self, key, state):
+        """Handle key events"""
+        if key in ["lshift", "rshift"]:
+            self.state["shift"] = (state == '+')
+        elif state == '+':
+            # Translate key presses into characters to output.
+            try:
+                value = self.key_maps["common"][key]
+            except KeyError:
+                value  = self.key_maps[self.state["shift"]].get(key, "<%s>" % key)
+            self.out.write(value)
+            self.out.flush()
Index: /rgbkbd/tags/0.1/rgbkbd/modes/typingmode.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd/modes/typingmode.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd/modes/typingmode.py	(revision 72)
@@ -0,0 +1,170 @@
+#!/usr/bin/python
+import time
+
+from rgbkbd.core import StaticLighting, KeyboardMode, EventHandler
+from rgbkbd.color import Color, Colors
+from rgbkbd.geometry import Keys
+
+
+# Lighting animation
+class TypingSpeedAnimation(EventHandler):
+    """Displays typing speeds (current, peak, sustained) in 10's of WPM along
+    the number row of keys.
+
+    Current speed is shown by a bar of white keys with a fading effect.
+    Peak speed is shown by a single yellow key, unless it exceeds the width of
+    the bar, in which case it will show as red on the highest value key.
+    Sustained speed is shown by a single green key, unless it exceeds the width
+    of the bar, in which case it will be shown as a single blue key on the
+    highest value key.
+    When there is a conflict on colors to display, the sustained value
+    overrides the peak value which overrides the current value.
+    """
+    tick_rate = 0.1
+    light_decay_seconds = 0.3
+    # Number of seconds of data to use for the current speed value
+    running_avg_seconds = 2
+    # Number of seconds of current speed in which to track peak speed
+    peak_seconds = 10
+    # Number of seconds to use for the sustained speed.  The intention is that
+    # this should be long enough time that it doesn't vary much on bursts of
+    # keystrokes.  It should reflect what you would be doing if you were typing
+    # non-stop such as composing text or doing data entry.
+    sustained_avg_seconds = 60
+    # Keys to use for the display of typing speed.
+    # '1' = >=10WPM, '2' = >=20WPM, ... '0' = >=100WPM, '=' = >=120WPM
+    # So when the '=' key goes red, that means you've peaked at over 130WPM;
+    # and if it goes blue, you have sustained over 130WPM for at least a
+    # minute.
+    display_bar = list("1234567890") + ["minus", "equal"]
+
+    def __init__(self, keyboard):
+        super(TypingSpeedAnimation, self).__init__(keyboard)
+        self.last_tick = time.time()
+        self.key_history = {}
+
+    def tick(self):
+        """Handler for tick events"""
+        # Display in units of 10WPM so we can represent a reasonable
+        # touch-typing range of WPM
+        self.display_rates([r/10. for r in self.calc_wpm_rates()])
+
+    def event(self, key, state):
+        """Handler for key events"""
+        #print "event: %s %s" % (key, state)
+        now = round(time.time(), 1) # tenth-second granularity
+        if state == '+':
+            keystrokes = self.key_history.get(now, 0)
+            if key in ['bspace', 'del']:
+                delta = -1
+            elif key in Keys.TYPING:
+                delta = 1
+            else:
+                delta = 0
+            self.key_history[now] = keystrokes + delta
+        self.tick()
+
+    def calc_cpm_rates(self):
+        """Returns a list of rates in characters per minute.  The lowest index
+        is the most recent rate.
+        """
+        seconds_of_history = max(self.running_avg_seconds + max(self.light_decay_seconds, self.peak_seconds), self.sustained_avg_seconds+1)
+        now = time.time()
+        total_keystrokes = [0,] * int(seconds_of_history / self.tick_rate)
+
+        for timestamp, keystrokes in sorted(self.key_history.items()):
+            if timestamp <= now - seconds_of_history:
+                # Age off old data
+                # We can modify the underlying dictionary because we have
+                # created a list of the items in the setup of the for loop
+                del self.key_history[timestamp]
+            else: # This one counts
+                age = now-timestamp # how many seconds old it is
+                bucket = int(age / self.tick_rate)
+                total_keystrokes[bucket] += keystrokes
+        return [c/self.tick_rate*60. for c in total_keystrokes]
+
+    def calc_wpm_rates(self):
+        """Returns rates in words per minute.  1 WPM is defined as 5 CPM."""
+        return [c/5. for c in self.calc_cpm_rates()]
+
+    def running_average(self, rate_data, amount):
+        """Utility function to calculate a running average of a given width
+        over a set of data.
+        """
+        return [sum(rate_data[n:n+amount])/amount for n in range(len(rate_data)-amount)]
+
+    def display_rates(self, rate_data):
+        """Update the keyboard lights to display the given rate data."""
+        # Calculate a running average of the data; otherwise the output is too
+        # volatile; hitting a few keys in very rapid succession can make for an
+        # misleading peak value.
+        sustained_rate = int(max(self.running_average(rate_data, int(self.sustained_avg_seconds / self.tick_rate)) + [0]))
+        rate_data = self.running_average(rate_data, int(self.running_avg_seconds / self.tick_rate))
+
+        #print max(rate_data), rate_data[:30], '...' # DEBUG
+
+        # intensities are in the range [0-1]; an intensity for each key in the display bar
+        intensities = [0,] * len(self.display_bar)
+        # Iterate over the data starting at the oldest data
+        for rate in reversed(rate_data[:int(self.light_decay_seconds/self.tick_rate)]):
+            # linear decay
+            intensities = [max(0.0, i-self.tick_rate/self.light_decay_seconds) for i in intensities]
+            for i in range(min(int(rate), len(self.display_bar))):
+                intensities[i] = 1.0 # peg the new data
+
+        # Determine preliminary colors for the keys based on the current typing speed
+        key_colors = {}
+        for intensity, key in zip(intensities, self.display_bar):
+            color = self.intensity_to_color(intensity)
+            key_colors[key] = color
+
+        # Indicate peak speed, if >0
+        peak = int(max(rate_data[:int(self.peak_seconds/self.tick_rate)]))
+        if peak:
+            key = self.display_bar[min(peak, len(self.display_bar))-1]
+            if peak > len(self.display_bar): # Blow-out!
+                color = Colors.RED
+            else:
+                color = Colors.YELLOW
+            key_colors[key] = color
+
+        # Indicate sustained speed, if >0
+        if sustained_rate:
+            key = self.display_bar[min(sustained_rate, len(self.display_bar))-1]
+            if sustained_rate > len(self.display_bar): # Blow-out!
+                color = Colors.BLUE
+            else:
+                color = Colors.GREEN
+            key_colors[key] = color
+
+        for key, color in key_colors.items():
+            self.keyboard.set_keys(key, color)
+
+        #print intensities, peak # DEBUG
+
+    def intensity_to_color(self, intensity):
+        """Convert intensity, a value in [0, 1], into a shade of grey."""
+        color_value = min(255, intensity * 256)
+        return Color(red=color_value, green=color_value, blue=color_value)
+
+
+# Keyboard Mode
+def TypingMode(manager, keyboard):
+    profile = [
+        (Keys.ALL, Color.fromstring('e0e0e0')),
+        (Keys.HOME, Colors.BLUE),
+        (Keys.NUM_PAD, Colors.GREEN),
+        (Keys.FUNCTION, Colors.RED),
+        (Keys.MEDIA, Colors.DARKCYAN),
+        (Keys.NAV, Colors.YELLOW),
+        (Keys.MOD, Colors.PURPLE),
+        ("lock", Colors.BLACK), # Windows Lock key
+        ("light", Colors.BLACK), # Light key
+        ("caps", Colors.BLACK), # Caps Lock key
+    ]
+    return KeyboardMode(manager, keyboard,
+        static_lighting=StaticLighting(keyboard, profile=profile),
+        animations = [
+            TypingSpeedAnimation(keyboard),
+        ])
Index: /rgbkbd/tags/0.1/rgbkbd_controller.py
===================================================================
--- /rgbkbd/tags/0.1/rgbkbd_controller.py	(revision 72)
+++ /rgbkbd/tags/0.1/rgbkbd_controller.py	(revision 72)
@@ -0,0 +1,119 @@
+#!/usr/bin/python
+# expects ckb-daemon to be running, but the ckb user interface (including the
+# icon in the tray) to not be running.
+
+import sys
+import optparse
+import select
+import re
+
+from rgbkbd.manager import KeyboardManager
+
+
+class Controller(object):
+    def __init__(self, keyboard=None):
+        self.keyboards = {}
+
+    def open_keyboard(self, device):
+        self.keyboards[device] = KeyboardManager(device)
+
+    def run(self):
+        """Primary event loop"""
+        try:
+            main_notifier = open('/dev/input/ckb0/notify0', 'r')
+        except IOError, error:
+            sys.stderr.write("The ckb-daemon must be running before starting "
+                "this application.\n")
+            sys.stderr.flush()
+            return
+
+        key_event_re = re.compile('key (?P<state>[-+])(?P<key>.*)', re.M)
+
+        for n in range(1,10):
+            try:
+                self.open_keyboard(device='/dev/input/ckb%s' % n)
+                #sys.stderr.write("Keyboard %s found\n" % n) # DEBUG
+            except Exception, error:
+                pass
+                #sys.stderr.write("Keyboard %s not found (%s)\n" % (n, error)) # DEBUG
+            #sys.stderr.flush() # DEBUG
+
+        notifiers = [main_notifier]
+        notifiers.extend(x.notifier for x in self.keyboards.values())
+
+        try:
+            while True:
+                read_events, write_events, err_events = \
+                    select.select(notifiers, [], notifiers, self.tick_rate())
+                if err_events:
+                    print "Error events %s" % err_events
+                for read_event in read_events:
+                    if read_event == main_notifier:
+                        event = main_notifier.readline()
+                        # print "Event on ckb0/notify0: %s" % event # DEBUG
+                        words = event.split()
+                        if words[0] == 'device' and words[2] == 'added':
+                            # print "connecting new keyboard" # DEBUG
+                            new_kbd = words[-1]
+                            self.open_keyboard(new_kbd)
+                            notifiers.append(self.keyboards[new_kbd].notifier)
+                        elif words[0] == 'device' and words[2] == 'removed':
+                            kbd = words[-1]
+                            old_keyboard_manager = self.keyboards[kbd]
+                            del self.keyboards[kbd]
+                            notifiers.remove(old_keyboard_manager.notifier)
+                    else:
+                        keyboard_manager_matched = [x for x in self.keyboards.values()
+                            if x.notifier == read_event]
+                        if keyboard_manager_matched:
+                            # We could get an event on a keyboard at the same
+                            # time we get a notification of its removal.
+                            keyboard_manager = keyboard_manager_matched[0]
+
+                            line = read_event.readline()
+                            key_match = key_event_re.match(line)
+                            if key_match:
+                                keyboard_manager.key_event(**key_match.groupdict())
+                        else:
+                            print "Read event on %r does not match a keyboard" % read_event
+
+                # Send tick events to all keyboard managers
+                for keyboard_manager in self.keyboards.values():
+                    keyboard_manager.current_mode().tick()
+        except KeyboardInterrupt:
+            # Exit cleanly on ^C
+            pass
+        finally:
+            self.shutdown()
+        return
+
+    def tick_rate(self):
+        """Calculate a tick rate to use to meet the requirements across all
+        attached keyboards.
+        """
+        tick_rates = [km.current_mode().tick_rate for km in self.keyboards.values()]
+        tick_rates = [x for x in tick_rates if x]
+        if tick_rates:
+            return min(tick_rates)
+        return None
+
+    def shutdown(self):
+        for keyboard_manager in self.keyboards.values():
+            keyboard_manager.shutdown()
+
+
+def main(argv):
+    """Run the keyboard manager"""
+    parser = optparse.OptionParser("Usage: %s [options]" % argv[0])
+    parser.add_option('-k', '--keyboard', type="int", default=1,
+        help="Keyboard number to manipulate")
+
+    (options, args) = parser.parse_args(argv[1:])
+
+    manager = Controller()
+    manager.run()
+    return 0
+
+
+if __name__ == '__main__':
+    sys.exit(main(sys.argv))
