Commits

3k committed 7524637

added setup.py, keyboard support, screenshot function

Comments (0)

Files changed (15)

 syntax: glob
-
+.project
+.pydevproject
+.settings
+MANIFEST
+dist
 *.pyc
 *.png
 *.jpg
 *.gif
 *.bmp
-.project
-.pydevproject
-.settings
-
 pilpal version history
 ======================
 
+1.1.0
+-----
+
+* First package release
+* Added support for keyboard shortcuts
+* Silent (-s) option now really makes sense
+* Updated default template
+* Better Python3 compatibility
+
 1.0.3
 -----
 
 -----
 
 * Added default template script
-* Other small fixes 
+* Other small fixes
 
 1.0.0
 -----
 state the exclusion of warranty; and each file should have at least
 the "copyright" line and a pointer to where the full notice is found.
 
-		pilpal - A simple utility to make image generation easier.
-    Copyright (C) 2013  Károly Kiripolszky
+    <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
   If the program does terminal interaction, make it output a short
 notice like this when it starts in an interactive mode:
 
-    pilpal  Copyright (C) 2013  Károly Kiripolszky
+    <program>  Copyright (C) <year>  <name of author>
     This program 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 library.  If this is what you want to do, use the GNU Lesser General
 Public License instead of this License.  But first, please read
 <http://www.gnu.org/philosophy/why-not-lgpl.html>.
-
-       _ .-.               .-.  
-      :_;: :               : :  
-.---. .-.: :  .---.  .--.  : :  
-: .; `: :: :_ : .; `' .; ; : :_ 
+
+       _ .-.               .-.
+      :_;: :               : :
+.---. .-.: :  .---.  .--.  : :
+: .; `: :: :_ : .; `' .; ; : :_
 : ._.':_;`.__;: ._.'`.__,_;`.__;
-: :           : :               
-:_;           :_;               
-                   version 1.0.3
+: :           : :
+:_;           :_;
+                   version 1.1.0
 
 Overview
---------
+========
 
 pilpal can be used to get instant visual feedback from scripts that generate
 image and are based on Python Imaging Library (PIL).
 
 * Invoke pilpal like so:
 
-  ./pilpal.py test.py
+  pilpal test.py
 
 * pilpal will display the image (in this case test.png by default)
 * If you change and save your code again the displayed image will be updated
+
+  Note: As of 1.1.0 you can press the 'r' key to refresh the display if the
+        image window has focus
+
 * If your program outputs an image with a different filename, use the -o
   switch to specify that filename, for example:
 
-  ./pilpal.py -o output.jpg test.py
+  pilpal.py -o output.jpg test.py
 
 Command-line help
 -----------------
 
-usage: pilpal.py [-h] [-o OUTPUT_FILE] [-y] [-s] input_file
+usage: pilpal [-h] [-o OUTPUT_FILE] [-y] [-s] [-k] [-v] input_file
+
+Quick and simple graphics programming.
 
 positional arguments:
   input_file            python source file
   -y, --yes             automatically create a new file if source file does
                         not exist
   -s, --silent          disable update messages
+  -k, --key-help        list available keyboard shortcuts and exit
+  -v, --version         show program's version number and exit
+
+Keyboard shortcuts
+------------------
+
+These shortcut keys are available when the display window has focus:
+
+  <F5>                  Updates the display window.
+  <F3>                  Saves current output as a unique image.
+  <F2>                  Shows information about the current image.
+  <F1>                  Displays keyboard help.
+  <F10>                 Closes the display window and the running script.
 
 Dependencies
 ------------
 
     http://www.pythonware.com/library/pil/handbook/index.htm
 
+License
+-------
+
+pilpal is licensed under GPLv3, see the COPYING file for details.
+
 Author
 ------
 
