tegaki-pygtk-0.3.1/0000755000175000017500000000000011352066723013772 5ustar mathieumathieutegaki-pygtk-0.3.1/AUTHORS0000644000175000017500000000005711342122346015035 0ustar mathieumathieuMathieu Blondel tegaki-pygtk-0.3.1/COPYING0000644000175000017500000004326211342122346015025 0ustar mathieumathieu GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 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 Library 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. Copyright (C) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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. , 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 Library General Public License instead of this License. tegaki-pygtk-0.3.1/PKG-INFO0000644000175000017500000000035711352066723015074 0ustar mathieumathieuMetadata-Version: 1.0 Name: tegaki-pygtk Version: 0.3.1 Summary: Tegaki pygtk library Home-page: http://www.tegaki.org Author: Mathieu Blondel Author-email: mathieu ÂT mblondel DÔT org License: GPL Description: UNKNOWN Platform: UNKNOWN tegaki-pygtk-0.3.1/tegakigtk/0000755000175000017500000000000011352066723015744 5ustar mathieumathieutegaki-pygtk-0.3.1/tegakigtk/fakekey.py0000644000175000017500000001147211342122346017733 0ustar mathieumathieu# -*- coding: utf-8 -*- # Copyright (C) 2009 The Tegaki project contributors # # 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. # Contributors to this file: # - Mathieu Blondel """ Send fake key events in order to display text where the cursor is currently located. """ import time import os import platform if os.name == 'nt': from ctypes import * PUL = POINTER(c_ulong) class KeyBdInput(Structure): _fields_ = [("wVk", c_ushort), ("wScan", c_ushort), ("dwFlags", c_ulong), ("time", c_ulong), ("dwExtraInfo", PUL)] class HardwareInput(Structure): _fields_ = [("uMsg", c_ulong), ("wParamL", c_short), ("wParamH", c_ushort)] class MouseInput(Structure): _fields_ = [("dx", c_long), ("dy", c_long), ("mouseData", c_ulong), ("dwFlags", c_ulong), ("time",c_ulong), ("dwExtraInfo", PUL)] class Input_I(Union): _fields_ = [("ki", KeyBdInput), ("mi", MouseInput), ("hi", HardwareInput)] class Input(Structure): _fields_ = [("type", c_ulong), ("ii", Input_I)] INPUT_KEYBOARD = 1 KEYEVENTF_KEYUP = 0x2 KEYEVENTF_UNICODE = 0x4 def _send_unicode_win(unistr): for ch in unistr: inp = Input() inp.type = INPUT_KEYBOARD inp.ii.ki.wVk = 0 inp.ii.ki.wScan = ord(ch) inp.ii.ki.dwFlags = KEYEVENTF_UNICODE windll.user32.SendInput(1, byref(inp), sizeof(inp)) inp.ii.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP windll.user32.SendInput(1, byref(inp), sizeof(inp)) _send_unicode = _send_unicode_win elif platform.system() == "Darwin": def _send_unicode_osx(unistr): # TODO: use CGPostKeyboardEvent? raise NotImplementedError _send_unicode = _send_unicode_osx else: try: import pyatspi from gtk import gdk def _send_unicode_atspi(unistr): for ch in unistr: keyval = gdk.unicode_to_keyval(ord(ch)) pyatspi.Registry.generateKeyboardEvent(keyval, None, pyatspi.KEY_SYM) _send_unicode = _send_unicode_atspi except ImportError: from ctypes import * try: Xlib = CDLL("libX11.so.6") Xtst = CDLL("libXtst.so.6") KeySym = c_uint Xlib.XGetKeyboardMapping.restype = POINTER(KeySym) except OSError: Xlib = None def _send_unicode_x11(unistr): if Xlib is None: raise NameError dpy = Xlib.XOpenDisplay(None) if not dpy: raise OSError # no display min_, max_, numcodes = c_int(0), c_int(0), c_int(0) Xlib.XDisplayKeycodes(dpy, byref(min_), byref(max_)) for ch in unistr: sym = Xlib.XStringToKeysym("U" + hex(ord(ch)).replace("0x", "")) keysym = Xlib.XGetKeyboardMapping(dpy, min_, max_.value-min_.value+1, byref(numcodes)) keysym[(max_.value-min_.value-1)*numcodes.value] = sym Xlib.XChangeKeyboardMapping(dpy,min_,numcodes,keysym, (max_.value-min_.value)) Xlib.XFree(keysym) Xlib.XFlush(dpy) code = Xlib.XKeysymToKeycode(dpy, sym) Xtst.XTestFakeKeyEvent(dpy, code, True, 1) Xtst.XTestFakeKeyEvent(dpy, code, False, 1) Xlib.XFlush(dpy) Xlib.XCloseDisplay(dpy) _send_unicode = _send_unicode_x11 def send_unicode(unistr): assert(isinstance(unistr, unicode)) try: _send_unicode(unistr) return True except (OSError, NotImplementedError, NameError), e: return False except e, msg: print "send_unicode", e, msg return False if __name__ == "__main__": send_unicode(u"漢字")tegaki-pygtk-0.3.1/tegakigtk/chartable.py0000644000175000017500000004010711342122346020236 0ustar mathieumathieu# -*- coding: utf-8 -*- # Copyright (C) 2009 The Tegaki project contributors # # 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. # Contributors to this file: # - Mathieu Blondel import gtk from gtk import gdk import gobject import pango import math import time from tegaki.character import * class CharTable(gtk.Widget): """ A nifty character table. A port of Takuro Ashie's TomoeCharTable to pygtk. """ LAYOUT_SINGLE_HORIZONTAL = 0 LAYOUT_SINGLE_VERTICAL = 1 LAYOUT_HORIZONTAL = 2 LAYOUT_VERTICAL = 3 DEFAULT_FONT_SCALE = 2.0 #pango.SCALE_XX_LARGE __gsignals__ = { "character_selected" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]) } def __init__(self): gtk.Widget.__init__(self) self._pixmap = None self._padding = 2 self._selected = None self._prelighted = None self._layout = self.LAYOUT_SINGLE_HORIZONTAL self._h_adj = None self._v_adj = None self.clear() self.connect("motion_notify_event", self.motion_notify_event) # Events... def do_realize(self): """ Called when the widget should create all of its windowing resources. We will create our gtk.gdk.Window. """ # Set an internal flag telling that we're realized self.set_flags(self.flags() | gtk.REALIZED) # Create a new gdk.Window which we can draw on. # Also say that we want to receive exposure events # and button click and button press events self.window = gdk.Window(self.get_parent_window(), x=self.allocation.x, y=self.allocation.y, width=self.allocation.width, height=self.allocation.height, window_type=gdk.WINDOW_CHILD, wclass=gdk.INPUT_OUTPUT, visual=self.get_visual(), colormap=self.get_colormap(), event_mask=gdk.EXPOSURE_MASK | gdk.BUTTON_PRESS_MASK | gdk.BUTTON_RELEASE_MASK | gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK | gdk.ENTER_NOTIFY_MASK | gdk.LEAVE_NOTIFY_MASK) # Associate the gdk.Window with ourselves, Gtk+ needs a reference # between the widget and the gdk window self.window.set_user_data(self) # Attach the style to the gdk.Window, a style contains colors and # GC contextes used for drawing self.style.attach(self.window) # The default color of the background should be what # the style (theme engine) tells us. self.style.set_background(self.window, gtk.STATE_NORMAL) self.window.move_resize(*self.allocation) # Font font_desc = self.style.font_desc.copy() size = font_desc.get_size() font_desc.set_size(int(size * self.DEFAULT_FONT_SCALE)) self.modify_font(font_desc) def do_unrealize(self): """ The do_unrealized method is responsible for freeing the GDK resources De-associate the window we created in do_realize with ourselves """ self.window.destroy() def do_size_request(self, requisition): """ The do_size_request method Gtk+ is called on a widget to ask it the widget how large it wishes to be. It's not guaranteed that gtk+ will actually give this size to the widget. """ self.ensure_style() context = self.get_pango_context() metrics = context.get_metrics(self.style.font_desc, context.get_language()) # width char_width = metrics.get_approximate_char_width() digit_width = metrics.get_approximate_digit_width() char_pixels = pango.PIXELS(int(max(char_width, digit_width) * self.DEFAULT_FONT_SCALE)) requisition.width = char_pixels + self._padding * 2 # height ascent = metrics.get_ascent() descent = metrics.get_descent() requisition.height = pango.PIXELS(ascent + descent) + self._padding * 2 def do_size_allocate(self, allocation): """ The do_size_allocate is called when the actual size is known and the widget is told how much space could actually be allocated.""" self.allocation = allocation self.width = self.allocation.width self.height = self.allocation.height if self.flags() & gtk.REALIZED: self.window.move_resize(*allocation) self._pixmap = gdk.Pixmap(self.window, self.width, self.height) self.draw() def do_expose_event(self, event): """ This is where the widget must draw itself. """ retval = False if self.flags() & gtk.REALIZED and not self._pixmap: self._pixmap = gdk.Pixmap(self.window, self.allocation.width, self.allocation.height) self._adjust_adjustments() self.draw() if self._pixmap: self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, event.area.x, event.area.y, event.area.x, event.area.y, event.area.width, event.area.height) return retval def motion_notify_event(self, widget, event): retval = False if event.is_hint: x, y, state = event.window.get_pointer() else: x = event.x y = event.y state = event.state prev_prelighted = self._prelighted self._prelighted = self._get_char_id_from_coordinates(x, y) if prev_prelighted != self._prelighted: self.draw() return retval def do_button_press_event(self, event): retval = False prev_selected = self._selected self._selected = self._get_char_id_from_coordinates(event.x, event.y) if prev_selected != self._selected: self.draw() if self._selected >= 0: self.emit("character_selected", event) return retval def do_button_release_event(self, event): return False def get_max_char_size(self): context = self.get_pango_context() metrics = context.get_metrics(self.style.font_desc, context.get_language()) # width char_width = metrics.get_approximate_char_width() digit_width = metrics.get_approximate_digit_width() max_char_width = pango.PIXELS(int(max(char_width, digit_width) * self.DEFAULT_FONT_SCALE)) # height ascent = metrics.get_ascent() descent = metrics.get_descent() max_char_height = pango.PIXELS(int((ascent + descent) * self.DEFAULT_FONT_SCALE)) return (max_char_width, max_char_height) def _get_char_frame_size(self): sizes = [layout.get_pixel_size() for layout in self._layouts] if len(sizes) > 0: inner_width = max([size[0] for size in sizes]) inner_height = max([size[1] for size in sizes]) else: inner_width, inner_height = self.get_max_char_size() outer_width = inner_width + 2 * self._padding outer_height = inner_height + 2 * self._padding return [inner_width, inner_height, outer_width, outer_height] def _get_char_id_from_coordinates(self, x, y): inner_width, inner_height, outer_width, outer_height = \ self._get_char_frame_size() h_offset = 0; v_offset = 0 if self._h_adj: h_offset = h_adj.get_value() if self._v_adj: v_offset = v_adj.get_value() # Calculate columns for horizontal layout cols = self.allocation.width / outer_width if cols <= 0: cols = 1 # Calculate rows for vertical layout rows = self.allocation.height / outer_height if rows <= 0: rows = 1 for i in range(len(self._layouts)): if self._layout == self.LAYOUT_SINGLE_HORIZONTAL: area_x = outer_width * i - h_offset if x >= area_x and x < area_x + outer_width: return i elif self._layout == self.LAYOUT_SINGLE_VERTICAL: area_y = outer_height * i - v_offset if y >= area_y and y < area_y + outer_height: return i elif self._layout == self.LAYOUT_HORIZONTAL: area_x = outer_width * (i % cols) - h_offset area_y = outer_height * (i / cols) - v_offset if x >= area_x and x < area_x + outer_width and \ y >= area_y and y < area_y + outer_height: return i elif self._layout == self.LAYOUT_VERTICAL: area_x = outer_width * (i / rows) - h_offset area_y = outer_height * (i % rows) - v_offset if x >= area_x and x < area_x + outer_width and \ y >= area_y and y < area_y + outer_height: return i return None def _adjust_adjustments(self): pass def draw(self): if not self._pixmap: return inner_width, inner_height, outer_width, outer_height = \ self._get_char_frame_size() y_pos = (self.allocation.height - inner_height) / 2 x_pos = (self.allocation.width - inner_width) / 2 cols = self.allocation.width / outer_width if cols <= 0: cols = 1 rows = self.allocation.height / outer_height if rows <= 0: rows = 1 h_offset = 0; v_offset = 0 if self._h_adj: h_offset = h_adj.get_value() if self._v_adj: v_offset = v_adj.get_value() # Fill background self._pixmap.draw_rectangle(self.style.white_gc, True, 0, 0, self.allocation.width, self.allocation.height) # Draw characters for i in range(len(self._layouts)): layout = self._layouts[i] selected = i == self._selected char_width, char_height = layout.get_pixel_size() if self._layout == self.LAYOUT_SINGLE_HORIZONTAL: outer_x = outer_width * i - h_offset outer_y = 0 outer_height = self.allocation.height inner_x = outer_x + (outer_width - char_width) / 2 inner_y = y_pos if outer_x + outer_width < 0: continue if outer_x + outer_width > self.allocation.width: break elif self._layout == self.LAYOUT_SINGLE_VERTICAL: outer_x = 0 outer_y = outer_height * i - v_offset outer_width = self.allocation.width inner_x = x_pos inner_y = outer_y + (outer_height - char_height) / 2 if outer_y + outer_height < 0: continue if outer_y + outer_height > self.allocation.height: break elif self._layout == self.LAYOUT_HORIZONTAL: outer_x = outer_width * (i % cols) - h_offset outer_y = outer_height * (i / cols) - v_offset inner_x = outer_x + (outer_width - char_width) / 2 inner_y = outer_y + (outer_height - char_height) / 2 if outer_y + outer_height < 0: continue if outer_y + outer_height > self.allocation.height: break elif self._layout == self.LAYOUT_VERTICAL: outer_x = outer_width * (i / rows) - h_offset outer_y = outer_height * (i % rows) - v_offset inner_x = outer_x + (outer_width - char_width) / 2 inner_y = outer_y + (outer_height - char_height) / 2 if outer_x + outer_width < 0: continue if outer_x + outer_width > self.allocation.width: break if selected: outer_gc = self.style.bg_gc[gtk.STATE_SELECTED] inner_gc = self.style.white_gc else: outer_gc = self.style.white_gc inner_gc = self.style.black_gc self._pixmap.draw_rectangle(outer_gc, True, outer_x, outer_y, outer_width, outer_height) self._pixmap.draw_layout(inner_gc, inner_x, inner_y, layout) if i == self._prelighted: # FIXME: doesn't seem to work self.style.paint_shadow(self.window, gtk.STATE_PRELIGHT, gtk.SHADOW_OUT, None, None, None, outer_x, outer_y, outer_width, outer_height) self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, 0, 0, 0, 0, self.allocation.width, self.allocation.height) def set_characters(self, characters): self._layouts = [] for character in characters: self._layouts.append(self.create_pango_layout(character)) self.draw() self._characters = characters def get_characters(self): return self._characters def get_selected(self): return self._selected def unselect(self): self._selected = None self.draw() def clear(self): self._selected = None self._prelighted = None self.set_characters([]) def set_layout(self, layout): self._layout = layout gobject.type_register(CharTable) if __name__ == "__main__": import sys window = gtk.Window() chartable = CharTable() chartable.set_characters(["あ", "い","う", "え", "お", "か", "き", "く", "け", "こ", "さ", "し", "す", "せ", "そ"]) try: layout = int(sys.argv[1]) if layout > 3: layout = 0 except IndexError: layout = 0 chartable.set_layout(layout) def on_selected(widget, event): print "char_selected", chartable.get_selected() print "ev button", event.button print "ev time", event.time chartable.connect("character-selected", on_selected) window.add(chartable) window.show_all() gtk.main() tegaki-pygtk-0.3.1/tegakigtk/iconview.py0000644000175000017500000000736011342122346020140 0ustar mathieumathieu# -*- coding: utf-8 -*- # Copyright (C) 2009 The Tegaki project contributors # # 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. # Contributors to this file: # - Mathieu Blondel import gtk from gtk import gdk from tegakigtk.renderers import WritingImageRenderer class _WritingPixbufRenderer(WritingImageRenderer): def get_pixbuf(self): w, h = self.surface.get_width(), self.surface.get_height() pixmap = gdk.Pixmap(None, w, h, 24) cr = pixmap.cairo_create() cr.set_source_surface(self.surface, 0, 0) cr.paint () pixbuf = gtk.gdk.Pixbuf (gdk.COLORSPACE_RGB, True, 8, w, h) pixbuf = pixbuf.get_from_drawable(pixmap, gdk.colormap_get_system(), 0, 0, 0, 0, w, h) return pixbuf class WritingIconView(gtk.IconView): def __init__(self): self._model = gtk.ListStore(gdk.Pixbuf, str) gtk.IconView.__init__(self, self._model) self.set_selection_mode(gtk.SELECTION_SINGLE) self.set_reorderable(False) self.set_pixbuf_column(0) self.set_text_column(1) self.set_item_width(100) def set_writings(self, writings): """ writings: a list of tegaki.Writing objects. """ self._model.clear() characters = [] for writing in writings: char = Character() char.set_writing(writing) char.set_utf8("?") characters.append(char) self.set_characters(characters) def set_characters(self, characters): """ characters: a list of tegaki.Character objects. """ self._model.clear() for char in characters: writing = char.get_writing() renderer = _WritingPixbufRenderer(writing, self.get_item_width(), self.get_item_width()) renderer.set_draw_annotations(False) renderer.draw_background() renderer.draw_border() #renderer.draw_axis() renderer.draw_writing() self._model.append((renderer.get_pixbuf(), char.get_utf8())) def show_icon_text(self): self.set_text_column(1) def hide_icon_text(self): self.set_text_column(-1) if __name__ == "__main__": import sys from glob import glob import os.path from tegaki.character import Character folder = sys.argv[1] # a folder contains XML character files window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_default_size(500, 500) iconview = WritingIconView() scrolledwindow = gtk.ScrolledWindow() scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) characters = [] for path in glob(os.path.join(folder, "*.xml")): char = Character() char.read(path) characters.append(char) iconview.set_item_width(80) iconview.set_characters(characters) iconview.hide_icon_text() scrolledwindow.add(iconview) window.add(scrolledwindow) window.show_all() gtk.main()tegaki-pygtk-0.3.1/tegakigtk/__init__.py0000644000175000017500000000005111352064314020043 0ustar mathieumathieu# -*- coding: utf-8 -*- VERSION = '0.3.1'tegaki-pygtk-0.3.1/tegakigtk/canvas.py0000644000175000017500000007122211342122346017566 0ustar mathieumathieu# -*- coding: utf-8 -*- # Copyright (C) 2008 The Tegaki project contributors # # 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. # Contributors to this file: # - Mathieu Blondel import gtk from gtk import gdk import gobject import pango import math import time from tegaki.character import * class Canvas(gtk.Widget): """ A character drawing canvas. This widget receives the input from the user and can return the corresponding L{tegaki.Writing} objects. It also has a "replay" method which can display a stroke-by-stroke animation of the current writing. The code was originally ported from Tomoe (C language). Since then many additional features were added. """ #: Default canvas size DEFAULT_WIDTH = 400 DEFAULT_HEIGHT = 400 #: Default canvas size DEFAULT_REPLAY_SPEED = 50 # msec #: - the stroke-added signal is emitted when the user has added a stroke #: - the drawing-stopped signal is emitted when the user has stopped drawing __gsignals__ = { "stroke_added" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, []), "drawing_stopped" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, []) } def __init__(self): gtk.Widget.__init__(self) self._width = self.DEFAULT_WIDTH self._height = self.DEFAULT_HEIGHT self._drawing = False self._pixmap = None self._writing = Writing() self._locked = False self._drawing_stopped_time = 0 self._drawing_stopped_id = 0 self._draw_annotations = True self._need_draw_axis = True self._handwriting_line_gc = None self._annotation_gc = None self._axis_gc = None self._stroke_gc = None self._background_writing_gc = None self._background_gc = None self._background_color = (0xFFFF, 0xFFFF, 0xFFFF) self._background_character = None self._background_writing = None self._first_point_time = None self.connect("motion_notify_event", self.motion_notify_event) # Events... def do_realize(self): """ Called when the widget should create all of its windowing resources. We will create our gtk.gdk.Window. """ # Set an internal flag telling that we're realized self.set_flags(self.flags() | gtk.REALIZED) # Create a new gdk.Window which we can draw on. # Also say that we want to receive exposure events # and button click and button press events self.window = gdk.Window(self.get_parent_window(), x=self.allocation.x, y=self.allocation.y, width=self.allocation.width, height=self.allocation.height, window_type=gdk.WINDOW_CHILD, wclass=gdk.INPUT_OUTPUT, visual=self.get_visual(), colormap=self.get_colormap(), event_mask=gdk.EXPOSURE_MASK | gdk.BUTTON_PRESS_MASK | gdk.BUTTON_RELEASE_MASK | gdk.POINTER_MOTION_MASK | gdk.POINTER_MOTION_HINT_MASK | gdk.ENTER_NOTIFY_MASK | gdk.LEAVE_NOTIFY_MASK) # Associate the gdk.Window with ourselves, Gtk+ needs a reference # between the widget and the gdk window self.window.set_user_data(self) # Attach the style to the gdk.Window, a style contains colors and # GC contextes used for drawing self.style.attach(self.window) # The default color of the background should be what # the style (theme engine) tells us. self.style.set_background(self.window, gtk.STATE_NORMAL) self.window.move_resize(*self.allocation) # Font font_desc = pango.FontDescription("Sans 12") self.modify_font(font_desc) self._init_gc() def do_unrealize(self): """ The do_unrealized method is responsible for freeing the GDK resources De-associate the window we created in do_realize with ourselves """ self.window.destroy() def do_size_request(self, requisition): """ The do_size_request method Gtk+ is called on a widget to ask it the widget how large it wishes to be. It's not guaranteed that gtk+ will actually give this size to the widget. """ requisition.height = self.DEFAULT_HEIGHT requisition.width = self.DEFAULT_WIDTH def do_size_allocate(self, allocation): """ The do_size_allocate is called when the actual size is known and the widget is told how much space could actually be allocated.""" self.allocation = allocation self._width = self.allocation.width self._height = self.allocation.height if self.flags() & gtk.REALIZED: self.window.move_resize(*allocation) self._pixmap = gdk.Pixmap(self.window, self._width, self._height) self.refresh() def do_expose_event(self, event): """ This is where the widget must draw itself. """ retval = False self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, event.area.x, event.area.y, event.area.x, event.area.y, event.area.width, event.area.height) return retval def motion_notify_event(self, widget, event): retval = False if self._locked or not self._drawing: return retval if event.is_hint: x, y, state = event.window.get_pointer() else: x = event.x y = event.y state = event.state x, y = self._internal_coordinates(x, y) point = Point() point.x = x point.y = y point.timestamp = event.time - self._first_point_time #point.pressure = pressure #point.xtilt = xtilt #point.ytilt = ytilt self._append_point(point) return retval def do_button_press_event(self, event): retval = False if self._locked: return retval if self._drawing_stopped_id > 0: gobject.source_remove(self._drawing_stopped_id) self._drawing_stopped_id = 0 if event.button == 1: self._drawing = True x, y = self._internal_coordinates(event.x, event.y) point = Point() point.x = x point.y = y if self._writing.get_n_strokes() == 0: self._first_point_time = event.time point.timestamp = 0 else: if self._first_point_time is None: # in the case we add strokes to an imported character self._first_point_time = event.time - \ self._writing.get_duration() - 50 point.timestamp = event.time - self._first_point_time #point.pressure = pressure #point.xtilt = xtilt #point.ytilt = ytilt self._writing.move_to_point(point) return retval def do_button_release_event(self, event): retval = False if self._locked or not self._drawing: return retval self._drawing = False self.refresh(force_draw=True) self.emit("stroke_added") if self._drawing_stopped_time > 0: def _on_drawing_stopped(): self.emit("drawing_stopped") return False self._drawing_stopped_id = \ gobject.timeout_add(self._drawing_stopped_time, _on_drawing_stopped) self._draw_background_writing_stroke() return retval # Private... def _gc_set_foreground (self, gc, color): colormap = gdk.colormap_get_system () if color: color = colormap.alloc_color(color, True, True) gc.set_foreground(color) else: default_color = gdk.Color(0x0000, 0x0000, 0x0000, 0) default_color = colormap.alloc_color(default_color, True, True) gc.set_foreground(default_color) def _init_gc(self): if not self._handwriting_line_gc: color = gdk.Color(red=0x0000, blue=0x0000, green=0x0000) self._handwriting_line_gc = gdk.GC(self.window) self._gc_set_foreground(self._handwriting_line_gc, color) self._handwriting_line_gc.set_line_attributes(4, gdk.LINE_SOLID, gdk.CAP_ROUND, gdk.JOIN_ROUND) if not self._stroke_gc: color = gdk.Color(red=0xff00, blue=0x0000, green=0x0000) self._stroke_gc = gdk.GC(self.window) self._gc_set_foreground(self._stroke_gc, color) self._stroke_gc.set_line_attributes(4, gdk.LINE_SOLID, gdk.CAP_ROUND, gdk.JOIN_ROUND) if not self._background_writing_gc: color = gdk.Color(red=0xcccc, blue=0xcccc, green=0xcccc) self._background_writing_gc = gdk.GC(self.window) self._gc_set_foreground(self._background_writing_gc, color) self._background_writing_gc.set_line_attributes(4, gdk.LINE_SOLID, gdk.CAP_ROUND, gdk.JOIN_ROUND) if not self._annotation_gc: color = gdk.Color(red=0x8000, blue=0x0000, green=0x0000) self._annotation_gc = gdk.GC(self.window) self._gc_set_foreground(self._annotation_gc, color) if not self._axis_gc: color = gdk.Color(red=0x8000, blue=0x8000, green=0x8000) self._axis_gc = gdk.GC(self.window) self._gc_set_foreground(self._axis_gc, color) self._axis_gc.set_line_attributes(1, gdk.LINE_ON_OFF_DASH, gdk.CAP_BUTT, gdk.JOIN_ROUND) if not self._background_gc: color = gdk.Color(*self._background_color) self._background_gc = gdk.GC(self.window) self._gc_set_foreground(self._background_gc, color) def _internal_coordinates(self, x, y): """ Converts window coordinates to internal coordinates. """ sx = float(self._writing.get_width()) / self._width sy = float(self._writing.get_height()) / self._height return (int(x * sx), int(y * sy)) def _window_coordinates(self, x, y): """ Converts internal coordinates to window coordinates. """ sx = float(self._width) / self._writing.get_width() sy = float(self._height) / self._writing.get_height() return (int(x * sx), int(y * sy)) def _append_point(self, point): # x and y are internal coordinates p2 = (point.x, point.y) strokes = self._writing.get_strokes(full=True) p1 = strokes[-1][-1].get_coordinates() self._draw_line(p1, p2, self._handwriting_line_gc, force_draw=True) self._writing.line_to_point(point) def _draw_stroke(self, stroke, index, gc, draw_annotation=True): l = len(stroke) for i in range(l): if i == l - 1: break p1 = stroke[i] p1 = (p1.x, p1.y) p2 = stroke[i+1] p2 = (p2.x, p2.y) self._draw_line(p1, p2, gc) if draw_annotation: self._draw_annotation(stroke, index) def _draw_line(self, p1, p2, line_gc, force_draw=False): # p1 and p2 are two points in internal coordinates p1 = self._window_coordinates(*p1) p2 = self._window_coordinates(*p2) self._pixmap.draw_line(line_gc, p1[0], p1[1], p2[0], p2[1]) if force_draw: x = min(p1[0], p2[0]) - 2 y = min(p1[1], p2[1]) - 2 width = abs(p1[0] - p2[0]) + 2 * 2 height = abs(p1[1] - p2[1]) + 2 * 2 self.queue_draw_area(x, y, width, height) def _draw_annotation(self, stroke, index, force_draw=False): x, y = self._window_coordinates(stroke[0].x, stroke[0].y) if len(stroke) == 1: dx, dy = x, y else: last_x, last_y = self._window_coordinates(stroke[-1].x, stroke[-1].y) dx, dy = last_x - x, last_y - y if dx == dy == 0: dx, dy = x, y dl = math.sqrt(dx*dx + dy*dy) if dy <= dx: sign = 1 else: sign = -1 num = str(index + 1) layout = self.create_pango_layout(num) width, height = layout.get_pixel_size() r = math.sqrt (width*width + height*height) x += (0.5 + (0.5 * r * dx / dl) + (sign * 0.5 * r * dy / dl) - \ (width / 2)) y += (0.5 + (0.5 * r * dy / dl) - (sign * 0.5 * r * dx / dl) - \ (height / 2)) x, y = int(x), int(y) self._pixmap.draw_layout(self._annotation_gc, x, y, layout) if force_draw: self.queue_draw_area(x-2, y-2, width+4, height+4) def _draw_axis(self): self._pixmap.draw_line(self._axis_gc, self._width / 2, 0, self._width / 2, self._height) self._pixmap.draw_line(self._axis_gc, 0, self._height / 2, self._width, self._height / 2) def _draw_background(self): self._pixmap.draw_rectangle(self._background_gc, True, 0, 0, self.allocation.width, self.allocation.height) if self._need_draw_axis: self._draw_axis() def _draw_background_character(self): if self._background_character: raise NotImplementedError def _draw_background_writing(self): if self._background_writing: strokes = self._background_writing.get_strokes(full=True) start = self._writing.get_n_strokes() + 1 for i in range(start, len(strokes)): self._draw_stroke(strokes[i], i, self._background_writing_gc, draw_annotation=False) def _draw_background_writing_stroke(self): if self._background_writing and self._writing.get_n_strokes() < \ self._background_writing.get_n_strokes(): time.sleep(0.5) l = self._writing.get_n_strokes() self._strokes = self._background_writing.get_strokes(full=True) self._strokes = self._strokes[l:l+1] self._curr_stroke = 0 self._curr_point = 1 self._refresh_writing = False speed = self._get_speed(self._curr_stroke) gobject.timeout_add(speed, self._on_animate) def _redraw(self): self.window.draw_drawable(self.style.fg_gc[self.state], self._pixmap, 0, 0, 0, 0, self.allocation.width, self.allocation.height) def _get_speed(self, index): if self._speed: speed = self._speed else: duration = self._strokes[index].get_duration() if duration: speed = duration / len(self._strokes[index]) else: speed = self.DEFAULT_REPLAY_SPEED return speed def _on_animate(self): self._locked = True if self._curr_stroke > 0 and self._curr_point == 1 and \ not self._speed: # inter stroke duration # t2 = self._strokes[self._curr_stroke][0].timestamp # t1 = self._strokes[self._curr_stroke - 1][-1].timestamp # time.sleep(float(t2 - t1) / 1000) time.sleep(float(self._get_speed(self._curr_stroke))/1000) p1 = self._strokes[self._curr_stroke][self._curr_point - 1] p1 = (p1.x, p1.y) p2 = self._strokes[self._curr_stroke][self._curr_point] p2 = (p2.x, p2.y) self._draw_line(p1, p2, self._stroke_gc, force_draw=True) if len(self._strokes[self._curr_stroke]) == self._curr_point + 1: # if we reach the stroke last point if self._draw_annotations: self._draw_annotation(self._strokes[self._curr_stroke], self._curr_stroke) self._curr_point = 1 self._curr_stroke += 1 if len(self._strokes) != self._curr_stroke: # if there are remaining strokes to process speed = self._get_speed(self._curr_stroke) gobject.timeout_add(speed, self._on_animate) else: # last stroke and last point was reached self._locked = False if self._refresh_writing: self.refresh(n_strokes=self._curr_stroke, force_draw=True) return False else: self._curr_point += 1 return True def _refresh(self, writing, n_strokes=None, force_draw=False): if self.flags() & gtk.REALIZED and self._pixmap: self._draw_background() self._draw_background_character() self._draw_background_writing() strokes = writing.get_strokes(full=True) if not n_strokes: n_strokes = len(strokes) for i in range(n_strokes): self._draw_stroke(strokes[i], i, self._handwriting_line_gc, draw_annotation=self._draw_annotations) if force_draw: self._redraw() # Public... def get_drawing_stopped_time(self): """ Get the inactivity time after which a character is considered drawn. @rtype: int @return: time in milliseconds """ return self._drawing_stopped_time def set_drawing_stopped_time(self, time_msec): """ Set the inactivity time after which a character is considered drawn. @type time_msec: int @param time_msec: time in milliseconds """ self._drawing_stopped_time = time_msec def set_draw_annotations(self, draw_annotations): """ Set whether to display stroke-number annotations or not. @type draw_annotations: boolean """ self._draw_annotations = draw_annotations def get_draw_annotations(self): """ Return whether stroke-number annotations are displayed or not. """ return self._draw_annotations def set_draw_axis(self, draw_axis): self._need_draw_axis = draw_axis def get_draw_axis(self): return self._need_draw_axis def refresh(self, n_strokes=None, force_draw=False): """ Update the screen. """ if self._writing: self._refresh(self._writing, n_strokes=n_strokes, force_draw=force_draw) def replay(self, speed=None): """ Display an animation of the current writing. One point is drawn every "speed" msec. If speed is None, uses the writing original speed when available or DEFAULT_REPLAY_SPEED when not available. @type speed: int @type speed: time between each point in milliseconds """ self._draw_background() self._redraw() self._strokes = self._writing.get_strokes(full=True) if len(self._strokes) == 0: return self._curr_stroke = 0 self._curr_point = 1 self._speed = speed self._refresh_writing = True speed = self._get_speed(self._curr_stroke) gobject.timeout_add(speed, self._on_animate) def get_writing(self, writing_width=None, writing_height=None): """ Return a L{tegaki.Writing} object for the current handwriting. @type writing_width: int @param writing_width: the width that the writing should have or \ None if default @type writing_height: int @param writing_height: the height that the writing should have or \ None if default @rtype: Writing """ if writing_width and writing_height: # Convert to requested size xratio = float(writing_width) / self._writing.get_width() yratio = float(writing_height) / self._writing.get_height() return self._writing.resize(xratio, yratio) else: return self._writing def set_writing(self, writing, writing_width=None, writing_height=None): if writing_width and writing_height: # Convert to internal size xratio = float(self._writing.get_width()) / writing_width yratio = float(self._writing.get_height()) / writing_height self._writing = self._writing.resize(xratio, yratio) else: self._writing = writing self.refresh(force_draw=True) def clear(self): """ Erase the current writing. """ self._writing.clear() self.refresh(force_draw=True) def revert_stroke(self): """ Undo the latest stroke """ n = self._writing.get_n_strokes() if n > 0: self._writing.remove_last_stroke() self.refresh(force_draw=True) def normalize(self): """ Normalize the current writing. (See L{tegaki.normalize}) """ self._writing.normalize() self.refresh(force_draw=True) def smooth(self): """ Smooth the current writing. (See L{tegaki.smooth}) """ self._writing.smooth() self.refresh(force_draw=True) def set_background_character(self, character): """ Set a character as background. @type character: str """ self._background_character = character def get_background_writing(self): return self._background_writing def set_background_writing(self, writing, speed=25): """ Set a writing as background. Strokes of the background writing are displayed one at a time. This is intended to let users "follow" the background writing like a template. @type writing: L{tegaki.Writing} """ self.clear() self._background_writing = writing self._speed = speed time.sleep(0.5) self._draw_background_writing_stroke() self.refresh(force_draw=True) def set_background_color(self, r, g, b): """ Set background color. @type r: int @param r: red @type g: int @param g: green @type b: int @param b: blue """ self._background_color = (r, g, b) if self._background_gc: # This part can only be called after the widget is visible color = gdk.Color(red=r, green=g, blue=b) self._background_gc = gdk.GC(self.window) self._gc_set_foreground(self._background_gc, color) self.refresh(force_draw=True) gobject.type_register(Canvas) if __name__ == "__main__": import sys import copy def on_stroke_added(widget): print "stroke added!" window = gtk.Window(gtk.WINDOW_TOPLEVEL) canvas = Canvas() canvas.connect("stroke_added", on_stroke_added) if len(sys.argv) >= 2: if sys.argv[1] == "upsample": try: n = int(sys.argv[2]) except IndexError: n = 5 def on_drawing_stopped(widget): print "before: %d pts" % widget.get_writing().get_n_points() widget.get_writing().upsample(n) widget.refresh(force_draw=True) print "after: %d pts" % widget.get_writing().get_n_points() elif sys.argv[1] == "upsamplet": try: n = int(sys.argv[2]) except IndexError: n = 10 def on_drawing_stopped(widget): print "before: %d pts" % widget.get_writing().get_n_points() widget.get_writing().upsample_threshold(n) widget.refresh(force_draw=True) print "after: %d pts" % widget.get_writing().get_n_points() elif sys.argv[1] == "downsample": try: n = int(sys.argv[2]) except IndexError: n = 5 def on_drawing_stopped(widget): print "before: %d pts" % widget.get_writing().get_n_points() widget.get_writing().downsample(n) widget.refresh(force_draw=True) print "after: %d pts" % widget.get_writing().get_n_points() elif sys.argv[1] == "downsamplet": try: n = int(sys.argv[2]) except IndexError: n = 10 def on_drawing_stopped(widget): print "before: %d pts" % widget.get_writing().get_n_points() widget.get_writing().downsample_threshold(n) widget.refresh(force_draw=True) print "after: %d pts" % widget.get_writing().get_n_points() elif sys.argv[1] == "smooth": def on_drawing_stopped(widget): widget.smooth() elif sys.argv[1] == "normalize": def on_drawing_stopped(widget): widget.normalize() elif sys.argv[1] == "replay": def on_drawing_stopped(widget): widget.replay() elif sys.argv[1] == "replay-speed": def on_drawing_stopped(widget): widget.replay(speed=25) elif sys.argv[1] == "background-writing": def on_drawing_stopped(widget): background_writing = widget.get_background_writing() if not background_writing: writing = copy.copy(widget.get_writing()) widget.set_background_writing(writing) else: def on_drawing_stopped(widget): print "drawing stopped!" if sys.argv[1] == "background-char": canvas.set_background_character("愛") else: def on_drawing_stopped(widget): print "drawing stopped!" print widget.get_writing().to_xml() canvas.set_draw_annotations(False) canvas.set_drawing_stopped_time(1000) canvas.connect("drawing_stopped", on_drawing_stopped) window.add(canvas) window.show_all() window.connect('delete-event', gtk.main_quit) gtk.main()tegaki-pygtk-0.3.1/tegakigtk/renderers.py0000644000175000017500000004326311342122346020310 0ustar mathieumathieu# -*- coding: utf-8 -*- # Copyright (C) 2008 The Tegaki project contributors # # 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. # Contributors to this file: # - Mathieu Blondel import math import cairo from math import pi from tegaki.character import * from tegaki.mathutils import euclidean_distance class _CairoRendererBase(object): def __init__(self, cairo_context, writing): self.cr = cairo_context self._init_colors() self.writing = writing self.draw_annotations = False self.draw_circles = False self.stroke_width = 8 self.area_changed_cb = None self.stroke_added_cb = None def set_area_changed_callback(self, cb): self.area_changed_cb = cb def set_stroke_added_callback(self, cb): self.stroke_added_cb = cb def _area_changed(self, x, y, w, h, delay_ms): if self.area_changed_cb: sx = float(self.width) / self.writing.get_width() # scale x sy = float(self.height) / self.writing.get_height() # scale y self.area_changed_cb(int(sx*x), int(sy*y), int(sx*w), int(sy*h), delay_ms) def _init_colors(self): self.handwriting_line_color = (0x0000, 0x0000, 0x0000, 1.0) self.axis_line_color = (0, 0, 0, 0.2) self.annotations_color = (255, 0, 0, 0.8) self.stroke_line_color = (255, 0, 0, 0.5) self.border_line_color = (0, 0, 0, 1.0) self.circle_color = (0, 0, 255, 0.5) def _with_handwriting_line(self): self.cr.set_line_width(self.stroke_width) self.cr.set_line_cap(cairo.LINE_CAP_ROUND) self.cr.set_line_join(cairo.LINE_JOIN_ROUND) def _with_circle_line(self): self.cr.set_line_width(self.stroke_width) self.cr.set_line_cap(cairo.LINE_CAP_ROUND) self.cr.set_line_join(cairo.LINE_JOIN_ROUND) self.cr.set_source_rgba (*self.circle_color) def _with_axis_line(self): self.cr.set_source_rgba (*self.axis_line_color) self.cr.set_line_width (4) self.cr.set_dash ([8, 8], 2) self.cr.set_line_cap(cairo.LINE_CAP_BUTT) self.cr.set_line_join(cairo.LINE_JOIN_ROUND) def _with_border_line(self): self.cr.set_source_rgba (*self.border_line_color) self.cr.set_line_width (8) self.cr.set_line_cap(cairo.LINE_CAP_BUTT) self.cr.set_line_join(cairo.LINE_JOIN_ROUND) def _with_annotations(self): self.cr.set_source_rgba (*self.annotations_color) self.annotation_font_size = 30 # user space units self.cr.set_font_size(self.annotation_font_size) def _draw_small_circle(self, x, y): self.cr.save() self._with_circle_line() self.cr.arc(x, y, 10, 0, 2*pi) self.cr.fill_preserve() self.cr.stroke() self.cr.restore() def set_draw_circles(self, draw_circles): self.draw_circles = draw_circles def set_draw_annotations(self, draw_annotations): self.draw_annotations = draw_annotations def set_stroke_width(self, stroke_width): self.stroke_width = stroke_width def draw_stroke(self, stroke, index, color, draw_annotation=False, draw_circle=False): l = len(stroke) self.cr.save() self._with_handwriting_line() self.cr.set_source_rgba(*color) point0 = stroke[0] if draw_circle: self._draw_small_circle(point0.x, point0.y) self.cr.move_to(point0.x, point0.y) last_point = point0 n_points = len(stroke) i = 1 for point in stroke[1:]: self.cr.line_to(point.x, point.y) self.cr.stroke() self.cr.move_to(point.x, point.y) dist = euclidean_distance(point.get_coordinates(), last_point.get_coordinates()) if dist > 50 or i == n_points - 1: win = 100 # window size x1 = last_point.x - win; y1 = last_point.y - win x2 = point.x + win; y2 = point.y + win if x1 > x2: x1, x2 = x2, x1 if y1 > y2: y1, y2 = y2, y1 w = x2 - x1; h = y2 - y1 if point.timestamp and last_point.timestamp: delay = point.timestamp - last_point.timestamp else: delay = None if w > 0 and h > 0: self._area_changed(x1, y1, w, h, delay) last_point = point i += 1 self.cr.stroke() self.cr.restore() if self.stroke_added_cb: self.stroke_added_cb() if draw_annotation: self._draw_annotation(stroke, index) def _draw_annotation(self, stroke, index): self.cr.save() self._with_annotations() x, y = stroke[0].x, stroke[0].y if len(stroke) == 1: dx, dy = x, y else: last_x, last_y = stroke[-1].x, stroke[-1].y dx, dy = last_x - x, last_y - y dl = math.sqrt(dx*dx + dy*dy) if dy <= dx: sign = 1 else: sign = -1 num = str(index + 1) # FIXME: how to know the actual size of the text? width, height = [int(self.annotation_font_size * 11.0/10.0)] * 2 r = math.sqrt (width*width + height*height) x += (0.5 + (0.5 * r * dx / dl) + (sign * 0.5 * r * dy / dl) - \ (width / 2)) y += (0.5 + (0.5 * r * dy / dl) - (sign * 0.5 * r * dx / dl) - \ (height / 2)) x, y = int(x), int(y) self.cr.move_to(x, y) self.cr.show_text(num) self.cr.stroke() self._area_changed(x-50, y-50, 100, 100, 0) self.cr.restore() def draw_background(self, color=(1, 1, 1)): self.cr.save() self.cr.set_source_rgb(*color) self.cr.paint() self.cr.restore() def draw_border(self): self.cr.save() self._with_axis_line() self.cr.move_to(0, 0) self.cr.line_to(0, 1000) self.cr.line_to(1000, 1000) self.cr.line_to(1000, 0) self.cr.line_to(0, 0) self.cr.stroke() self.cr.restore() def draw_axis(self): self.cr.save() self._with_axis_line() self.cr.move_to(500, 0) self.cr.line_to(500, 1000) self.cr.move_to(0, 500) self.cr.line_to(1000, 500) self.cr.stroke() self.cr.restore() class _SurfaceRendererBase(object): def get_width(self): return self.width def get_height(self): return self.height def get_size(self): return (self.width, self.height) class _ImageRendererBase(_SurfaceRendererBase): def write_to_png(self, filename): self.surface.write_to_png(filename) def get_data(self): return self.surface.get_data() def get_area_data(self, x, y, width, height): data = self.get_data() stride = self.surface.get_stride() # number of bytes per line bpp = stride / self.surface.get_width() # bytes per pixel start = 0 if y > 0: start += y * stride if x > 0: start += x * bpp buf = "" for i in range(height): buf += data[start:start+width*bpp] start += stride return buf def get_stride(self): return self.surface.get_stride() class WritingCairoRenderer(_CairoRendererBase): def __init__(self, *a, **kw): _CairoRendererBase.__init__(self, *a, **kw) self.draw_annotations = True def draw_writing(self): strokes = self.writing.get_strokes(full=True) n_strokes = len(strokes) for i in range(n_strokes): self.draw_stroke(strokes[i], i, self.handwriting_line_color, draw_annotation=self.draw_annotations, draw_circle=self.draw_circles) class WritingStepsCairoRenderer(_CairoRendererBase): def __init__(self, cairo_context, writing, stroke_groups=None, start=0, length=None, n_chars_per_row=None): _CairoRendererBase.__init__(self, cairo_context, writing) def _init(self): n_strokes = self.writing.get_n_strokes() if not self.stroke_groups: self.stroke_groups = [1] * n_strokes else: n = sum(self.stroke_groups) diff = n_strokes - n if diff > 0: # fix the number of groups if not enough self.stroke_groups += [1] * diff elif diff < 0: # fix the number of groups if too big tmp = [] i = 0 while sum(tmp) <= n_strokes: tmp.append(self.stroke_groups[i]) i += 1 self.stroke_groups = tmp n_stroke_groups = len(self.stroke_groups) if not self.length or self.start + self.length > n_stroke_groups: self.length = n_stroke_groups - self.start # interval groups are used to know which strokes are grouped together interval_groups = [] interval_groups.append((0, self.stroke_groups[0] - 1)) for i in range(1, n_stroke_groups): prev = interval_groups[i-1][1] interval_groups.append((prev + 1, prev + self.stroke_groups[i])) self.interval_groups = interval_groups # rows and cols if not self.n_chars_per_row: self.n_rows = 1 self.n_cols = self.length else: self.n_cols = self.n_chars_per_row self.n_rows = int(math.ceil(float(self.length) / self.n_cols)) # this factor is a multiplication factor used to determine # the amount of space to leave between two character steps self.FACTOR = 1.05 # find proportional image size # we use width / n_cols == height / n_rows if self.width and not self.height: self.height = int(self.width / self.n_cols * self.n_rows) elif self.height and not self.width: self.width = int(self.n_cols * self.height / self.n_rows) elif not self.height and not self.width: raise ValueError, \ "At least one of height or width should be defined." def draw_writing_steps(self): strokes = self.writing.get_strokes(full=True) n_strokes = len(strokes) n_stroke_groups = len(self.interval_groups) self.cr.save() x_scale = 1.0 / (self.n_cols * self.FACTOR) if self.n_rows == 1: y_scale = 1.0 else: y_scale = 1.0 / (self.n_rows * self.FACTOR) self.cr.scale(x_scale, y_scale) for i in range(self.start, self.start + self.length): if i != self.start: if self.n_rows > 1 and i % self.n_cols == 0: self.cr.translate((-self.n_cols+1) * self.writing.get_width() * self.FACTOR, self.writing.get_height() * self.FACTOR) else: self.cr.translate(self.writing.get_width() * self.FACTOR,0) # draw the character step for j in range(n_strokes): interval_min, interval_max = self.interval_groups[i] if interval_min <= j and j <= interval_max: color = self.handwriting_line_color draw_annotation = self.draw_annotations draw_circle = self.draw_circles else: color = self.stroke_line_color draw_annotation = False draw_circle = False self.draw_stroke(strokes[j], j, color, draw_annotation=draw_annotation, draw_circle=draw_circle) self.cr.restore() class WritingImageRenderer(WritingCairoRenderer, _ImageRendererBase): def __init__(self, writing, width, height): """ width and height are in pixels. """ self.width = width self.height = height self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) cr = cairo.Context(self.surface) cr.scale(float(width) / writing.get_width(), float(height) / writing.get_height()) WritingCairoRenderer.__init__(self, cr, writing) class WritingSVGRenderer(WritingCairoRenderer, _SurfaceRendererBase): def __init__(self, writing, filename, width, height): """ width and height are in points (1 point == 1/72.0 inch). """ self.width = width self.height = height self.surface = cairo.SVGSurface(filename, width, height) cr = cairo.Context(self.surface) cr.scale(float(width) / writing.get_width(), float(height) / writing.get_height()) WritingCairoRenderer.__init__(self, cr, writing) class WritingPDFRenderer(WritingCairoRenderer, _SurfaceRendererBase): def __init__(self, writing, filename, width, height): """ width and height are in points (1 point == 1/72.0 inch). """ self.width = width self.height = height self.surface = cairo.PDFSurface(filename, width, height) cr = cairo.Context(self.surface) cr.scale(float(width) / writing.get_width(), float(height) / writing.get_height()) WritingCairoRenderer.__init__(self, cr, writing) class WritingStepsImageRenderer(WritingStepsCairoRenderer, _ImageRendererBase): def __init__(self, writing, width=None, height=None, stroke_groups=None, start=0, length=None, n_chars_per_row=None): """ width and height are in pixels. """ self.writing = writing self.width = width self.height = height self.stroke_groups = stroke_groups self.start = start self.length = length self.n_chars_per_row = n_chars_per_row self._init() self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height) cr = cairo.Context(self.surface) cr.scale(float(self.width) / writing.get_width(), float(self.height) / writing.get_height()) WritingStepsCairoRenderer.__init__(self, cr, writing) def write_to_png(self, filename): self.surface.write_to_png(filename) class WritingStepsSVGRenderer(WritingStepsCairoRenderer, _SurfaceRendererBase): def __init__(self, writing, filename, width=None, height=None, stroke_groups=None, start=0, length=None, n_chars_per_row=None): """ width and height are in points (1 point == 1/72.0 inch). """ self.writing = writing self.width = width self.height = height self.stroke_groups = stroke_groups self.start = start self.length = length self.n_chars_per_row = n_chars_per_row self._init() self.surface = cairo.SVGSurface(filename, self.width, self.height) cr = cairo.Context(self.surface) cr.scale(float(self.width) / writing.get_width(), float(self.height) / writing.get_height()) WritingStepsCairoRenderer.__init__(self, cr, writing) class WritingStepsPDFRenderer(WritingStepsCairoRenderer, _SurfaceRendererBase): def __init__(self, writing, filename, width=None, height=None, stroke_groups=None, start=0, length=None, n_chars_per_row=None): """ width and height are in points (1 point == 1/72.0 inch). """ self.writing = writing self.width = width self.height = height self.stroke_groups = stroke_groups self.start = start self.length = length self.n_chars_per_row = n_chars_per_row self._init() self.surface = cairo.PDFSurface(filename, self.width, self.height) cr = cairo.Context(self.surface) cr.scale(float(self.width) / writing.get_width(), float(self.height) / writing.get_height()) WritingStepsCairoRenderer.__init__(self, cr, writing) def inch_to_pt(*arr): arr = [inch * 72 for inch in arr] if len(arr) == 1: return arr[0] else: return arr def cm_to_pt(*arr): arr = [int(round(cm * 28.3464567)) for cm in arr] if len(arr) == 1: return arr[0] else: return arr tegaki-pygtk-0.3.1/tegakigtk/osd.py0000644000175000017500000001571611342122346017106 0ustar mathieumathieu# -*- coding: utf-8 -*- """ On Screen Display (OSD) for Tegaki """ import gtk import gobject from tegaki.character import Writing from tegakigtk.fakekey import send_unicode from tegaki.recognizer import Recognizer class Window(): def __init__(self, color='red', line_width=5): """ :param color: The foreground color we want to use. can be named ('black', 'red', etc.) or hex ('#ff0000', '#abcdef') :param line_width: The width of a line """ # create the window (without decorations and display in the taskbar #through override_redirect) self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) # get screen self.screen = self.window.get_screen() # get size self.size = (self.screen.get_width(), self.screen.get_height()) # get the colormap and the fg color self.colormap = self.screen.get_rgb_colormap() self.color = self.colormap.alloc_color(color) self.c_black = self.colormap.alloc_color('black') self.c_white = self.colormap.alloc_color('white') self.window.set_default_size(self.size[0], self.size[1]) self.window.set_decorated(False) self.window.set_colormap(self.colormap) self.window.show() self.window.window.set_override_redirect(True) # create the pixmap self.pixmap = gtk.gdk.Pixmap(self.window.window, self.size[0], self.size[1]) self.pixmap.set_colormap(self.colormap) self.pixmap.gc = self.pixmap.new_gc(foreground=self.color, line_width=line_width) self.pixmap.gc.set_colormap(self.colormap) # create the mask self.mask = gtk.gdk.Pixmap(None, self.size[0], self.size[1], 1) self.mask.gc = self.mask.new_gc(foreground=self.c_white, line_width=line_width) # reset everything self.clear() self.window.stick() # set `old_pos` self.old_pos = None def destroy(self): """ destroy the window """ self.window.destroy() def move_to(self, x, y): self.old_pos = (x, y) self.writing.move_to(x,y) def line_to(self, x, y): """ paint a new station in the gesture's path """ if self.old_pos: self.draw_line(self.old_pos[0], self.old_pos[1], x, y) self.writing.line_to(x,y) self.old_pos = (x, y) def clear(self): """ clear + remove all """ self.writing = Writing() self.writing.set_size(*self.size) self.window.hide() self.reset_mask() self.reset_pixmap() self.update_mask(False) self.update_pixmap() self.window.hide() self.old_pos = None def draw_line(self, x1, y1, x2, y2): """ wrapper for a line """ # draw on pixmap self.pixmap.draw_line(self.pixmap.gc, x1, y1, x2, y2) # draw on mask self.mask.draw_line(self.mask.gc, x1, y1, x2, y2) # update all self.update_mask() self.update_pixmap() def destroy(self): """ destroy the window """ self.window.destroy() def reset_mask(self): """ reset the shape mask to fully transparent """ # fill black self.mask.gc.set_foreground(self.c_black) #todo? self.mask.draw_rectangle(self.mask.gc, True, 0, 0, self.size[0], self.size[1]) self.mask.gc.set_foreground(self.c_white) def reset_pixmap(self): """ reset the pixmap to fully black """ # fill black self.pixmap.gc.set_foreground(self.c_black) #todo? self.pixmap.draw_rectangle(self.pixmap.gc, True, 0, 0, self.size[0], self.size[1]) self.pixmap.gc.set_foreground(self.color) def update_mask(self, do_show=True): """ update the mask """ self.window.window.input_shape_combine_mask(self.mask, 0, 0) # vllt nach #.show()? self.window.window.shape_combine_mask(self.mask, 0, 0) # vllt nach #.show()? if do_show: self.window.show() def update_pixmap(self): """ update the pixmap """ self.window.window.begin_paint_rect((0, 0, self.size[0], self.size[1])) self.window.window.set_back_pixmap(self.pixmap, False) self.window.window.end_paint() def get_writing(self): return self.writing.copy() class Listener: def __init__(self, recognizer): self.root_window = gtk.gdk.get_default_root_window() #self.create_osd_window() self.running = False self._window = Window() self._drawing = False self._new_stroke = True self._recognizer = recognizer def stop(self): self.running = False def start(self): self.running = True gobject.timeout_add(100, self._listen) def _listen(self): x, y, state = self.root_window.get_pointer() ctrl = gtk.gdk.CONTROL_MASK ctrl_left = gtk.gdk.CONTROL_MASK|gtk.gdk.BUTTON1_MASK if state & ctrl_left == ctrl_left: if self._new_stroke: self._window.move_to(x,y) else: self._window.line_to(x,y) self._new_stroke = False self._drawing = True elif state & ctrl == ctrl: self._new_stroke = True else: if self._drawing: print "drawing done" writing = self._window.get_writing() print writing writing.normalize() writing.upsample_threshold(10) # should not be necessary but... writing.resize(1000.0/writing.get_width(), 1000.0/writing.get_height()) writing.set_size(1000, 1000) res = recognizer.recognize(writing) best = res[0][0] self._window.clear() send_unicode(unicode(best, "utf8")) clipboard = gtk.Clipboard() clipboard.set_text(best) #win = gtk.Window() #from tegakigtk.canvas import Canvas #canvas = Canvas() #canvas.set_writing(writing) #win.add(canvas) #win.show_all() self._drawing = None return self.running if __name__ == "__main__": import sys #win = Window() ##win.show_all() #gtk.main() recognizer = sys.argv[1] # name of recognizer model = sys.argv[2] # name of model file recognizers = Recognizer.get_available_recognizers() print "Available recognizers", recognizers.keys() if not recognizer in recognizers: raise Exception, "Not an available recognizer" recognizer_klass = recognizers[recognizer] recognizer = recognizer_klass() models = recognizer_klass.get_available_models() print "Available models", models.keys() if not model in models: raise Exception, "Not an available model" recognizer.set_model(model) listener = Listener(recognizer) listener.start() gtk.main()tegaki-pygtk-0.3.1/tegakigtk/recognizer.py0000644000175000017500000007170511342122346020470 0ustar mathieumathieu# -*- coding: utf-8 -*- # Copyright (C) 2009 The Tegaki project contributors # # 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. # Contributors to this file: # - Mathieu Blondel import os from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError import gtk from gtk import gdk import gobject from canvas import Canvas from chartable import CharTable from tegaki.recognizer import Recognizer class RecognizerWidgetBase(gtk.HBox): DEFAULT_CANVAS_WIDTH = 250 __gsignals__ = { "commit-string" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_STRING]) } def __init__(self): gtk.HBox.__init__(self) self._recognizer = None self._search_on_stroke = True self._create_ui() self.clear_canvas() self.clear_characters() self._load_preferences() def _load_preferences(self): pm = PreferenceManager() pm.load() self.set_drawing_stopped_time(pm["GENERAL"]["DRAWING_STOPPED_TIME"]) self.set_search_on_stroke(pm["GENERAL"]["SEARCH_ON_STROKE"]) self.set_selected_model(pm["GENERAL"]["SELECTED_MODEL"]) self.set_draw_annotations(pm["GENERAL"]["DRAW_ANNOTATIONS"]) def _save_preferences(self): pm = PreferenceManager() pm["GENERAL"]["DRAWING_STOPPED_TIME"] = self.get_drawing_stopped_time() pm["GENERAL"]["SEARCH_ON_STROKE"] = self.get_search_on_stroke() pm["GENERAL"]["SELECTED_MODEL"] = self.get_selected_model() pm["GENERAL"]["DRAW_ANNOTATIONS"] = self.get_draw_annotations() pm.save() def _create_toolbar_separator(self): self._toolbar.pack_start(gtk.HSeparator(), expand=False) def _create_clear_button(self): self._clear_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_BUTTON) self._clear_button.set_image(image) self._clear_button.connect("clicked", self._on_clear) self._toolbar.pack_start(self._clear_button, expand=False) def _create_find_button(self): self._find_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_FIND, gtk.ICON_SIZE_BUTTON) self._find_button.set_image(image) self._find_button.connect("clicked", self._on_find) self._toolbar.pack_start(self._find_button, expand=False) def _create_undo_button(self): self._undo_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_UNDO, gtk.ICON_SIZE_BUTTON) self._undo_button.set_image(image) self._undo_button.connect("clicked", self._on_undo) self._toolbar.pack_start(self._undo_button, expand=False) def _create_prefs_button(self): self._prefs_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_BUTTON) self._prefs_button.set_image(image) self._prefs_button.connect("clicked", self._on_prefs) self._toolbar.pack_start(self._prefs_button, expand=False) def _create_models_button(self): self._models_button = gtk.Button("Models") self._models_button.connect("button-press-event", self._on_models) self._toolbar.pack_start(self._models_button, expand=False) def _create_model_menu(self): menu = gtk.Menu() all_models = Recognizer.get_all_available_models() if len(all_models) == 0: return None i = 0 for r_name, model_name, meta in all_models: item = gtk.MenuItem("%d. %s (%s)" % (i+1, model_name, r_name)) item.connect("activate", self._on_activate_model, i) menu.append(item) i += 1 return menu def _create_canvas(self, canvas_name): canvas = Canvas() canvas.set_size_request(self.DEFAULT_CANVAS_WIDTH, self.DEFAULT_CANVAS_WIDTH) canvas.connect("button-press-event", self._on_canvas_button_press, canvas_name) canvas.connect("drawing-stopped", self._on_canvas_drawing_stopped, canvas_name) canvas.connect("stroke-added", self._on_canvas_stroke_added, canvas_name) setattr(self, canvas_name, canvas) frame = gtk.Frame() frame.add(canvas) setattr(self, canvas_name + "_frame", frame) def _create_chartable(self): self._chartable_frame = gtk.Frame() self._chartable = CharTable() self._chartable_frame.add(self._chartable) self._chartable.connect("character-selected", self._on_character_selected) def _on_models(self, button, event): menu = self._create_model_menu() if menu: menu.show_all() menu.popup(None, None, None, event.button, event.time) else: parent = self.get_toplevel() msg = "No recognizers and/or no models installed!" dialog = ErrorDialog(parent, msg).run() def _on_activate_model(self, item, i): self.set_selected_model(i) self._save_preferences() def _on_find(self, button): self.find() def _on_undo(self, button): self.revert_stroke() def _on_prefs(self, button): parent = self.get_toplevel() if not parent.flags() & gtk.TOPLEVEL: parent = None pref_dialog = PreferenceDialog(parent) pref_dialog.connect("response", self._on_pref_validate) pref_dialog.set_search_on_stroke(self.get_search_on_stroke()) pref_dialog.set_drawing_stopped_time(self.get_drawing_stopped_time()) pref_dialog.set_draw_annotations(self.get_draw_annotations()) pref_dialog.run() def _on_pref_validate(self, dialog, response): if response == gtk.RESPONSE_OK: if dialog.get_search_on_stroke(): self.set_search_on_stroke(True) else: self.set_drawing_stopped_time(dialog.get_drawing_stopped_time()) self.set_draw_annotations(dialog.get_draw_annotations()) self._save_preferences() dialog.destroy() def _on_clear(self, button): self.clear_canvas() def clear_all(self): self.clear_characters() self.clear_canvas() def get_search_on_stroke(self): return self._search_on_stroke def set_search_on_stroke(self, enabled): self._search_on_stroke = enabled def get_characters(self): return self._chartable.get_characters() def get_selected_model(self): return self._models_button.selected_model def set_selected_model(self, i): try: r_name, model_name, meta = Recognizer.get_all_available_models()[i] klass = Recognizer.get_available_recognizers()[r_name] self._recognizer = klass() self._recognizer.set_model(meta["name"]) self._models_button.set_label(meta["shortname"]) # a hack to retain the model id the button self._models_button.selected_model = i self._ready = True except IndexError: self._ready = False def get_toolbar_vbox(self): return self._toolbar class SimpleRecognizerWidget(RecognizerWidgetBase): def __init__(self): RecognizerWidgetBase.__init__(self) def _create_toolbar(self): self._toolbar = gtk.VBox(spacing=2) self._create_find_button() self._create_toolbar_separator() self._create_undo_button() self._create_clear_button() self._create_toolbar_separator() self._create_models_button() self._create_prefs_button() def _create_ui(self): self._create_canvasbox() self._create_chartable() vbox = gtk.VBox(spacing=2) vbox.pack_start(self._canvasbox, expand=True) vbox.pack_start(self._chartable_frame, expand=False) self._create_toolbar() self.set_spacing(2) self.pack_start(vbox, expand=True) self.pack_start(self._toolbar, expand=False) def _create_canvasbox(self): self._create_canvas("_canvas") self._canvasbox = self._canvas_frame def _on_canvas_button_press(self, widget, event, curr_canv): pass def _on_canvas_drawing_stopped(self, widget, curr_canv): if not self._search_on_stroke: self.find() def _on_canvas_stroke_added(self, widget, curr_canv): if self._search_on_stroke: self.find() def _on_character_selected(self, chartable, event): chars = self._chartable.get_characters() selected = self._chartable.get_selected() self.emit("commit-string", chars[selected]) def clear_canvas(self): self._canvas.clear() self.clear_characters() def clear_characters(self): self._chartable.clear() def get_drawing_stopped_time(self): return self._canvas.get_drawing_stopped_time() def set_drawing_stopped_time(self, time_msec): self._search_on_stroke = False self._canvas.set_drawing_stopped_time(time_msec) def get_draw_annotations(self): return self._canvas.get_draw_annotations() def set_draw_annotations(self, active): self._canvas.set_draw_annotations(active) def revert_stroke(self): self._canvas.revert_stroke() if self._search_on_stroke: self.find() def find(self): if not self._ready: return writing = self._canvas.get_writing().copy() if writing.get_n_strokes() > 0: candidates = self._recognizer.recognize(writing, n=9) candidates = [char for char, prob in candidates] self._chartable.set_characters(candidates) def get_writing(self): self._canvas.get_writing() def set_writing(self, writing): self._canvas.set_writing(writing) class SmartRecognizerWidget(RecognizerWidgetBase): OTHER_CANVAS_COLOR = (0xFFFF, 0xFFFF, 0xFFFF) CURR_CANVAS_COLOR = map(lambda x: x * 256, (255, 235, 235)) def __init__(self): RecognizerWidgetBase.__init__(self) def _create_toolbar(self): self._toolbar = gtk.VBox(spacing=2) self._create_commit_button() self._create_del_button() self._create_toolbar_separator() self._create_find_button() self._create_toolbar_separator() self._create_undo_button() self._create_clear_button() self._create_toolbar_separator() self._create_models_button() self._create_prefs_button() def _create_commit_button(self): self._commit_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_BUTTON) self._commit_button.set_image(image) self._commit_button.connect("clicked", self._on_commit) self._toolbar.pack_start(self._commit_button, expand=False) def _create_del_button(self): self._del_button = gtk.Button("Del") self._del_button.connect("clicked", self._on_delete) self._toolbar.pack_start(self._del_button, expand=False) def _create_ui(self): self._create_canvasbox() self._create_chartable() vbox = gtk.VBox(spacing=2) vbox.pack_start(self._chartable_frame, expand=False) vbox.pack_start(self._canvasbox, expand=True) self._create_toolbar() self.set_spacing(2) self.pack_start(vbox, expand=True) self.pack_start(self._toolbar, expand=False) def _create_canvasbox(self): self._canvasbox = gtk.HBox(spacing=2) self._create_canvas("_canvas1") self._create_canvas("_canvas2") self._canvasbox.pack_start(self._canvas1_frame) self._canvasbox.pack_start(self._canvas2_frame) def _find(self, canvas): if not self._ready: return writing = getattr(self, canvas).get_writing() if writing.get_n_strokes() == 0: return writing = writing.copy() candidates = self._recognizer.recognize(writing) candidates = [char for char, prob in candidates] if candidates: candidate_list = CandidateList(candidates) if canvas == self._last_completed_canvas: # update the current character if the same canvas was used last = len(self.get_characters()) - 1 self.replace_character(last, candidate_list) self._writings[last] = writing else: # append character otherwise self.add_character(candidate_list) self._writings.append(writing) self._last_completed_canvas = canvas def _other_canvas(self, canvas): if canvas == "_canvas1": othr_canv = "_canvas2" else: othr_canv = "_canvas1" return othr_canv def _set_canvas_focus(self, curr_canv): othr_canv = self._other_canvas(curr_canv) self._focused_canvas = curr_canv # set background color for canvas, color in ((curr_canv, self.CURR_CANVAS_COLOR), (othr_canv, self.OTHER_CANVAS_COLOR)): getattr(self, canvas).set_background_color(*color) def _on_canvas_button_press(self, widget, event, curr_canv): othr_canv = self._other_canvas(curr_canv) if self._focused_canvas == othr_canv: getattr(self, curr_canv).clear() if getattr(self, othr_canv).get_writing().get_n_strokes() > 0 and \ self._last_completed_canvas != othr_canv and \ not self._search_on_stroke: self._find(othr_canv) self._set_canvas_focus(curr_canv) def _on_canvas_drawing_stopped(self, widget, curr_canv): if self._focused_canvas == curr_canv and not self._search_on_stroke: self._find(curr_canv) def _on_canvas_stroke_added(self, widget, curr_canv): if self._search_on_stroke: self._find(curr_canv) def _on_commit(self, button): chars = self.get_selected_characters() if len(chars) > 0: self.clear_all() self.emit("commit-string", "".join(chars)) def _on_delete(self, button): self.delete_character() def _on_character_selected(self, chartable, event): selected = self._chartable.get_selected() candidates = self._characters[selected] popup = CandidatePopup(candidates) popup.move(int(event.x_root), int(event.y_root) + \ int(self._chartable.allocation.height/3)) popup.connect("character-selected", self._on_candidate_selected) popup.connect("hide", self._on_popup_close) popup.connect("edit-character", self._on_edit_character) popup.connect("delete-character", self._on_delete_character) popup.popup() def _on_candidate_selected(self, popup, event): char_selected = self._chartable.get_selected() cand_selected = popup.get_selected() self._characters[char_selected].selected = cand_selected self._chartable.set_characters(self.get_selected_characters()) self._chartable.unselect() def _on_edit_character(self, popup): char_selected = self._chartable.get_selected() edit_window = gtk.Window() edit_window.set_title("Edit character") rw = SimpleRecognizerWidget() rw.set_writing(self._writings[char_selected]) edit_window.add(rw) parent = self.get_toplevel() if parent.flags() & gtk.TOPLEVEL: edit_window.set_transient_for(parent) edit_window.set_position(gtk.WIN_POS_CENTER_ON_PARENT) edit_window.set_type_hint(gdk.WINDOW_TYPE_HINT_DIALOG) edit_window.set_modal(True) rw.connect("commit-string", self._on_commit_edited_char, char_selected) edit_window.show_all() def _on_commit_edited_char(self, rw, char, char_selected): candidate_list = CandidateList(rw.get_characters()) candidate_list.set_selected(char) self.replace_character(char_selected, candidate_list) rw.get_parent().destroy() def _on_delete_character(self, popup): char_selected = self._chartable.get_selected() self.remove_character(char_selected) def _on_popup_close(self, popup): self._chartable.unselect() def clear_canvas(self): self._canvas1.clear() if self._canvas2: self._canvas2.clear() self._set_canvas_focus("_canvas1") self._last_completed_canvas = None def delete_character(self): try: self._characters.pop() self._writings.pop() self._chartable.set_characters(self.get_selected_characters()) self._chartable.unselect() except IndexError: pass def clear_characters(self): self._characters = [] self._writings = [] self._chartable.clear() def add_character(self, candidate_list): if len(candidate_list) > 0: self._characters.append(candidate_list) self._chartable.set_characters(self.get_selected_characters()) def replace_character(self, index, candidate_list): if len(candidate_list) > 0: try: self._characters[index] = candidate_list self._chartable.set_characters(self.get_selected_characters()) except IndexError: pass def remove_character(self, index): length = len(self._chartable.get_characters()) if length > 0 and index <= length - 1: del self._characters[index] del self._writings[index] self._chartable.set_characters(self.get_selected_characters()) def get_selected_characters(self): return [char[char.selected] for char in self._characters] def get_drawing_stopped_time(self): return self._canvas1.get_drawing_stopped_time() def set_drawing_stopped_time(self, time_msec): self._search_on_stroke = False for canvas in (self._canvas1, self._canvas2): canvas.set_drawing_stopped_time(time_msec) def get_draw_annotations(self): return self._canvas1.get_draw_annotations() def set_draw_annotations(self, active): for canvas in (self._canvas1, self._canvas2): canvas.set_draw_annotations(active) def revert_stroke(self): if self._focused_canvas: getattr(self, self._focused_canvas).revert_stroke() def find(self): if self._focused_canvas: self._find(self._focused_canvas) class CandidatePopup(gtk.Window): __gsignals__ = { "character_selected" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, [gobject.TYPE_PYOBJECT]), "edit-character" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, []), "delete-character" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, []) } def __init__(self, candidates): gtk.Window.__init__(self, gtk.WINDOW_POPUP) self._candidates = candidates self._create_ui() def get_selected(self): return self._chartable.get_selected() def _create_ui(self): self.add_events(gdk.BUTTON_PRESS_MASK) self.set_title("Candidates") frame = gtk.Frame() self._chartable = CharTable() self._chartable.add_events(gdk.BUTTON_PRESS_MASK) self._chartable.set_characters(self._candidates) self._chartable.set_layout(CharTable.LAYOUT_HORIZONTAL) max_width, max_height = self._chartable.get_max_char_size() self._chartable.set_size_request(int(max_width*3.5), int(max_height*3.5)) frame.add(self._chartable) self.connect("button-press-event", self._on_button_press) self._chartable.connect("character-selected", self._on_character_selected) vbox = gtk.VBox(spacing=2) vbox.pack_start(frame) self._edit_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_EDIT, gtk.ICON_SIZE_BUTTON) self._edit_button.set_image(image) self._edit_button.set_relief(gtk.RELIEF_NONE) self._edit_button.connect("clicked", self._on_edit) self._delete_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_DELETE, gtk.ICON_SIZE_BUTTON) self._delete_button.set_image(image) self._delete_button.set_relief(gtk.RELIEF_NONE) self._delete_button.connect("clicked", self._on_delete) self._close_button = gtk.Button() image = gtk.image_new_from_stock(gtk.STOCK_CLOSE, gtk.ICON_SIZE_BUTTON) self._close_button.set_image(image) self._close_button.set_relief(gtk.RELIEF_NONE) self._close_button.connect("clicked", self._on_close) frame = gtk.Frame() buttonbox = gtk.HBox() buttonbox.pack_start(self._edit_button, expand=False) buttonbox.pack_start(self._delete_button, expand=False) buttonbox.pack_start(self._close_button, expand=False) frame.add(buttonbox) vbox.pack_start(frame) self.add(vbox) def _on_close(self, button): self.popdown() def _on_edit(self, button): self.emit("edit-character") self.popdown() def _on_delete(self, button): self.emit("delete-character") self.popdown() def _on_character_selected(self, chartable, event): self.emit("character-selected", event) def _on_button_press(self, window, event): # If we're clicking outside of the window or in the chartable # close the popup if (event.window != self.window or (tuple(self.allocation.intersect( gdk.Rectangle(x=int(event.x), y=int(event.y), width=1, height=1)))) == (0, 0, 0, 0)): self.popdown() def popup(self): self.show_all() # grab pointer self.grab_add() gdk.pointer_grab(self.window, True, gdk.BUTTON_PRESS_MASK| gdk.BUTTON_RELEASE_MASK| gdk.POINTER_MOTION_MASK, None, None, gtk.get_current_event_time()) def popdown(self): gdk.pointer_ungrab(gtk.get_current_event_time()) self.grab_remove() self.destroy() class CandidateList(list): def __init__(self, initial_candidates=[]): self.extend(initial_candidates) self.selected = 0 def get_selected(self): try: return self[self.selected] except IndexError: return None def set_selected(self, name): try: i = self.index(name) self.selected = i except ValueError: pass class ErrorDialog(gtk.MessageDialog): def __init__(self, parent, msg): gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, msg) self.connect("response", lambda w,r: self.destroy()) class PreferenceManager(dict): def __init__(self): dict.__init__(self) self._init_paths() self._init_dirs() self._init_defaults() def _init_defaults(self): self["GENERAL"] = {} def _init_paths(self): try: self._home_dir = os.environ['HOME'] self._tegaki_dir = os.path.join(self._home_dir, ".tegaki") except KeyError: self._home_dir = os.environ['USERPROFILE'] self._tegaki_dir = os.path.join(self._home_dir, "tegaki") self._conf_file = os.path.join(self._tegaki_dir, "recognizer.ini") def _init_dirs(self): if not os.path.exists(self._tegaki_dir): os.makedirs(self._tegaki_dir) def load(self): config = SafeConfigParser() config.read(self._conf_file) for opt, dflt, meth in [("SEARCH_ON_STROKE", True, config.getboolean), ("DRAWING_STOPPED_TIME", 0, config.getint), ("SELECTED_MODEL", 0, config.getint), ("DRAW_ANNOTATIONS", 1, config.getboolean)]: try: self["GENERAL"][opt] = meth("GENERAL", opt) except (NoSectionError, NoOptionError, ValueError), e: self["GENERAL"][opt] = dflt def save(self): config = SafeConfigParser() for section in self.keys(): if not config.has_section(section): config.add_section(section) for opt, value in self[section].items(): config.set(section, opt, str(value)) f = open(self._conf_file, "w") config.write(f) f.close() class PreferenceDialog(gtk.Dialog): def __init__(self, parent): gtk.Dialog.__init__(self) self._init_dialog(parent) self._create_ui() def _init_dialog(self, parent): self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK) self.set_default_response(gtk.RESPONSE_OK) self.set_has_separator(True) self.set_transient_for(parent) self.set_border_width(6) self.set_modal(True) self.set_title("Preferences") def _create_ui(self): self._search_on_stroke = gtk.RadioButton(group=None, label="Search on stroke") self._search_on_stroke.connect("toggled", self._on_search_on_stroke) self._search_after = gtk.RadioButton(group=self._search_on_stroke, label="Search after:") self._search_after.connect("toggled", self._on_search_after) adjustment = gtk.Adjustment(value=0, lower=0, upper=3000, step_incr=100, page_incr=0, page_size=0) self._spinbutton = gtk.SpinButton(adjustment) self._spinbutton.set_sensitive(False) self._search_after_hbox = gtk.HBox(spacing=2) self._search_after_hbox.pack_start(self._search_after, expand=False) self._search_after_hbox.pack_start(self._spinbutton, expand=False) self._search_after_hbox.pack_start(gtk.Label("[msecs]"), expand=False) self._draw_annotations = gtk.CheckButton(label="Draw annotations") main_vbox = self.get_child() main_vbox.set_spacing(10) main_vbox.pack_start(self._search_on_stroke) main_vbox.pack_start(self._search_after_hbox) main_vbox.pack_start(self._draw_annotations) self.show_all() def _on_search_on_stroke(self, radiobutton): self._spinbutton.set_sensitive(False) def _on_search_after(self, radiobutton): self._spinbutton.set_sensitive(True) def get_search_on_stroke(self): return self._search_on_stroke.get_active() def set_search_on_stroke(self, active): self._search_on_stroke.set_active(active) self._search_after.set_active(not(active)) def get_draw_annotations(self): return self._draw_annotations.get_active() def set_draw_annotations(self, active): self._draw_annotations.set_active(active) def get_search_after(self): return self._search_after.get_active() def set_search_after(self, active): self._search_after.set_active(active) self._search_on_stroke.set_active(not(active)) def get_drawing_stopped_time(self): return int(self._spinbutton.get_value()) def set_drawing_stopped_time(self, time): self._spinbutton.set_value(int(time)) if __name__ == "__main__": import sys try: simple = int(sys.argv[1]) except IndexError: simple = False window = gtk.Window() if simple: recognizer_widget = SimpleRecognizerWidget() else: recognizer_widget = SmartRecognizerWidget() def on_commit_string(rw, string): print string recognizer_widget.connect("commit-string", on_commit_string) window.add(recognizer_widget) window.show_all() gtk.main()tegaki-pygtk-0.3.1/README0000644000175000017500000000071511342122346014646 0ustar mathieumathieutegaki-pygtk ============ Base user interface library for the Tegaki project. Requirements ------------ Python 2.4 http://www.python.org pygtk 2.10 http://www.pygtk.org tegaki-python 0.2 Install ------- ($ su) # python setup.py install License ------- This package is distributed under the terms of the GNU General Public License. See the COPYING file for more information. Homepage -------- http://www.tegaki.org tegaki-pygtk-0.3.1/ChangeLog0000644000175000017500000000737311352066723015556 0ustar mathieumathieucommit 5b0b86343c91cbf3d7ee683e82f41f9df75edf4d Author: Mathieu Blondel Date: Mon Mar 22 15:32:33 2010 +0900 [all] Set current version to 0.3.1. commit 9cc6c138b363a4ef19580b991bb574ed0167f76a Author: Mathieu Blondel Date: Thu Dec 24 16:24:31 2009 +0900 [tegaki-pygtk] Fixed typo and bumped to version 0.4. commit da137c803c137c41ab931e546bdd3b96e4eff3eb Author: Mathieu Blondel Date: Wed Dec 23 20:25:19 2009 +0900 [tegaki-canvas] Support writing objects of arbitrary size. commit 386ca12147f208d1264f48900c13c62c15f9393e Author: Mathieu Blondel Date: Wed Dec 23 17:53:56 2009 +0900 [tegaki-pygtk] Added set_draw_axis(). commit 82a054aed86258d2567892a6964b540bb5ef83b7 Author: Mathieu Blondel Date: Wed Dec 23 14:49:51 2009 +0900 [tegaki-pygtk] Fix pb when no display available. commit 8530dea2cea289d8f3d9d5d6f8b5803ff33ac4b1 Author: Mathieu Blondel Date: Wed Dec 23 03:59:02 2009 +0900 [tegaki-pygtk] Fake key events. commit 93aeb45451066b4cf27a25949597a300fcf37002 Author: Mathieu Blondel Date: Wed Dec 2 21:28:01 2009 +0900 [tegaki-pygtk] Added documentation for Canvas. commit 23428970b5125e6effc233ff3261e6cb368ff93d Author: Mathieu Blondel Date: Sun Nov 1 20:56:48 2009 +0900 [all] Include ChangeLog. commit 7802dbc65fcc51ef83425f77e767037e27597969 Author: Mathieu Blondel Date: Sun Nov 1 19:34:53 2009 +0900 [tegaki-pygtk] Removed NEWS file. commit 226876d3ada0df56700adeee160ab09e4a252d92 Author: Mathieu Blondel Date: Sun Oct 25 20:16:34 2009 +0900 [tegaki-pygtk] Bumped to version 0.3 commit 5bf471341a4db7051529107018f69d88b49f094f Author: Christoph Burgmer Date: Mon Oct 12 10:27:47 2009 +0200 [tegaki-pygtk] Fix float division by zero commit 799a160957b39ee1d87cad99c64366dfb368bbf7 Author: Mathieu Blondel Date: Sun Sep 27 01:30:07 2009 +0900 [all] Distutils on python 2.6 for win32 doesn't like end slashes for directories. commit 132878388c28366ddb6335f7ab920a306d6a4d26 Author: Mathieu Blondel Date: Fri Sep 18 01:46:14 2009 +0900 [tegaki-pygtk] Fixed replay() in Canvas for characters that don't include time information. commit d0435bc65ff2bec4c00505a156379e968474df69 Author: Mathieu Blondel Date: Thu Sep 3 18:48:49 2009 +0900 [tegaki-pygtk] Various improvements to renderers. commit 292833eb09d5091031a726fe83eae674c222dccc Author: Mathieu Blondel Date: Fri Jul 31 17:52:25 2009 +0900 [tegaki-pygtk] Use a copy of the writing object in simple recognizer. commit 29cc0f1657f4933a0c5683477c7a7128ffa5503f Author: Mathieu Blondel Date: Tue Jul 28 12:18:14 2009 +0900 [tegaki-pygtk] Make the candidate popup window a little bit bigger. commit 072589a2417565b3697ae3abc8e547b06ccde39d Author: Mathieu Blondel Date: Sun Jul 19 11:45:53 2009 +0200 [all] Update project URL. commit 6f796ef5c39bcb39a94399518368cbaca2dbf6cc Author: Mathieu Blondel Date: Sun Jul 19 11:38:05 2009 +0200 [tegaki-pygtk] Fixed setup.py. commit 94c701ab036903a7ae162b4ba9c76b43090f8b18 Author: Mathieu Blondel Date: Sun Jul 19 05:53:54 2009 +0200 [tegaki-pygtk] Added NEWS file. commit 10ea23607f9a0879e1c1c459cf83e763286871da Author: Mathieu Blondel Date: Sun Jul 19 05:23:37 2009 +0200 [tegaki,tegaki-gtk] Renamed the packages to respectively tegaki-python and tegaki-pygtk to make it clear that they are Python packages. tegaki-pygtk-0.3.1/data/0000755000175000017500000000000011352066723014703 5ustar mathieumathieutegaki-pygtk-0.3.1/data/tegaki/0000755000175000017500000000000011352066723016147 5ustar mathieumathieutegaki-pygtk-0.3.1/data/tegaki/icons/0000755000175000017500000000000011352066723017262 5ustar mathieumathieutegaki-pygtk-0.3.1/data/tegaki/icons/handwriting.png0000644000175000017500000000042411342122346022277 0ustar mathieumathieuPNG  IHDRabKGDIDATxc` KPC300XQ B300īsg``τiږ9NyaSouo5 A4o&U .Bata:וO4OL 300\zE῿h#:A-D! `MG XIENDB`tegaki-pygtk-0.3.1/setup.py0000644000175000017500000000143711342122346015502 0ustar mathieumathieu# -*- coding: utf-8 -*- from distutils.core import setup import os def getversion(): currdir = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(currdir, "tegakigtk", "__init__.py") import re regexp = re.compile(r"VERSION = '([^']*)'") f = open(path) buf = f.read() f.close() return regexp.search(buf).group(1) # Please run # python setup.py install setup( name = 'tegaki-pygtk', description = 'Tegaki pygtk library', author = 'Mathieu Blondel', author_email = 'mathieu ÂT mblondel DÔT org', url = 'http://www.tegaki.org', version = getversion(), license='GPL', packages = ['tegakigtk'], package_dir = {'tegakigtk':'tegakigtk'}, data_files=[('share/tegaki/icons', ['data/tegaki/icons/handwriting.png'])] )tegaki-pygtk-0.3.1/MANIFEST.in0000644000175000017500000000024411342122346015521 0ustar mathieumathieuinclude AUTHORS COPYING COPYRIGHT README TODO MANIFEST.in ChangeLog exclude *~ *.orig *.bak *.tmp *.pyc MANIFEST recursive-include tests * recursive-include data * tegaki-pygtk-0.3.1/COPYRIGHT0000644000175000017500000000027411342122346015261 0ustar mathieumathieuThe code included in this package is copyrighted by Mathieu Blondel : Copyright (C) 2008 Mathieu Blondel. All Rights Reserved. See the COPYING File for the terms of distribution licence.tegaki-pygtk-0.3.1/TODO0000644000175000017500000000014311342122346014451 0ustar mathieumathieu- Rewrite the Canvas with cairo. (the widget should not redraw itself completely on expose events!)