+#!/usr/bin/python
+# encoding: utf-8
+# vim: set filetype=python
+#
+# This file is part of pilpal.
+#
+# pilpal - Simple and quick graphics programming using Python Imaging Library
+# Copyright (C) 2013  Károly Kiripolszky
+#
+# pilpal 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 3 of the License, or
+# (at your option) any later version.
+#
+# pilpal 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 pilpal.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+import os
+import sys
+import argparse
+
+try:
+    import Image
+    import ImageDraw
+    import ImageFont
+except ImportError:
+    print("*** The required package python-imaging (PIL) is not available. Exiting.")
+    sys.exit()
+
+try:
+    import ImageTk
+except ImportError:
+    print("*** The required package python-imaging-tk is not available. Exiting.")
+    sys.exit()
+
+try:
+    from pilpal import pilpal as pp
+except ImportError:
+    rootpath = os.path.dirname(os.path.realpath(os.path.join(__file__, "../")))
+    sys.path.insert(0, rootpath)
+    try:
+        from pilpal import pilpal as pp
+    except ImportError:
+        print("*** pilpal is not available or not installed properly. Exiting.")
+        sys.exit()
+
+
+class KeyboardHelpAction(argparse.Action):
+    def __call__(self, parser, namespace, values, option_string=None):
+        print("Available keyboard shortcuts:")
+        for line in pp.get_key_listing():
+            print(line)
+        sys.exit()
+
+
+parser = argparse.ArgumentParser(description="Quick and simple graphics programming.")
+parser.add_argument("input_file",
+    help="python source file")
+parser.add_argument("-o", "--output", dest="output_file",
+    help="defaults to the basename of the source file with .png extension")
+parser.add_argument("-y", "--yes", action="store_true", dest="force_create",
+    help="automatically create a new file if source file does not exist")
+parser.add_argument("-s", "--silent", action="store_true", dest="silent",
+    help="disable update messages")
+parser.add_argument("-k", "--key-help", nargs=0, action=KeyboardHelpAction,
+    help="list available keyboard shortcuts and exit")
+parser.add_argument("-v", "--version", action="version", version="pilpal {0}".format(pp.__version__))
+
+args = parser.parse_args()
+input_file = args.input_file
+image_file = args.output_file if args.output_file is not None else input_file.replace(".py", ".png")
+
+if not args.silent:
+    print("pilpal {0}".format(pp.__version__))
+
+try:
+    if not os.path.exists(input_file):
+        if not args.force_create:
+            s = raw_input("Do you want to create '{0}'? [y/n]: ".format(input_file))
+            if s == "y":
+                pp.create_script(input_file, image_file)
+            else:
+                sys.exit()
+        else:
+            pp.create_script(input_file, image_file)
+
+    pp.initialize(input_file, image_file, args.silent)
+    pp.observer.start()
+    pp.root.mainloop()
+    while True:
+        pass
+except (KeyboardInterrupt, SystemExit):
+    if pp.observer is not None:
+        pp.observer.running = False
+        pp.observer.join()
+    if not args.silent:
+        print("bye!")
+    sys.exit()
+

fonts/DroidSans-Bold.ttf

Binary file added.

fonts/DroidSansMono.ttf

Binary file added.
+
+   Copyright (c) 2005-2008, The Android Open Source Project
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+

fonts/trebuc.ttf

Binary file removed.

fonts/trebucbd.ttf

Binary file removed.

pilpal.py

-#!/usr/bin/python
-# encoding: utf-8
-#
-# pilpal - Simple and quick graphics programming using Python Imaging Library
-# Copyright (C) 2013  Károly Kiripolszky
-#
-# pilpal 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 3 of the License, or
-# (at your option) any later version.
-#
-# pilpal 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 pilpal.  If not, see <http://www.gnu.org/licenses/>.
-#
-
-__author__ = "Károly Kiripolszky"
-__version__ = "1.0.3"
-
-
-import sys, os
-import traceback
-import argparse
-import time
-from datetime import datetime
-from importlib import import_module
-from threading import Thread
-import Tkinter
-
-import Image, ImageDraw, ImageFont
-
-
-TEMPLATE = """import Image, ImageDraw
-
-size = (512, 512)
-img = Image.new("RGB", size, "gray")
-
-img.save("%s")
-"""
-
-
-class Observer(Thread):
-    
-    LOG_NORMAL = "  "
-    LOG_INFO = "* "
-    LOG_ERROR = "*** "
-
-    def __init__(self, tk, src, imgfile, silent=False):
-        Thread.__init__(self)
-        self.root = tk
-        self.src = src
-        self.imgfile = imgfile
-        self.modname = src.replace(".py", "")
-        self.silent = silent
-        self.last_src_mtime = 0
-        self.old_label_img = None
-        self.running = False
-        self.delay = 0.1
-        self.font_norm = ImageFont.truetype("fonts/trebuc.ttf", 16)
-        self.font_bold = ImageFont.truetype("fonts/trebucbd.ttf", 16)
-
-    def log(self, s, deco=None):
-        if self.silent:
-            return
-        print("".join((deco if deco is not None else self.LOG_INFO, s)))
-    
-    def display_image(self, img):
-        root.geometry("%dx%d" % (img.size[0], img.size[1]))
-        tkimg = ImageTk.PhotoImage(img)
-        label_img = Tkinter.Label(self.root, image=tkimg)
-        label_img.image = tkimg
-        label_img.place(x=0, y=0, width=img.size[0], height=img.size[1])
-        label_img.pack()
-        if self.old_label_img is not None:
-            self.old_label_img.destroy()
-        self.old_label_img = label_img
-
-    def display_file(self, path):
-        img = Image.open(path)
-        root = self.root
-        root.title(path)
-        self.display_image(img)
-
-    def display_error(self, excinfo):
-        et, ev, tb = excinfo
-        lines = traceback.format_exception(et, ev, tb)
-        heightpx = 0
-        widthpx = 0
-        longest = ""
-        for line in lines:
-            more_lines = line.split("\n")
-            for s in more_lines:
-                if len(s.strip()) == 0:
-                    continue
-                size = self.font_norm.getsize(s)
-                heightpx = heightpx + size[1]
-                if widthpx < size[0]:
-                    widthpx = size[0]
-        img = Image.new("RGB", (widthpx + 24, heightpx + 64), (16, 16, 16))
-        d = ImageDraw.Draw(img)
-        d.text((8, 8), "ERROR", font=self.font_bold)
-        i = 1
-        for line in lines:
-            more_lines = line.split("\n")
-            for s in more_lines:
-                if len(s.strip()) == 0:
-                    continue
-                d.text((8, 24 + (20 * i)), s.rstrip(), font=self.font_norm)
-                i = i + 1
-        del d
-        self.root.title(self.src)
-        self.display_image(img)
-
-    def run(self):
-        self.log("using source: %s" % self.src, self.LOG_NORMAL)
-        self.running = True
-        while self.running:
-            try:
-                # check modification
-                new_mtime = os.path.getmtime(src)
-                if self.last_src_mtime == new_mtime:
-                    time.sleep(self.delay)
-                    continue
-                # saving timestamp
-                logvars = (datetime.now().isoformat(), new_mtime, imgfile)
-                if self.last_src_mtime == 0:
-                    self.log("initial @ %s: %d => %s" % logvars)
-                else:
-                    self.log("changed @ %s: %d => %s" % logvars)
-                self.last_src_mtime = new_mtime
-                # reload source module
-                mod = import_module(self.modname)
-                reload(mod)
-                # open image
-                self.display_file(imgfile)
-            except OSError:
-                self.log("Cannot access source file: %s" % src, self.LOG_ERROR);
-                raise SystemExit()
-            except ImportError:
-                self.log("Error importing module: %s" % self.modname, self.LOG_ERROR)
-                raise SystemExit()
-            except Exception:
-                # error happened in source script
-                excinfo = sys.exc_info()
-                self.display_error(excinfo)
-                et, ev, tb = excinfo
-                traceback.print_exception(et, ev, tb, file=sys.stdout)
-                print("---")
-                time.sleep(self.delay)
-                continue
-
-
-root = None
-observer = None
-src = None
-imgfile = None
-args = None
-
-
-def create_script(path):
-    global TEMPLATE
-    try:
-        tmp = open(path, "w+")
-        tmp.write(TEMPLATE % imgfile)
-        tmp.close()
-        print("".join((Observer.LOG_NORMAL, "created module: ", path)))
-    except IOError:
-        print("*** Error creating file: %s. Exiting." % path)
-        raise SystemExit()
-
-
-def display(img):
-    global observer
-    observer.display_image(img)
-
-
-def initialize():
-    global observer, root
-    root = Tkinter.Tk()
-    observer = Observer(root, args.input_file, imgfile, args.silent)
-    observer.daemon = True
-
-
-if __name__ == "__main__":
-    print("pilpal %s" % __version__)
-
-    try:
-        import Image
-    except ImportError:
-        print("*** The required package Python Imaging Library (PIL) is not available. Exiting.")
-        sys.exit()
-
-    try:
-        import ImageTk
-    except ImportError:
-        print("*** The required package python-imaging-tk is not available. Exiting.")
-        sys.exit()
-
-    parser = argparse.ArgumentParser(description="Quick and simple graphics programming.")
-    parser.add_argument("input_file",
-        help="python source file")
-    parser.add_argument("-o", "--output", dest="output_file",
-        help="defaults to the basename of the source file with .png extension")
-    parser.add_argument("-y", "--yes", action="store_true", dest="force_create",
-        help="automatically create a new file if source file does not exist")
-    parser.add_argument("-s", "--silent", action="store_true", dest="silent",
-        help="disable update messages")
-
-    args = parser.parse_args()
-    src = args.input_file
-    imgfile = args.output_file if args.output_file is not None else src.replace(".py", ".png")
-
-    try:
-        if not os.path.exists(src):
-            if not args.force_create:
-                s = raw_input("Do you want to create %s? [y/n]: " % src)
-                if s == "y":
-                    create_script(src)
-                else:
-                    raise SystemExit()
-            else:
-                create_script(src)
-
-        initialize()
-        observer.start()
-        root.mainloop()
-        while True:
-            pass
-    except (KeyboardInterrupt, SystemExit):
-        if observer is not None:
-            observer.running = False
-            observer.join()
-        print("bye!")
-        sys.exit()
-
+# encoding: utf-8
+# 
+# This file is part of pilpal.
+#
+# pilpal - Simple and quick graphics programming using Python Imaging Library
+# Copyright (C) 2013  Károly Kiripolszky
+#
+# pilpal 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 3 of the License, or
+# (at your option) any later version.
+#
+# pilpal 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 pilpal.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+__author__ = "Károly Kiripolszky"
+__version__ = "1.1.0"
+
+__all__ = ["pilpal", "geom"]
+
+from pilpal import *
+
+# encoding: utf-8
+#
+# This file is part of pilpal.
+#
+# pilpal - Simple and quick graphics programming using Python Imaging Library
+# Copyright (C) 2013  Károly Kiripolszky
+#
+# pilpal 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 3 of the License, or
+# (at your option) any later version.
+#
+# pilpal 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 pilpal.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+from math import sqrt, pow, sin, cos, atan2
+
+
+def dist(p1, p2):
+    """Calculates the distance between two points.
+    """
+    return sqrt(pow(p1[0] - p2[0], 2) + pow(p1[1] - p2[1], 2))
+
+
+def move(p, angle, distance):
+    """Moves a point in the given direction by the given distance.
+    """
+    return (p[0] + cos(angle) * distance, p[1] + sin(angle) * distance)
+
+
+def angle(p1, p2):
+    """Returns the angle between two points in radians.
+    """
+    return atan2(p2[1] - p1[1], p2[0] - p1[0])
+# encoding: utf-8
+#
+# This file is part of pilpal.
+#
+# pilpal - Simple and quick graphics programming using Python Imaging Library
+# Copyright (C) 2013  Károly Kiripolszky
+#
+# pilpal 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 3 of the License, or
+# (at your option) any later version.
+#
+# pilpal 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 pilpal.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+import sys
+import os
+import shutil
+import traceback
+import time
+from datetime import datetime
+from importlib import import_module
+from threading import Thread
+from Queue import Queue, Empty
+import Tkinter
+
+import Image
+import ImageDraw
+import ImageFont
+import ImageTk
+
+from . import __version__
+
+
+#
+# Module variables
+#
+
+DEFAULT_TITLE = "pilpal {0}".format(__version__)
+SCRIPT_TEMPLATE = """import Image, ImageDraw
+
+size = (512, 512)
+img = Image.new("RGB", size, "gray")
+
+draw = ImageDraw.Draw(img)
+# put your drawing logic here
+
+img.save("{0}")
+"""
+SCREENSHOT_FILE = "{0}-{1:04}{2}"
+NL = "<:BREAK:>"
+
+root = None
+observer = None
+src = None
+output_file = None
+evt_queue = None
+msg_queue = None
+
+
+#
+# Classes
+#
+
+class Theme:
+    """Holds default theme configuration.
+    """
+    MSG_BG = (46, 38, 51)
+    MSG_FG = (220, 220, 220)
+    MSG_HEADER_BG = (85, 81, 82)
+    MSG_HEADER_FG = (240, 240, 240)
+
+    FONT_SIZE = 16
+    FONT_BOOK = "fonts/DroidSansMono.ttf"
+    FONT_BOLD = "fonts/DroidSans-Bold.ttf"
+
+    @classmethod
+    def from_dict(cls, d):
+        """Loads theme configuration from a dictionary object.
+        """
+        for k, _ in cls.__dict__.items():
+            if k.startswith("__"):
+                continue
+            if k in d:
+                cls.__dict__[k] = d[k]
+
+
+class Observer(Thread):
+    """Observes changes in the source code and updates the display window.
+    """
+    LOG_NORMAL = "  "
+    LOG_INFO = "* "
+    LOG_ERROR = "*** "
+
+    def __init__(self, tk, src, output_file, silent=False):
+        Thread.__init__(self)
+        self.root = tk
+        self.src = src
+        self.output_file = output_file
+        self.modname = src.replace(".py", "")
+        self.silent = silent
+        self.last_src_mtime = 0
+        self.old_label_img = None
+        self.running = False
+        self.delay = 0.1
+        self.font_book = ImageFont.truetype(Theme.FONT_BOOK, Theme.FONT_SIZE)
+        self.font_bold = ImageFont.truetype(Theme.FONT_BOLD, Theme.FONT_SIZE)
+
+    def log(self, s, deco=None):
+        if self.silent:
+            return
+        print("".join((deco if deco is not None else self.LOG_INFO, s)))
+
+    def display_image(self, image, wtitle=None):
+        self.root.title(wtitle if wtitle is not None else self.src)
+        self.root.geometry("{0:n}x{1:n}".format(image.size[0], image.size[1]))
+        tkimg = ImageTk.PhotoImage(image)
+        label_img = Tkinter.Label(self.root, image=tkimg, takefocus=1)
+        label_img.image = tkimg
+        label_img.place(x=0, y=0, width=image.size[0], height=image.size[1])
+        label_img.pack()
+        if self.old_label_img is not None:
+            self.old_label_img.destroy()
+        self.old_label_img = label_img
+
+    def display_file(self, path):
+        if not os.path.exists(path):
+            self.display_message("image not found:", path, self.src);
+            return False
+        self.display_image(Image.open(path), path)
+        return True
+
+    def display_message(self, header, lines, wtitle=None):
+        img = self.create_message(header, lines)
+        self.display_image(img, wtitle)
+
+    def display_error(self, et, ev, tb):
+        lines = traceback.format_exception(et, ev, tb)
+        self.display_message("ooops, an error occured!", lines)
+
+    def create_message(self, header, lines):
+        header = header.upper()
+        heightpx = 0
+        widthpx = 0
+        if lines.__class__ is not list:
+            lines = [lines]
+        lines.insert(0, header)
+        for line in lines:
+            more_lines = str(line).split("\n")
+            for s in more_lines:
+                if len(s.strip()) == 0:
+                    continue
+                s = s.replace("\t", "    ")
+                size = self.font_book.getsize(s)
+                heightpx = heightpx + size[1]
+                if widthpx < size[0]:
+                    widthpx = size[0]
+        lines.remove(header)
+
+        top_margin = int(round(Theme.FONT_SIZE / 2))
+        left_margin = top_margin
+
+        line_height = int(round(Theme.FONT_SIZE * 1.25))
+        wtitle_height = Theme.FONT_SIZE * 2
+
+        top = wtitle_height + top_margin
+        widthpx = widthpx + wtitle_height
+        heightpx = heightpx + top
+
+        img = Image.new("RGB", (widthpx, heightpx), Theme.MSG_BG)
+        d = ImageDraw.Draw(img)
+        d.rectangle([(0, 0), (widthpx, wtitle_height)], Theme.MSG_HEADER_BG)
+        d.text((left_margin, top_margin), header, font=self.font_bold,
+            fill=Theme.MSG_HEADER_FG)
+        i = 0
+        for line in lines:
+            more_lines = str(line).split("\n")
+            for s in more_lines:
+                if len(s.strip()) == 0:
+                    continue
+                s = s.replace("\t", "    ")
+                if s != NL:
+                    d.text((left_margin, top + (line_height * i)), s.rstrip(),
+                        font=self.font_book, fill=Theme.MSG_FG)
+                i = i + 1
+        return img
+
+    def reload(self):
+        reload(import_module(self.modname))
+        return self.display_file(self.output_file)
+
+    def source_modified(self):
+        new_mtime = os.path.getmtime(self.src)
+        if self.last_src_mtime == new_mtime:
+            return False
+        logvars = (datetime.now().isoformat(), self.output_file)
+        if self.last_src_mtime == 0:
+            self.log("initial @ {0[0]}: {0[1]}".format(logvars))
+        else:
+            self.log("changed @ {0[0]}: {0[1]}".format(logvars))
+        self.last_src_mtime = new_mtime
+        return True
+
+    def run(self):
+        self.log("using source: {0}".format(self.src, self.LOG_NORMAL))
+        self.running = True
+        waiting = False
+        while self.running:
+            # check for messages to display
+            try:
+                msg = msg_queue.get_nowait()
+                self.display_message(msg[0], msg[1], None if len(msg) < 3 else msg[2])
+            except Empty:
+                pass
+            # check user events
+            try:
+                evt = evt_queue.get_nowait()
+                if evt == "reload":
+                    self.reload()
+                elif evt[0] == "display":
+                    self.display_image(evt[1], evt[2])
+            except Empty:
+                pass
+            # check if source file exists
+            if not os.path.exists(self.src):
+                # show error and prevent multiple display of the same error
+                if not waiting:
+                    self.display_message("source not found:",
+                        "Please create the following file:", "\t{0}".format(self.src))
+                    self.log("Waiting for source file to be created: {0}".format(self.src),
+                        self.LOG_ERROR)
+                waiting = True
+                continue
+            waiting = False
+            try:
+                # check modification
+                if not self.source_modified():
+                    time.sleep(self.delay)
+                    continue
+                # reload source module
+                self.reload()
+            except Exception:
+                # show error message and prevent multiple display of the same error
+                if not waiting:
+                    excinfo = sys.exc_info()
+                    et, ev, tb = excinfo
+                    self.display_error(et, ev, tb)
+                    traceback.print_exception(et, ev, tb, file=sys.stdout)
+                    print("---")
+                    time.sleep(self.delay)
+                    waiting = True
+                    continue
+                continue
+
+
+#
+# Public interface
+#
+
+def create_script(path, image_file):
+    """Creates a template script at the given path.
+    """
+    try:
+        open(path, "w+").write(SCRIPT_TEMPLATE.format(image_file))
+        print("".join((Observer.LOG_NORMAL, "created module: ", path)))
+    except IOError:
+        print("*** Error creating file: {0}. Exiting.".format(path))
+        raise SystemExit()
+
+
+def show_message(header, lines, wtitle=None):
+    """Puts a new message in the message queue.
+    """
+    msg_queue.put_nowait((header, lines, wtitle))
+
+
+def display(image, wtitle=None):
+    """Displays the specified Image instance.
+    """
+    evt_queue.put_nowait(("display", image, wtitle))
+
+
+def get_key_listing():
+    lines = []
+    for key, fun in KEY_MAPPINGS:
+        lines.append("  {0}    {1}".format(key.ljust(5), fun.__doc__.strip()))
+    return lines
+
+
+#
+# Keyboard event handlers
+#
+
+def _refresh(event):
+    """Updates the display window.
+    """
+    evt_queue.put_nowait("reload")
+
+
+def _screenshot(event):
+    """Saves current output as a unique image.
+    """
+    if not observer.reload():
+        return False
+    img_file = observer.output_file
+    ext = os.path.splitext(img_file)[1]
+    s = img_file.replace(ext, "")
+    n = 0
+    output = None
+    found = False
+    while not found:
+        output = SCREENSHOT_FILE.format(s, n, ext)
+        if not os.path.isfile(output):
+            found = True
+        n = n + 1
+    if output is None:
+        return False
+    shutil.copy(img_file, output)
+    show_message("screenshot", ["Output saved as:", "\t{0}".format(output),
+        NL, "Press F5 to refresh the display."])
+    return True
+
+
+def _imginfo(event):
+    """Shows information about the current image.
+    """
+    img = Image.open(observer.output_file)
+    lines = []
+    lines.append("path:")
+    lines.append("\t{0}".format(os.path.realpath(observer.output_file)))
+    lines.append("source:")
+    lines.append("\t{0}".format(os.path.realpath(observer.src)))
+    lines.append("size:\t{0}x{1}".format(img.size[0], img.size[1]))
+    lines.append("mode:\t{0}".format(img.mode))
+    lines.append(NL)
+    lines.append("Press F5 to refresh the display.")
+    show_message(observer.output_file, lines)
+
+
+def _kbhelp(event):
+    """Displays keyboard help.
+    """
+    lines = get_key_listing()
+    lines.append(NL)
+    lines.append("Press F5 to refresh the display.")
+    show_message("keyboard shortcuts", lines, DEFAULT_TITLE)
+
+
+def _exit(event):
+    """Closes the display window and the running script.
+    """
+    observer.running = False
+    observer.join()
+    root.destroy()
+    sys.exit()
+
+
+#
+# Keyboard mapping
+#
+
+KEY_MAPPINGS = [
+    ("<F5>", _refresh),
+    ("<F3>", _screenshot),
+    ("<F2>", _imginfo),
+    ("<F1>", _kbhelp),
+    ("<F10>", _exit),
+]
+
+
+#
+# Startup function
+#
+
+def initialize(input_file, image_file=None, silent=False):
+    """Creates necessary objects, sets up pilpal.
+    """
+    global observer, root, msg_queue, evt_queue
+    msg_queue = Queue(9)
+    evt_queue = Queue(3)
+    root = Tkinter.Tk()
+    root.title(DEFAULT_TITLE)
+    observer = Observer(root, input_file, image_file, silent)
+    for kbcfg in KEY_MAPPINGS:
+        root.bind_all(kbcfg[0], kbcfg[1])
+    observer.daemon = True
+#!/usr/bin/python
+# encoding: utf-8
+#
+# This file is part of pilpal.
+#
+# pilpal - Simple and quick graphics programming using Python Imaging Library
+# Copyright (C) 2013  Károly Kiripolszky
+#
+# pilpal 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 3 of the License, or
+# (at your option) any later version.
+#
+# pilpal 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 pilpal.  If not, see <http://www.gnu.org/licenses/>.
+#
+
+from distutils.core import setup
+from pilpal import __version__, Theme
+
+setup(
+    name="pilpal",
+    version=__version__,
+    author="Károly Kiripolszky",
+    author_email="karcsi@ekezet.com",
+    description="Simple graphics programming for Python",
+    license="GPLv3",
+    keywords="graphics creative-coding imaging",
+    long_description=open("README").read(),
+    url="http://ekezet.com/code#pilpal",
+    download_url="https://bitbucket.org/3k/pilpal/",
+    scripts=["bin/pilpal"],
+    packages=["pilpal"],
+    data_files=[
+        ("", ["README", "CHANGES", "COPYING"]),
+        ("fonts", [Theme.FONT_BOOK, Theme.FONT_BOLD, "fonts/NOTICE"])],
+    requires=["PIL"],
+    classifiers=[
+        "Topic :: Multimedia :: Graphics"
+    ]
+)