From 86e216671b8e5d5fbc712734e294f62d950832c1 Mon Sep 17 00:00:00 2001 From: Philippe Lagadec Date: Tue, 9 Oct 2012 22:47:02 +0200 Subject: [PATCH] Initial version of olebrowse and xxxswf2 --- oletools/LICENSE.txt | 25 +++++++++++++++++++++++++ oletools/__init__.py | 0 oletools/ezhexviewer.py | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ oletools/olebrowse.py | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ oletools/thirdparty/OleFileIO_PL/LICENSE.txt | 31 +++++++++++++++++++++++++++++++ oletools/thirdparty/OleFileIO_PL/OleFileIO_PL.py | 1674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ oletools/thirdparty/OleFileIO_PL/README.txt | 173 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ oletools/thirdparty/OleFileIO_PL/__init__.py | 0 oletools/thirdparty/__init__.py | 0 oletools/thirdparty/easygui/LICENSE.txt | 32 ++++++++++++++++++++++++++++++++ oletools/thirdparty/easygui/__init__.py | 0 oletools/thirdparty/easygui/easygui.py | 2492 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ oletools/thirdparty/xxxswf/LICENSE.txt | 3 +++ oletools/thirdparty/xxxswf/__init__.py | 0 oletools/thirdparty/xxxswf/xxxswf.py | 371 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ oletools/xxxswf2.py | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 16 files changed, 5138 insertions(+), 0 deletions(-) create mode 100644 oletools/LICENSE.txt create mode 100644 oletools/__init__.py create mode 100644 oletools/ezhexviewer.py create mode 100644 oletools/olebrowse.py create mode 100644 oletools/thirdparty/OleFileIO_PL/LICENSE.txt create mode 100644 oletools/thirdparty/OleFileIO_PL/OleFileIO_PL.py create mode 100644 oletools/thirdparty/OleFileIO_PL/README.txt create mode 100644 oletools/thirdparty/OleFileIO_PL/__init__.py create mode 100644 oletools/thirdparty/__init__.py create mode 100644 oletools/thirdparty/easygui/LICENSE.txt create mode 100644 oletools/thirdparty/easygui/__init__.py create mode 100644 oletools/thirdparty/easygui/easygui.py create mode 100644 oletools/thirdparty/xxxswf/LICENSE.txt create mode 100644 oletools/thirdparty/xxxswf/__init__.py create mode 100644 oletools/thirdparty/xxxswf/xxxswf.py create mode 100644 oletools/xxxswf2.py diff --git a/oletools/LICENSE.txt b/oletools/LICENSE.txt new file mode 100644 index 0000000..ce17131 --- /dev/null +++ b/oletools/LICENSE.txt @@ -0,0 +1,25 @@ +LICENSE for the oletools package: + + +Copyright (c) 2012, Philippe Lagadec (http://www.decalage.info) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/oletools/__init__.py b/oletools/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/oletools/__init__.py diff --git a/oletools/ezhexviewer.py b/oletools/ezhexviewer.py new file mode 100644 index 0000000..af158d1 --- /dev/null +++ b/oletools/ezhexviewer.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python +""" +ezhexviewer.py + +A simple hexadecimal viewer based on easygui. It should work on any platform +with Python 2.x. + +Usage: ezhexviewer.py [file] + +Usage in a python application: + + import ezhexviewer + ezhexviewer.hexview_file(filename) + ezhexviewer.hexview_data(data) + + +ezhexviewer project website: http://www.decalage.info/python/ezhexviewer + +ezhexviewer is copyright (c) 2012, Philippe Lagadec (http://www.decalage.info) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +__version__ = '0.01' + +#------------------------------------------------------------------------------ +# CHANGELOG: +# 2012-09-17 v0.01 PL: - first version +# 2012-10-04 v0.02 PL: - added license + +#------------------------------------------------------------------------------ +# TODO: +# + options to set title and msg + + +from thirdparty.easygui import easygui +import sys + +#------------------------------------------------------------------------------ +# The following code (hexdump3 only) is a modified version of the hex dumper +# recipe published on ASPN by Sebastien Keim and Raymond Hattinger under the +# PSF license. I added the startindex parameter. +# see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/142812 +# PSF license: http://docs.python.org/license.html +# Copyright (c) 2001-2012 Python Software Foundation; All Rights Reserved + +FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) + +def hexdump3(src, length=8, startindex=0): + """ + Returns a hexadecimal dump of a binary string. + length: number of bytes per row. + startindex: index of 1st byte. + """ + result=[] + for i in xrange(0, len(src), length): + s = src[i:i+length] + hexa = ' '.join(["%02X"%ord(x) for x in s]) + printable = s.translate(FILTER) + result.append("%08X %-*s %s\n" % (i+startindex, length*3, hexa, printable)) + return ''.join(result) + +# end of PSF-licensed code. +#------------------------------------------------------------------------------ + + +def hexview_data (data, msg='', title='ezhexviewer', length=16, startindex=0): + hex = hexdump3(data, length=length, startindex=startindex) + easygui.codebox(msg=msg, title=title, text=hex) + + +def hexview_file (filename, msg='', title='ezhexviewer', length=16, startindex=0): + data = open(filename, 'rb').read() + hexview_data(data, msg=msg, title=title, length=length, startindex=startindex) + + +if __name__ == '__main__': + try: + filename = sys.argv[1] + except: + filename = easygui.fileopenbox() + if filename: + try: + hexview_file(filename, msg='File: %s' % filename) + except: + easygui.exceptionbox(msg='Error:', title='ezhexviewer') diff --git a/oletools/olebrowse.py b/oletools/olebrowse.py new file mode 100644 index 0000000..95fcd45 --- /dev/null +++ b/oletools/olebrowse.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python +""" +olebrowse.py + +A simple GUI to browse OLE files (e.g. MS Word, Excel, Powerpoint documents), to +view and extract individual data streams. + +Usage: olebrowse.py [file] + +olebrowse project website: http://www.decalage.info/python/olebrowse + +olebrowse is copyright (c) 2012, Philippe Lagadec (http://www.decalage.info) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +__version__ = '0.01' + +#------------------------------------------------------------------------------ +# CHANGELOG: +# 2012-09-17 v0.01 PL: - first version + +#------------------------------------------------------------------------------ +# TODO: +# - menu option to open another file +# - menu option to display properties +# - menu option to run xxxswf2, oleid, oleyara, olecarve, etc +# - for a stream, display info: size, path, etc +# - stream info: magic, entropy, ... ? + +import optparse, sys, os +from thirdparty.easygui import easygui +from thirdparty.OleFileIO_PL import OleFileIO_PL +import ezhexviewer + +ABOUT = '~ About olebrowse' +QUIT = '~ Quit' + + +def about (): + easygui.textbox(title='About olebrowse', text=__doc__) + + +def browse_stream (ole, stream): + #print 'stream:', stream + while True: + msg ='Select an action for the stream "%s", or press Esc to exit' % repr(stream) + actions = [ + 'Hex view', +## 'Text view', +## 'Repr view', + 'Save stream to file', + '~ Back to main menu', + ] + action = easygui.choicebox(msg, title='olebrowse', choices=actions) + if action is None or 'Back' in action: + break + elif action.startswith('Hex'): + data = ole.openstream(stream).getvalue() + ezhexviewer.hexview_data(data, msg='Stream: %s' % stream, title='olebrowse') +## elif action.startswith('Text'): +## data = ole.openstream(stream).getvalue() +## easygui.codebox(title='Text view - %s' % stream, text=data) +## elif action.startswith('Repr'): +## data = ole.openstream(stream).getvalue() +## easygui.codebox(title='Repr view - %s' % stream, text=repr(data)) + elif action.startswith('Save'): + data = ole.openstream(stream).getvalue() + fname = easygui.filesavebox(default='stream.bin') + if fname is not None: + f = open(fname, 'wb') + f.write(data) + f.close() + easygui.msgbox('stream saved to file %s' % fname) + + + +def main(): + try: + filename = sys.argv[1] + except: + filename = easygui.fileopenbox() + try: + ole = OleFileIO_PL.OleFileIO(filename) + listdir = ole.listdir() + streams = [] + for direntry in listdir: + #print direntry + streams.append('/'.join(direntry)) + streams.append(ABOUT) + streams.append(QUIT) + stream = True + while stream is not None: + msg ="Select a stream, or press Esc to exit" + title = "olebrowse" + stream = easygui.choicebox(msg, title, streams) + if stream is None or stream == QUIT: + break + if stream == ABOUT: + about() + else: + browse_stream(ole, stream) + except: + easygui.exceptionbox() + + + + +if __name__ == '__main__': + main() diff --git a/oletools/thirdparty/OleFileIO_PL/LICENSE.txt b/oletools/thirdparty/OleFileIO_PL/LICENSE.txt new file mode 100644 index 0000000..7251e41 --- /dev/null +++ b/oletools/thirdparty/OleFileIO_PL/LICENSE.txt @@ -0,0 +1,31 @@ +LICENSE for the OleFileIO_PL module: + + +OleFileIO_PL is an improved version of the OleFileIO module from the +Python Imaging Library (PIL). + +OleFileIO_PL changes are Copyright (c) 2005-2012 by Philippe Lagadec + +The Python Imaging Library (PIL) is + Copyright (c) 1997-2005 by Secret Labs AB + Copyright (c) 1995-2005 by Fredrik Lundh + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply with +the following terms and conditions: + +Permission to use, copy, modify, and distribute this software and its +associated documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that both +that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author(s) not be used +in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHORS BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/oletools/thirdparty/OleFileIO_PL/OleFileIO_PL.py b/oletools/thirdparty/OleFileIO_PL/OleFileIO_PL.py new file mode 100644 index 0000000..ba04b01 --- /dev/null +++ b/oletools/thirdparty/OleFileIO_PL/OleFileIO_PL.py @@ -0,0 +1,1674 @@ +#!/usr/local/bin/python +# -*- coding: latin-1 -*- +""" +OleFileIO_PL: + Module to read Microsoft OLE2 files (also called Structured Storage or + Microsoft Compound Document File Format), such as Microsoft Office + documents, Image Composer and FlashPix files, Outlook messages, ... + +version 0.24 2012-09-18 Philippe Lagadec - http://www.decalage.info + +Project website: http://www.decalage.info/python/olefileio + +Improved version of the OleFileIO module from PIL library v1.1.6 +See: http://www.pythonware.com/products/pil/index.htm + +The Python Imaging Library (PIL) is + Copyright (c) 1997-2005 by Secret Labs AB + Copyright (c) 1995-2005 by Fredrik Lundh +OleFileIO_PL changes are Copyright (c) 2005-2012 by Philippe Lagadec + +See source code and LICENSE.txt for information on usage and redistribution. + +WARNING: THIS IS (STILL) WORK IN PROGRESS. +""" + +__author__ = "Fredrik Lundh (Secret Labs AB), Philippe Lagadec" +__date__ = "2012-09-18" +__version__ = '0.24' + +#--- LICENSE ------------------------------------------------------------------ + +# OleFileIO_PL is an improved version of the OleFileIO module from the +# Python Imaging Library (PIL). + +# OleFileIO_PL changes are Copyright (c) 2005-2012 by Philippe Lagadec +# +# The Python Imaging Library (PIL) is +# Copyright (c) 1997-2005 by Secret Labs AB +# Copyright (c) 1995-2005 by Fredrik Lundh +# +# By obtaining, using, and/or copying this software and/or its associated +# documentation, you agree that you have read, understood, and will comply with +# the following terms and conditions: +# +# Permission to use, copy, modify, and distribute this software and its +# associated documentation for any purpose and without fee is hereby granted, +# provided that the above copyright notice appears in all copies, and that both +# that copyright notice and this permission notice appear in supporting +# documentation, and that the name of Secret Labs AB or the author(s) not be used +# in advertising or publicity pertaining to distribution of the software +# without specific, written prior permission. +# +# SECRET LABS AB AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +# IN NO EVENT SHALL SECRET LABS AB OR THE AUTHORS BE LIABLE FOR ANY SPECIAL, +# INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +# PERFORMANCE OF THIS SOFTWARE. + +#----------------------------------------------------------------------------- +# CHANGELOG: (only OleFileIO_PL changes compared to PIL 1.1.6) +# 2005-05-11 v0.10 PL: - a few fixes for Python 2.4 compatibility +# (all changes flagged with [PL]) +# 2006-02-22 v0.11 PL: - a few fixes for some Office 2003 documents which raise +# exceptions in _OleStream.__init__() +# 2006-06-09 v0.12 PL: - fixes for files above 6.8MB (DIFAT in loadfat) +# - added some constants +# - added header values checks +# - added some docstrings +# - getsect: bugfix in case sectors >512 bytes +# - getsect: added conformity checks +# - DEBUG_MODE constant to activate debug display +# 2007-09-04 v0.13 PL: - improved/translated (lots of) comments +# - updated license +# - converted tabs to 4 spaces +# 2007-11-19 v0.14 PL: - added OleFileIO._raise_defect() to adapt sensitivity +# - improved _unicode() to use Python 2.x unicode support +# - fixed bug in _OleDirectoryEntry +# 2007-11-25 v0.15 PL: - added safety checks to detect FAT loops +# - fixed _OleStream which didn't check stream size +# - added/improved many docstrings and comments +# - moved helper functions _unicode and _clsid out of +# OleFileIO class +# - improved OleFileIO._find() to add Unix path syntax +# - OleFileIO._find() is now case-insensitive +# - added get_type() and get_rootentry_name() +# - rewritten loaddirectory and _OleDirectoryEntry +# 2007-11-27 v0.16 PL: - added _OleDirectoryEntry.kids_dict +# - added detection of duplicate filenames in storages +# - added detection of duplicate references to streams +# - added get_size() and exists() to _OleDirectoryEntry +# - added isOleFile to check header before parsing +# - added __all__ list to control public keywords in pydoc +# 2007-12-04 v0.17 PL: - added _load_direntry to fix a bug in loaddirectory +# - improved _unicode(), added workarounds for Python <2.3 +# - added set_debug_mode and -d option to set debug mode +# - fixed bugs in OleFileIO.open and _OleDirectoryEntry +# - added safety check in main for large or binary +# properties +# - allow size>0 for storages for some implementations +# 2007-12-05 v0.18 PL: - fixed several bugs in handling of FAT, MiniFAT and +# streams +# - added option '-c' in main to check all streams +# 2009-12-10 v0.19 PL: - bugfix for 32 bit arrays on 64 bits platforms +# (thanks to Ben G. and Martijn for reporting the bug) +# 2009-12-11 v0.20 PL: - bugfix in OleFileIO.open when filename is not plain str +# 2010-01-22 v0.21 PL: - added support for big-endian CPUs such as PowerPC Macs +# 2012-02-16 v0.22 PL: - fixed bug in getproperties, patch by chuckleberryfinn +# (https://bitbucket.org/decalage/olefileio_pl/issue/7) +# - added close method to OleFileIO (fixed issue #2) +# 2012-07-25 v0.23 PL: - added support for file-like objects (patch by mete0r_kr) + + +#----------------------------------------------------------------------------- +# TODO (for version 1.0): +# + add path attrib to _OleDirEntry, set it once and for all in init or +# append_kids (then listdir/_list can be simplified) +# - TESTS with Linux, MacOSX, Python 1.5.2, various files, PIL, ... +# - add underscore to each private method, to avoid their display in +# pydoc/epydoc documentation - Remove it for classes to be documented +# - replace all raised exceptions with _raise_defect (at least in OleFileIO) +# - merge code from _OleStream and OleFileIO.getsect to read sectors +# (maybe add a class for FAT and MiniFAT ?) +# - add method to check all streams (follow sectors chains without storing all +# stream in memory, and report anomalies) +# - use _OleDirectoryEntry.kids_dict to improve _find and _list ? +# - fix Unicode names handling (find some way to stay compatible with Py1.5.2) +# => if possible avoid converting names to Latin-1 +# - review DIFAT code: fix handling of DIFSECT blocks in FAT (not stop) +# - rewrite OleFileIO.getproperties +# - improve docstrings to show more sample uses +# - see also original notes and FIXME below +# - remove all obsolete FIXMEs + +# IDEAS: +# - allow _raise_defect to raise different exceptions, not only IOError +# - provide a class with named attributes to get well-known properties of +# MS Office documents (title, author, ...) ? +# - in OleFileIO._open and _OleStream, use size=None instead of 0x7FFFFFFF for +# streams with unknown size +# - use arrays of int instead of long integers for FAT/MiniFAT, to improve +# performance and reduce memory usage ? (possible issue with values >2^31) +# - provide tests with unittest (may need write support to create samples) +# - move all debug code (and maybe dump methods) to a separate module, with +# a class which inherits OleFileIO ? +# - fix docstrings to follow epydoc format +# - add support for 4K sectors ? +# - add support for big endian byte order ? +# - create a simple OLE explorer with wxPython + +# FUTURE EVOLUTIONS to add write support: +# 1) add ability to write a stream back on disk from StringIO (same size, no +# change in FAT/MiniFAT). +# 2) rename a stream/storage if it doesn't change the RB tree +# 3) use rbtree module to update the red-black tree + any rename +# 4) remove a stream/storage: free sectors in FAT/MiniFAT +# 5) allocate new sectors in FAT/MiniFAT +# 6) create new storage/stream +#----------------------------------------------------------------------------- + +# +# THIS IS WORK IN PROGRESS +# +# The Python Imaging Library +# $Id: OleFileIO.py 2339 2005-03-25 08:02:17Z fredrik $ +# +# stuff to deal with OLE2 Structured Storage files. this module is +# used by PIL to read Image Composer and FlashPix files, but can also +# be used to read other files of this type. +# +# History: +# 1997-01-20 fl Created +# 1997-01-22 fl Fixed 64-bit portability quirk +# 2003-09-09 fl Fixed typo in OleFileIO.loadfat (noted by Daniel Haertle) +# 2004-02-29 fl Changed long hex constants to signed integers +# +# Notes: +# FIXME: sort out sign problem (eliminate long hex constants) +# FIXME: change filename to use "a/b/c" instead of ["a", "b", "c"] +# FIXME: provide a glob mechanism function (using fnmatchcase) +# +# Literature: +# +# "FlashPix Format Specification, Appendix A", Kodak and Microsoft, +# September 1996. +# +# Quotes: +# +# "If this document and functionality of the Software conflict, +# the actual functionality of the Software represents the correct +# functionality" -- Microsoft, in the OLE format specification +# +# Copyright (c) Secret Labs AB 1997. +# Copyright (c) Fredrik Lundh 1997. +# +# See the README file for information on usage and redistribution. +# + +#------------------------------------------------------------------------------ + +import string, StringIO, struct, array, os.path, sys + +#[PL] Define explicitly the public API to avoid private objects in pydoc: +__all__ = ['OleFileIO', 'isOleFile'] + +#[PL] workaround to fix an issue with array item size on 64 bits systems: +if array.array('L').itemsize == 4: + # on 32 bits platforms, long integers in an array are 32 bits: + UINT32 = 'L' +elif array.array('I').itemsize == 4: + # on 64 bits platforms, integers in an array are 32 bits: + UINT32 = 'I' +else: + raise ValueError, 'Need to fix a bug with 32 bit arrays, please contact author...' + + +#[PL] These workarounds were inspired from the Path module +# (see http://www.jorendorff.com/articles/python/path/) +#TODO: test with old Python versions + +# Pre-2.3 workaround for booleans +try: + True, False +except NameError: + True, False = 1, 0 + +# Pre-2.3 workaround for basestring. +try: + basestring +except NameError: + try: + # is Unicode supported (Python >2.0 or >1.6 ?) + basestring = (str, unicode) + except NameError: + basestring = str + +#[PL] Experimental setting: if True, OLE filenames will be kept in Unicode +# if False (default PIL behaviour), all filenames are converted to Latin-1. +KEEP_UNICODE_NAMES = False + +#[PL] DEBUG display mode: False by default, use set_debug_mode() or "-d" on +# command line to change it. +DEBUG_MODE = False +def debug_print(msg): + print msg +def debug_pass(msg): + pass +debug = debug_pass + +def set_debug_mode(debug_mode): + """ + Set debug mode on or off, to control display of debugging messages. + mode: True or False + """ + global DEBUG_MODE, debug + DEBUG_MODE = debug_mode + if debug_mode: + debug = debug_print + else: + debug = debug_pass + +#TODO: convert this to hex +MAGIC = '\320\317\021\340\241\261\032\341' + +#[PL]: added constants for Sector IDs (from AAF specifications) +MAXREGSECT = 0xFFFFFFFAL; # maximum SECT +DIFSECT = 0xFFFFFFFCL; # (-4) denotes a DIFAT sector in a FAT +FATSECT = 0xFFFFFFFDL; # (-3) denotes a FAT sector in a FAT +ENDOFCHAIN = 0xFFFFFFFEL; # (-2) end of a virtual stream chain +FREESECT = 0xFFFFFFFFL; # (-1) unallocated sector + +#[PL]: added constants for Directory Entry IDs (from AAF specifications) +MAXREGSID = 0xFFFFFFFAL; # maximum directory entry ID +NOSTREAM = 0xFFFFFFFFL; # (-1) unallocated directory entry + +#[PL] object types in storage (from AAF specifications) +STGTY_EMPTY = 0 # empty directory entry (according to OpenOffice.org doc) +STGTY_STORAGE = 1 # element is a storage object +STGTY_STREAM = 2 # element is a stream object +STGTY_LOCKBYTES = 3 # element is an ILockBytes object +STGTY_PROPERTY = 4 # element is an IPropertyStorage object +STGTY_ROOT = 5 # element is a root storage + + +# +# -------------------------------------------------------------------- +# property types + +VT_EMPTY=0; VT_NULL=1; VT_I2=2; VT_I4=3; VT_R4=4; VT_R8=5; VT_CY=6; +VT_DATE=7; VT_BSTR=8; VT_DISPATCH=9; VT_ERROR=10; VT_BOOL=11; +VT_VARIANT=12; VT_UNKNOWN=13; VT_DECIMAL=14; VT_I1=16; VT_UI1=17; +VT_UI2=18; VT_UI4=19; VT_I8=20; VT_UI8=21; VT_INT=22; VT_UINT=23; +VT_VOID=24; VT_HRESULT=25; VT_PTR=26; VT_SAFEARRAY=27; VT_CARRAY=28; +VT_USERDEFINED=29; VT_LPSTR=30; VT_LPWSTR=31; VT_FILETIME=64; +VT_BLOB=65; VT_STREAM=66; VT_STORAGE=67; VT_STREAMED_OBJECT=68; +VT_STORED_OBJECT=69; VT_BLOB_OBJECT=70; VT_CF=71; VT_CLSID=72; +VT_VECTOR=0x1000; + +# map property id to name (for debugging purposes) + +VT = {} +for keyword, var in vars().items(): + if keyword[:3] == "VT_": + VT[var] = keyword + +# +# -------------------------------------------------------------------- +# Some common document types (root.clsid fields) + +WORD_CLSID = "00020900-0000-0000-C000-000000000046" +#TODO: check Excel, PPT, ... + +#[PL]: Defect levels to classify parsing errors - see OleFileIO._raise_defect() +DEFECT_UNSURE = 10 # a case which looks weird, but not sure it's a defect +DEFECT_POTENTIAL = 20 # a potential defect +DEFECT_INCORRECT = 30 # an error according to specifications, but parsing + # can go on +DEFECT_FATAL = 40 # an error which cannot be ignored, parsing is + # impossible + +#[PL] add useful constants to __all__: +for key in vars().keys(): + if key.startswith('STGTY_') or key.startswith('DEFECT_'): + __all__.append(key) + + +#--- FUNCTIONS ---------------------------------------------------------------- + +def isOleFile (filename): + """ + Test if file is an OLE container (according to its header). + filename: file name or path (str, unicode) + return: True if OLE, False otherwise. + """ + f = open(filename, 'rb') + header = f.read(len(MAGIC)) + if header == MAGIC: + return True + else: + return False + + +#TODO: replace i16 and i32 with more readable struct.unpack equivalent +def i16(c, o = 0): + """ + Converts a 2-bytes (16 bits) string to an integer. + + c: string containing bytes to convert + o: offset of bytes to convert in string + """ + return ord(c[o])+(ord(c[o+1])<<8) + + +def i32(c, o = 0): + """ + Converts a 4-bytes (32 bits) string to an integer. + + c: string containing bytes to convert + o: offset of bytes to convert in string + """ + return int(ord(c[o])+(ord(c[o+1])<<8)+(ord(c[o+2])<<16)+(ord(c[o+3])<<24)) + # [PL]: added int() because "<<" gives long int since Python 2.4 + + +def _clsid(clsid): + """ + Converts a CLSID to a human-readable string. + clsid: string of length 16. + """ + assert len(clsid) == 16 + if clsid == "\0" * len(clsid): + return "" + return (("%08X-%04X-%04X-%02X%02X-" + "%02X" * 6) % + ((i32(clsid, 0), i16(clsid, 4), i16(clsid, 6)) + + tuple(map(ord, clsid[8:16])))) + + + +# UNICODE support for Old Python versions: +# (necessary to handle storages/streams names which use Unicode) + +try: + # is Unicode supported ? + unicode + + def _unicode(s, errors='replace'): + """ + Map unicode string to Latin 1. (Python with Unicode support) + + s: UTF-16LE unicode string to convert to Latin-1 + errors: 'replace', 'ignore' or 'strict'. See Python doc for unicode() + """ + #TODO: test if it OleFileIO works with Unicode strings, instead of + # converting to Latin-1. + try: + # First the string is converted to plain Unicode: + # (assuming it is encoded as UTF-16 little-endian) + u = s.decode('UTF-16LE', errors) + if KEEP_UNICODE_NAMES: + return u + else: + # Second the unicode string is converted to Latin-1 + return u.encode('latin_1', errors) + except: + # there was an error during Unicode to Latin-1 conversion: + raise IOError, 'incorrect Unicode name' + +except NameError: + def _unicode(s, errors='replace'): + """ + Map unicode string to Latin 1. (Python without native Unicode support) + + s: UTF-16LE unicode string to convert to Latin-1 + errors: 'replace', 'ignore' or 'strict'. (ignored in this version) + """ + # If the unicode function does not exist, we assume this is an old + # Python version without Unicode support. + # Null bytes are simply removed (this only works with usual Latin-1 + # strings which do not contain unicode characters>256): + return filter(ord, s) + + + + +#=== CLASSES ================================================================== + +#--- _OleStream --------------------------------------------------------------- + +class _OleStream(StringIO.StringIO): + """ + OLE2 Stream + + Returns a read-only file object which can be used to read + the contents of a OLE stream (instance of the StringIO class). + To open a stream, use the openstream method in the OleFile class. + + This function can be used with either ordinary streams, + or ministreams, depending on the offset, sectorsize, and + fat table arguments. + + Attributes: + - size: actual size of data stream, after it was opened. + """ + + # FIXME: should store the list of sects obtained by following + # the fat chain, and load new sectors on demand instead of + # loading it all in one go. + + def __init__(self, fp, sect, size, offset, sectorsize, fat, filesize): + """ + Constructor for _OleStream class. + + fp : file object, the OLE container or the MiniFAT stream + sect : sector index of first sector in the stream + size : total size of the stream + offset : offset in bytes for the first FAT or MiniFAT sector + sectorsize: size of one sector + fat : array/list of sector indexes (FAT or MiniFAT) + filesize : size of OLE file (for debugging) + return : a StringIO instance containing the OLE stream + """ + debug('_OleStream.__init__:') + debug(' sect=%d (%X), size=%d, offset=%d, sectorsize=%d, len(fat)=%d, fp=%s' + %(sect,sect,size,offset,sectorsize,len(fat), repr(fp))) + #[PL] To detect malformed documents with FAT loops, we compute the + # expected number of sectors in the stream: + unknown_size = False + if size==0x7FFFFFFF: + # this is the case when called from OleFileIO._open(), and stream + # size is not known in advance (for example when reading the + # Directory stream). Then we can only guess maximum size: + size = len(fat)*sectorsize + # and we keep a record that size was unknown: + unknown_size = True + debug(' stream with UNKNOWN SIZE') + nb_sectors = (size + (sectorsize-1)) / sectorsize + debug('nb_sectors = %d' % nb_sectors) + # This number should (at least) be less than the total number of + # sectors in the given FAT: + if nb_sectors > len(fat): + raise IOError, 'malformed OLE document, stream too large' + # optimization(?): data is first a list of strings, and join() is called + # at the end to concatenate all in one string. + # (this may not be really useful with recent Python versions) + data = [] + # if size is zero, then first sector index should be ENDOFCHAIN: + if size == 0 and sect != ENDOFCHAIN: + debug('size == 0 and sect != ENDOFCHAIN:') + raise IOError, 'incorrect OLE sector index for empty stream' + #[PL] A fixed-length for loop is used instead of an undefined while + # loop to avoid DoS attacks: + for i in xrange(nb_sectors): + # Sector index may be ENDOFCHAIN, but only if size was unknown + if sect == ENDOFCHAIN: + if unknown_size: + break + else: + # else this means that the stream is smaller than declared: + debug('sect=ENDOFCHAIN before expected size') + raise IOError, 'incomplete OLE stream' + # sector index should be within FAT: + if sect<0 or sect>=len(fat): + debug('sect=%d (%X) / len(fat)=%d' % (sect, sect, len(fat))) + debug('i=%d / nb_sectors=%d' %(i, nb_sectors)) +## tmp_data = string.join(data, "") +## f = open('test_debug.bin', 'wb') +## f.write(tmp_data) +## f.close() +## debug('data read so far: %d bytes' % len(tmp_data)) + raise IOError, 'incorrect OLE FAT, sector index out of range' + #TODO: merge this code with OleFileIO.getsect() ? + #TODO: check if this works with 4K sectors: + try: + fp.seek(offset + sectorsize * sect) + except: + debug('sect=%d, seek=%d, filesize=%d' % + (sect, offset+sectorsize*sect, filesize)) + raise IOError, 'OLE sector index out of range' + sector_data = fp.read(sectorsize) + # [PL] check if there was enough data: + # Note: if sector is the last of the file, sometimes it is not a + # complete sector (of 512 or 4K), so we may read less than + # sectorsize. + if len(sector_data)!=sectorsize and sect!=(len(fat)-1): + debug('sect=%d / len(fat)=%d, seek=%d / filesize=%d, len read=%d' % + (sect, len(fat), offset+sectorsize*sect, filesize, len(sector_data))) + debug('seek+len(read)=%d' % (offset+sectorsize*sect+len(sector_data))) + raise IOError, 'incomplete OLE sector' + data.append(sector_data) + # jump to next sector in the FAT: + try: + sect = fat[sect] + except IndexError: + # [PL] if pointer is out of the FAT an exception is raised + raise IOError, 'incorrect OLE FAT, sector index out of range' + #[PL] Last sector should be a "end of chain" marker: + if sect != ENDOFCHAIN: + raise IOError, 'incorrect last sector index in OLE stream' + data = string.join(data, "") + # Data is truncated to the actual stream size: + if len(data) >= size: + data = data[:size] + # actual stream size is stored for future use: + self.size = size + elif unknown_size: + # actual stream size was not known, now we know the size of read + # data: + self.size = len(data) + else: + # read data is less than expected: + debug('len(data)=%d, size=%d' % (len(data), size)) + raise IOError, 'OLE stream size is less than declared' + # when all data is read in memory, StringIO constructor is called + StringIO.StringIO.__init__(self, data) + # Then the _OleStream object can be used as a read-only file object. + + +#--- _OleDirectoryEntry ------------------------------------------------------- + +class _OleDirectoryEntry: + + """ + OLE2 Directory Entry + """ + #[PL] parsing code moved from OleFileIO.loaddirectory + + # struct to parse directory entries: + # <: little-endian byte order + # 64s: string containing entry name in unicode (max 31 chars) + null char + # H: uint16, number of bytes used in name buffer, including null = (len+1)*2 + # B: uint8, dir entry type (between 0 and 5) + # B: uint8, color: 0=black, 1=red + # I: uint32, index of left child node in the red-black tree, NOSTREAM if none + # I: uint32, index of right child node in the red-black tree, NOSTREAM if none + # I: uint32, index of child root node if it is a storage, else NOSTREAM + # 16s: CLSID, unique identifier (only used if it is a storage) + # I: uint32, user flags + # 8s: uint64, creation timestamp or zero + # 8s: uint64, modification timestamp or zero + # I: uint32, SID of first sector if stream or ministream, SID of 1st sector + # of stream containing ministreams if root entry, 0 otherwise + # I: uint32, total stream size in bytes if stream (low 32 bits), 0 otherwise + # I: uint32, total stream size in bytes if stream (high 32 bits), 0 otherwise + STRUCT_DIRENTRY = '<64sHBBIII16sI8s8sIII' + # size of a directory entry: 128 bytes + DIRENTRY_SIZE = 128 + assert struct.calcsize(STRUCT_DIRENTRY) == DIRENTRY_SIZE + + + def __init__(self, entry, sid, olefile): + """ + Constructor for an _OleDirectoryEntry object. + Parses a 128-bytes entry from the OLE Directory stream. + + entry : string (must be 128 bytes long) + sid : index of this directory entry in the OLE file directory + olefile: OleFileIO containing this directory entry + """ + self.sid = sid + # ref to olefile is stored for future use + self.olefile = olefile + # kids is a list of children entries, if this entry is a storage: + # (list of _OleDirectoryEntry objects) + self.kids = [] + # kids_dict is a dictionary of children entries, indexed by their + # name in lowercase: used to quickly find an entry, and to detect + # duplicates + self.kids_dict = {} + # flag used to detect if the entry is referenced more than once in + # directory: + self.used = False + # decode DirEntry + ( + name, + namelength, + self.entry_type, + self.color, + self.sid_left, + self.sid_right, + self.sid_child, + clsid, + self.dwUserFlags, + self.createTime, + self.modifyTime, + self.isectStart, + sizeLow, + sizeHigh + ) = struct.unpack(_OleDirectoryEntry.STRUCT_DIRENTRY, entry) + if self.entry_type not in [STGTY_ROOT, STGTY_STORAGE, STGTY_STREAM, STGTY_EMPTY]: + olefile._raise_defect(DEFECT_INCORRECT, 'unhandled OLE storage type') + # only first directory entry can (and should) be root: + if self.entry_type == STGTY_ROOT and sid != 0: + olefile._raise_defect(DEFECT_INCORRECT, 'duplicate OLE root entry') + if sid == 0 and self.entry_type != STGTY_ROOT: + olefile._raise_defect(DEFECT_INCORRECT, 'incorrect OLE root entry') + #debug (struct.unpack(fmt_entry, entry[:len_entry])) + # name should be at most 31 unicode characters + null character, + # so 64 bytes in total (31*2 + 2): + if namelength>64: + olefile._raise_defect(DEFECT_INCORRECT, 'incorrect DirEntry name length') + # if exception not raised, namelength is set to the maximum value: + namelength = 64 + # only characters without ending null char are kept: + name = name[:(namelength-2)] + # name is converted from unicode to Latin-1: + self.name = _unicode(name) + + debug('DirEntry SID=%d: %s' % (self.sid, repr(self.name))) + debug(' - type: %d' % self.entry_type) + debug(' - sect: %d' % self.isectStart) + debug(' - SID left: %d, right: %d, child: %d' % (self.sid_left, + self.sid_right, self.sid_child)) + + # sizeHigh is only used for 4K sectors, it should be zero for 512 bytes + # sectors, BUT apparently some implementations set it as 0xFFFFFFFFL, 1 + # or some other value so it cannot be raised as a defect in general: + if olefile.sectorsize == 512: + if sizeHigh != 0 and sizeHigh != 0xFFFFFFFFL: + debug('sectorsize=%d, sizeLow=%d, sizeHigh=%d (%X)' % + (olefile.sectorsize, sizeLow, sizeHigh, sizeHigh)) + olefile._raise_defect(DEFECT_UNSURE, 'incorrect OLE stream size') + self.size = sizeLow + else: + self.size = sizeLow + (long(sizeHigh)<<32) + debug(' - size: %d (sizeLow=%d, sizeHigh=%d)' % (self.size, sizeLow, sizeHigh)) + + self.clsid = _clsid(clsid) + # a storage should have a null size, BUT some implementations such as + # Word 8 for Mac seem to allow non-null values => Potential defect: + if self.entry_type == STGTY_STORAGE and self.size != 0: + olefile._raise_defect(DEFECT_POTENTIAL, 'OLE storage with size>0') + # check if stream is not already referenced elsewhere: + if self.entry_type in (STGTY_ROOT, STGTY_STREAM) and self.size>0: + if self.size < olefile.minisectorcutoff \ + and self.entry_type==STGTY_STREAM: # only streams can be in MiniFAT + # ministream object + minifat = True + else: + minifat = False + olefile._check_duplicate_stream(self.isectStart, minifat) + + + + def build_storage_tree(self): + """ + Read and build the red-black tree attached to this _OleDirectoryEntry + object, if it is a storage. + Note that this method builds a tree of all subentries, so it should + only be called for the root object once. + """ + debug('build_storage_tree: SID=%d - %s - sid_child=%d' + % (self.sid, repr(self.name), self.sid_child)) + if self.sid_child != NOSTREAM: + # if child SID is not NOSTREAM, then this entry is a storage. + # Let's walk through the tree of children to fill the kids list: + self.append_kids(self.sid_child) + + # Note from OpenOffice documentation: the safest way is to + # recreate the tree because some implementations may store broken + # red-black trees... + + # in the OLE file, entries are sorted on (length, name). + # for convenience, we sort them on name instead: + # (see __cmp__ method in this class) + self.kids.sort() + + + def append_kids(self, child_sid): + """ + Walk through red-black tree of children of this directory entry to add + all of them to the kids list. (recursive method) + + child_sid : index of child directory entry to use, or None when called + first time for the root. (only used during recursion) + """ + #[PL] this method was added to use simple recursion instead of a complex + # algorithm. + # if this is not a storage or a leaf of the tree, nothing to do: + if child_sid == NOSTREAM: + return + # check if child SID is in the proper range: + if child_sid<0 or child_sid>=len(self.olefile.direntries): + self.olefile._raise_defect(DEFECT_FATAL, 'OLE DirEntry index out of range') + # get child direntry: + child = self.olefile._load_direntry(child_sid) #direntries[child_sid] + debug('append_kids: child_sid=%d - %s - sid_left=%d, sid_right=%d, sid_child=%d' + % (child.sid, repr(child.name), child.sid_left, child.sid_right, child.sid_child)) + # the directory entries are organized as a red-black tree. + # (cf. Wikipedia for details) + # First walk through left side of the tree: + self.append_kids(child.sid_left) + # Check if its name is not already used (case-insensitive): + name_lower = child.name.lower() + if self.kids_dict.has_key(name_lower): + self.olefile._raise_defect(DEFECT_INCORRECT, + "Duplicate filename in OLE storage") + # Then the child_sid _OleDirectoryEntry object is appended to the + # kids list and dictionary: + self.kids.append(child) + self.kids_dict[name_lower] = child + # Check if kid was not already referenced in a storage: + if child.used: + self.olefile._raise_defect(DEFECT_INCORRECT, + 'OLE Entry referenced more than once') + child.used = True + # Finally walk through right side of the tree: + self.append_kids(child.sid_right) + # Afterwards build kid's own tree if it's also a storage: + child.build_storage_tree() + + + def __cmp__(self, other): + "Compare entries by name" + return cmp(self.name, other.name) + #TODO: replace by the same function as MS implementation ? + # (order by name length first, then case-insensitive order) + + + def dump(self, tab = 0): + "Dump this entry, and all its subentries (for debug purposes only)" + TYPES = ["(invalid)", "(storage)", "(stream)", "(lockbytes)", + "(property)", "(root)"] + print " "*tab + repr(self.name), TYPES[self.entry_type], + if self.entry_type in (STGTY_STREAM, STGTY_ROOT): + print self.size, "bytes", + print + if self.entry_type in (STGTY_STORAGE, STGTY_ROOT) and self.clsid: + print " "*tab + "{%s}" % self.clsid + + for kid in self.kids: + kid.dump(tab + 2) + + +#--- OleFileIO ---------------------------------------------------------------- + +class OleFileIO: + """ + OLE container object + + This class encapsulates the interface to an OLE 2 structured + storage file. Use the {@link listdir} and {@link openstream} methods to + access the contents of this file. + + Object names are given as a list of strings, one for each subentry + level. The root entry should be omitted. For example, the following + code extracts all image streams from a Microsoft Image Composer file: + + ole = OleFileIO("fan.mic") + + for entry in ole.listdir(): + if entry[1:2] == "Image": + fin = ole.openstream(entry) + fout = open(entry[0:1], "wb") + while 1: + s = fin.read(8192) + if not s: + break + fout.write(s) + + You can use the viewer application provided with the Python Imaging + Library to view the resulting files (which happens to be standard + TIFF files). + """ + + def __init__(self, filename = None, raise_defects=DEFECT_FATAL): + """ + Constructor for OleFileIO class. + + filename: file to open. + raise_defects: minimal level for defects to be raised as exceptions. + (use DEFECT_FATAL for a typical application, DEFECT_INCORRECT for a + security-oriented application, see source code for details) + """ + self._raise_defects_level = raise_defects + if filename: + self.open(filename) + + + def _raise_defect(self, defect_level, message): + """ + This method should be called for any defect found during file parsing. + It may raise an IOError exception according to the minimal level chosen + for the OleFileIO object. + + defect_level: defect level, possible values are: + DEFECT_UNSURE : a case which looks weird, but not sure it's a defect + DEFECT_POTENTIAL : a potential defect + DEFECT_INCORRECT : an error according to specifications, but parsing can go on + DEFECT_FATAL : an error which cannot be ignored, parsing is impossible + message: string describing the defect, used with raised exception. + """ + # added by [PL] + if defect_level >= self._raise_defects_level: + raise IOError, message + + + def open(self, filename): + """ + Open an OLE2 file. + Reads the header, FAT and directory. + + filename: string-like or file-like object + """ + #[PL] check if filename is a string-like or file-like object: + # (it is better to check for a read() method) + if hasattr(filename, 'read'): + # file-like object + self.fp = filename + else: + # string-like object: filename of file on disk + #TODO: if larger than 1024 bytes, this could be the actual data => StringIO + self.fp = open(filename, "rb") + # old code fails if filename is not a plain string: + #if type(filename) == type(""): + # self.fp = open(filename, "rb") + #else: + # self.fp = filename + # obtain the filesize by using seek and tell, which should work on most + # file-like objects: + #TODO: do it above, using getsize with filename when possible? + #TODO: fix code to fail with clear exception when filesize cannot be obtained + self.fp.seek(0, os.SEEK_END) + try: + filesize = self.fp.tell() + finally: + self.fp.seek(0) + self._filesize = filesize + + # lists of streams in FAT and MiniFAT, to detect duplicate references + # (list of indexes of first sectors of each stream) + self._used_streams_fat = [] + self._used_streams_minifat = [] + + header = self.fp.read(512) + + if len(header) != 512 or header[:8] != MAGIC: + self._raise_defect(DEFECT_FATAL, "not an OLE2 structured storage file") + + # [PL] header structure according to AAF specifications: + ##Header + ##struct StructuredStorageHeader { // [offset from start (bytes), length (bytes)] + ##BYTE _abSig[8]; // [00H,08] {0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, + ## // 0x1a, 0xe1} for current version + ##CLSID _clsid; // [08H,16] reserved must be zero (WriteClassStg/ + ## // GetClassFile uses root directory class id) + ##USHORT _uMinorVersion; // [18H,02] minor version of the format: 33 is + ## // written by reference implementation + ##USHORT _uDllVersion; // [1AH,02] major version of the dll/format: 3 for + ## // 512-byte sectors, 4 for 4 KB sectors + ##USHORT _uByteOrder; // [1CH,02] 0xFFFE: indicates Intel byte-ordering + ##USHORT _uSectorShift; // [1EH,02] size of sectors in power-of-two; + ## // typically 9 indicating 512-byte sectors + ##USHORT _uMiniSectorShift; // [20H,02] size of mini-sectors in power-of-two; + ## // typically 6 indicating 64-byte mini-sectors + ##USHORT _usReserved; // [22H,02] reserved, must be zero + ##ULONG _ulReserved1; // [24H,04] reserved, must be zero + ##FSINDEX _csectDir; // [28H,04] must be zero for 512-byte sectors, + ## // number of SECTs in directory chain for 4 KB + ## // sectors + ##FSINDEX _csectFat; // [2CH,04] number of SECTs in the FAT chain + ##SECT _sectDirStart; // [30H,04] first SECT in the directory chain + ##DFSIGNATURE _signature; // [34H,04] signature used for transactions; must + ## // be zero. The reference implementation + ## // does not support transactions + ##ULONG _ulMiniSectorCutoff; // [38H,04] maximum size for a mini stream; + ## // typically 4096 bytes + ##SECT _sectMiniFatStart; // [3CH,04] first SECT in the MiniFAT chain + ##FSINDEX _csectMiniFat; // [40H,04] number of SECTs in the MiniFAT chain + ##SECT _sectDifStart; // [44H,04] first SECT in the DIFAT chain + ##FSINDEX _csectDif; // [48H,04] number of SECTs in the DIFAT chain + ##SECT _sectFat[109]; // [4CH,436] the SECTs of first 109 FAT sectors + ##}; + + # [PL] header decoding: + # '<' indicates little-endian byte ordering for Intel (cf. struct module help) + fmt_header = '<8s16sHHHHHHLLLLLLLLLL' + header_size = struct.calcsize(fmt_header) + debug( "fmt_header size = %d, +FAT = %d" % (header_size, header_size + 109*4) ) + header1 = header[:header_size] + ( + self.Sig, + self.clsid, + self.MinorVersion, + self.DllVersion, + self.ByteOrder, + self.SectorShift, + self.MiniSectorShift, + self.Reserved, self.Reserved1, + self.csectDir, + self.csectFat, + self.sectDirStart, + self.signature, + self.MiniSectorCutoff, + self.MiniFatStart, + self.csectMiniFat, + self.sectDifStart, + self.csectDif + ) = struct.unpack(fmt_header, header1) + debug( struct.unpack(fmt_header, header1)) + + if self.Sig != '\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1': + # OLE signature should always be present + self._raise_defect(DEFECT_FATAL, "incorrect OLE signature") + if self.clsid != '\x00'*16: + # according to AAF specs, CLSID should always be zero + self._raise_defect(DEFECT_INCORRECT, "incorrect CLSID in OLE header") + debug( "MinorVersion = %d" % self.MinorVersion ) + debug( "DllVersion = %d" % self.DllVersion ) + if self.DllVersion not in [3, 4]: + # version 3: usual format, 512 bytes per sector + # version 4: large format, 4K per sector + self._raise_defect(DEFECT_INCORRECT, "incorrect DllVersion in OLE header") + debug( "ByteOrder = %X" % self.ByteOrder ) + if self.ByteOrder != 0xFFFE: + # For now only common little-endian documents are handled correctly + self._raise_defect(DEFECT_FATAL, "incorrect ByteOrder in OLE header") + # TODO: add big-endian support for documents created on Mac ? + self.SectorSize = 2**self.SectorShift + debug( "SectorSize = %d" % self.SectorSize ) + if self.SectorSize not in [512, 4096]: + self._raise_defect(DEFECT_INCORRECT, "incorrect SectorSize in OLE header") + if (self.DllVersion==3 and self.SectorSize!=512) \ + or (self.DllVersion==4 and self.SectorSize!=4096): + self._raise_defect(DEFECT_INCORRECT, "SectorSize does not match DllVersion in OLE header") + self.MiniSectorSize = 2**self.MiniSectorShift + debug( "MiniSectorSize = %d" % self.MiniSectorSize ) + if self.MiniSectorSize not in [64]: + self._raise_defect(DEFECT_INCORRECT, "incorrect MiniSectorSize in OLE header") + if self.Reserved != 0 or self.Reserved1 != 0: + self._raise_defect(DEFECT_INCORRECT, "incorrect OLE header (non-null reserved bytes)") + debug( "csectDir = %d" % self.csectDir ) + if self.SectorSize==512 and self.csectDir!=0: + self._raise_defect(DEFECT_INCORRECT, "incorrect csectDir in OLE header") + debug( "csectFat = %d" % self.csectFat ) + debug( "sectDirStart = %X" % self.sectDirStart ) + debug( "signature = %d" % self.signature ) + # Signature should be zero, BUT some implementations do not follow this + # rule => only a potential defect: + if self.signature != 0: + self._raise_defect(DEFECT_POTENTIAL, "incorrect OLE header (signature>0)") + debug( "MiniSectorCutoff = %d" % self.MiniSectorCutoff ) + debug( "MiniFatStart = %X" % self.MiniFatStart ) + debug( "csectMiniFat = %d" % self.csectMiniFat ) + debug( "sectDifStart = %X" % self.sectDifStart ) + debug( "csectDif = %d" % self.csectDif ) + + # calculate the number of sectors in the file + # (-1 because header doesn't count) + self.nb_sect = ( (filesize + self.SectorSize-1) / self.SectorSize) - 1 + debug( "Number of sectors in the file: %d" % self.nb_sect ) + + # file clsid (probably never used, so we don't store it) + clsid = _clsid(header[8:24]) + self.sectorsize = self.SectorSize #1 << i16(header, 30) + self.minisectorsize = self.MiniSectorSize #1 << i16(header, 32) + self.minisectorcutoff = self.MiniSectorCutoff # i32(header, 56) + + # check known streams for duplicate references (these are always in FAT, + # never in MiniFAT): + self._check_duplicate_stream(self.sectDirStart) + # check MiniFAT only if it is not empty: + if self.csectMiniFat: + self._check_duplicate_stream(self.MiniFatStart) + # check DIFAT only if it is not empty: + if self.csectDif: + self._check_duplicate_stream(self.sectDifStart) + + # Load file allocation tables + self.loadfat(header) + # Load direcory. This sets both the direntries list (ordered by sid) + # and the root (ordered by hierarchy) members. + self.loaddirectory(self.sectDirStart)#i32(header, 48)) + self.ministream = None + self.minifatsect = self.MiniFatStart #i32(header, 60) + + + def close(self): + """ + close the OLE file, to release the file object + """ + self.fp.close() + + + def _check_duplicate_stream(self, first_sect, minifat=False): + """ + Checks if a stream has not been already referenced elsewhere. + This method should only be called once for each known stream, and only + if stream size is not null. + first_sect: index of first sector of the stream in FAT + minifat: if True, stream is located in the MiniFAT, else in the FAT + """ + if minifat: + debug('_check_duplicate_stream: sect=%d in MiniFAT' % first_sect) + used_streams = self._used_streams_minifat + else: + debug('_check_duplicate_stream: sect=%d in FAT' % first_sect) + # some values can be safely ignored (not a real stream): + if first_sect in (DIFSECT,FATSECT,ENDOFCHAIN,FREESECT): + return + used_streams = self._used_streams_fat + #TODO: would it be more efficient using a dict or hash values, instead + # of a list of long ? + if first_sect in used_streams: + self._raise_defect(DEFECT_INCORRECT, 'Stream referenced twice') + else: + used_streams.append(first_sect) + + + def dumpfat(self, fat, firstindex=0): + "Displays a part of FAT in human-readable form for debugging purpose" + # [PL] added only for debug + if not DEBUG_MODE: + return + # dictionary to convert special FAT values in human-readable strings + VPL=8 # valeurs par ligne (8+1 * 8+1 = 81) + fatnames = { + FREESECT: "..free..", + ENDOFCHAIN: "[ END. ]", + FATSECT: "FATSECT ", + DIFSECT: "DIFSECT " + } + nbsect = len(fat) + nlines = (nbsect+VPL-1)/VPL + print "index", + for i in range(VPL): + print ("%8X" % i), + print "" + for l in range(nlines): + index = l*VPL + print ("%8X:" % (firstindex+index)), + for i in range(index, index+VPL): + if i>=nbsect: + break + sect = fat[i] + if sect in fatnames: + nom = fatnames[sect] + else: + if sect == i+1: + nom = " --->" + else: + nom = "%8X" % sect + print nom, + print "" + + + def dumpsect(self, sector, firstindex=0): + "Displays a sector in a human-readable form, for debugging purpose." + if not DEBUG_MODE: + return + VPL=8 # number of values per line (8+1 * 8+1 = 81) + tab = array.array(UINT32, sector) + nbsect = len(tab) + nlines = (nbsect+VPL-1)/VPL + print "index", + for i in range(VPL): + print ("%8X" % i), + print "" + for l in range(nlines): + index = l*VPL + print ("%8X:" % (firstindex+index)), + for i in range(index, index+VPL): + if i>=nbsect: + break + sect = tab[i] + nom = "%8X" % sect + print nom, + print "" + + def sect2array(self, sect): + """ + convert a sector to an array of 32 bits unsigned integers, + swapping bytes on big endian CPUs such as PowerPC (old Macs) + """ + a = array.array(UINT32, sect) + # if CPU is big endian, swap bytes: + if sys.byteorder == 'big': + a.byteswap() + return a + + + def loadfat_sect(self, sect): + """ + Adds the indexes of the given sector to the FAT + sect: string containing the first FAT sector, or array of long integers + return: index of last FAT sector. + """ + # a FAT sector is an array of ulong integers. + if isinstance(sect, array.array): + # if sect is already an array it is directly used + fat1 = sect + else: + # if it's a raw sector, it is parsed in an array + fat1 = self.sect2array(sect) + self.dumpsect(sect) + # The FAT is a sector chain starting at the first index of itself. + for isect in fat1: + #print "isect = %X" % isect + if isect == ENDOFCHAIN or isect == FREESECT: + # the end of the sector chain has been reached + break + # read the FAT sector + s = self.getsect(isect) + # parse it as an array of 32 bits integers, and add it to the + # global FAT array + nextfat = self.sect2array(s) + self.fat = self.fat + nextfat + return isect + + + def loadfat(self, header): + """ + Load the FAT table. + """ + # The header contains a sector numbers + # for the first 109 FAT sectors. Additional sectors are + # described by DIF blocks + + sect = header[76:512] + debug( "len(sect)=%d, so %d integers" % (len(sect), len(sect)/4) ) + #fat = [] + # [PL] FAT is an array of 32 bits unsigned ints, it's more effective + # to use an array than a list in Python. + # It's initialized as empty first: + self.fat = array.array(UINT32) + self.loadfat_sect(sect) + #self.dumpfat(self.fat) +## for i in range(0, len(sect), 4): +## ix = i32(sect, i) +## #[PL] if ix == -2 or ix == -1: # ix == 0xFFFFFFFEL or ix == 0xFFFFFFFFL: +## if ix == 0xFFFFFFFEL or ix == 0xFFFFFFFFL: +## break +## s = self.getsect(ix) +## #fat = fat + map(lambda i, s=s: i32(s, i), range(0, len(s), 4)) +## fat = fat + array.array(UINT32, s) + if self.csectDif != 0: + # [PL] There's a DIFAT because file is larger than 6.8MB + # some checks just in case: + if self.csectFat <= 109: + # there must be at least 109 blocks in header and the rest in + # DIFAT, so number of sectors must be >109. + self._raise_defect(DEFECT_INCORRECT, 'incorrect DIFAT, not enough sectors') + if self.sectDifStart >= self.nb_sect: + # initial DIFAT block index must be valid + self._raise_defect(DEFECT_FATAL, 'incorrect DIFAT, first index out of range') + debug( "DIFAT analysis..." ) + # We compute the necessary number of DIFAT sectors : + # (each DIFAT sector = 127 pointers + 1 towards next DIFAT sector) + nb_difat = (self.csectFat-109 + 126)/127 + debug( "nb_difat = %d" % nb_difat ) + if self.csectDif != nb_difat: + raise IOError, 'incorrect DIFAT' + isect_difat = self.sectDifStart + for i in xrange(nb_difat): + debug( "DIFAT block %d, sector %X" % (i, isect_difat) ) + #TODO: check if corresponding FAT SID = DIFSECT + sector_difat = self.getsect(isect_difat) + difat = self.sect2array(sector_difat) + self.dumpsect(sector_difat) + self.loadfat_sect(difat[:127]) + # last DIFAT pointer is next DIFAT sector: + isect_difat = difat[127] + debug( "next DIFAT sector: %X" % isect_difat ) + # checks: + if isect_difat not in [ENDOFCHAIN, FREESECT]: + # last DIFAT pointer value must be ENDOFCHAIN or FREESECT + raise IOError, 'incorrect end of DIFAT' +## if len(self.fat) != self.csectFat: +## # FAT should contain csectFat blocks +## print "FAT length: %d instead of %d" % (len(self.fat), self.csectFat) +## raise IOError, 'incorrect DIFAT' + # since FAT is read from fixed-size sectors, it may contain more values + # than the actual number of sectors in the file. + # Keep only the relevant sector indexes: + if len(self.fat) > self.nb_sect: + debug('len(fat)=%d, shrunk to nb_sect=%d' % (len(self.fat), self.nb_sect)) + self.fat = self.fat[:self.nb_sect] + debug('\nFAT:') + self.dumpfat(self.fat) + + + def loadminifat(self): + """ + Load the MiniFAT table. + """ + # MiniFAT is stored in a standard sub-stream, pointed to by a header + # field. + # NOTE: there are two sizes to take into account for this stream: + # 1) Stream size is calculated according to the number of sectors + # declared in the OLE header. This allocated stream may be more than + # needed to store the actual sector indexes. + # (self.csectMiniFat is the number of sectors of size self.SectorSize) + stream_size = self.csectMiniFat * self.SectorSize + # 2) Actually used size is calculated by dividing the MiniStream size + # (given by root entry size) by the size of mini sectors, *4 for + # 32 bits indexes: + nb_minisectors = (self.root.size + self.MiniSectorSize-1) / self.MiniSectorSize + used_size = nb_minisectors * 4 + debug('loadminifat(): minifatsect=%d, nb FAT sectors=%d, used_size=%d, stream_size=%d, nb MiniSectors=%d' % + (self.minifatsect, self.csectMiniFat, used_size, stream_size, nb_minisectors)) + if used_size > stream_size: + # This is not really a problem, but may indicate a wrong implementation: + self._raise_defect(DEFECT_INCORRECT, 'OLE MiniStream is larger than MiniFAT') + # In any case, first read stream_size: + s = self._open(self.minifatsect, stream_size, force_FAT=True).read() + #[PL] Old code replaced by an array: + #self.minifat = map(lambda i, s=s: i32(s, i), range(0, len(s), 4)) + self.minifat = self.sect2array(s) + # Then shrink the array to used size, to avoid indexes out of MiniStream: + debug('MiniFAT shrunk from %d to %d sectors' % (len(self.minifat), nb_minisectors)) + self.minifat = self.minifat[:nb_minisectors] + debug('loadminifat(): len=%d' % len(self.minifat)) + debug('\nMiniFAT:') + self.dumpfat(self.minifat) + + def getsect(self, sect): + """ + Read given sector from file on disk. + sect: sector index + returns a string containing the sector data. + """ + # [PL] this original code was wrong when sectors are 4KB instead of + # 512 bytes: + #self.fp.seek(512 + self.sectorsize * sect) + #[PL]: added safety checks: + #print "getsect(%X)" % sect + try: + self.fp.seek(self.sectorsize * (sect+1)) + except: + debug('getsect(): sect=%X, seek=%d, filesize=%d' % + (sect, self.sectorsize*(sect+1), self._filesize)) + self._raise_defect(DEFECT_FATAL, 'OLE sector index out of range') + sector = self.fp.read(self.sectorsize) + if len(sector) != self.sectorsize: + debug('getsect(): sect=%X, read=%d, sectorsize=%d' % + (sect, len(sector), self.sectorsize)) + self._raise_defect(DEFECT_FATAL, 'incomplete OLE sector') + return sector + + + def loaddirectory(self, sect): + """ + Load the directory. + sect: sector index of directory stream. + """ + # The directory is stored in a standard + # substream, independent of its size. + + # open directory stream as a read-only file: + # (stream size is not known in advance) + self.directory_fp = self._open(sect) + + #[PL] to detect malformed documents and avoid DoS attacks, the maximum + # number of directory entries can be calculated: + max_entries = self.directory_fp.size / 128 + debug('loaddirectory: size=%d, max_entries=%d' % + (self.directory_fp.size, max_entries)) + + # Create list of directory entries + #self.direntries = [] + # We start with a list of "None" object + self.direntries = [None] * max_entries +## for sid in xrange(max_entries): +## entry = fp.read(128) +## if not entry: +## break +## self.direntries.append(_OleDirectoryEntry(entry, sid, self)) + # load root entry: + root_entry = self._load_direntry(0) + # Root entry is the first entry: + self.root = self.direntries[0] + # read and build all storage trees, starting from the root: + self.root.build_storage_tree() + + + def _load_direntry (self, sid): + """ + Load a directory entry from the directory. + This method should only be called once for each storage/stream when + loading the directory. + sid: index of storage/stream in the directory. + return: a _OleDirectoryEntry object + raise: IOError if the entry has always been referenced. + """ + # check if SID is OK: + if sid<0 or sid>=len(self.direntries): + self._raise_defect(DEFECT_FATAL, "OLE directory index out of range") + # check if entry was already referenced: + if self.direntries[sid] is not None: + self._raise_defect(DEFECT_INCORRECT, + "double reference for OLE stream/storage") + # if exception not raised, return the object + return self.direntries[sid] + self.directory_fp.seek(sid * 128) + entry = self.directory_fp.read(128) + self.direntries[sid] = _OleDirectoryEntry(entry, sid, self) + return self.direntries[sid] + + + def dumpdirectory(self): + """ + Dump directory (for debugging only) + """ + self.root.dump() + + + def _open(self, start, size = 0x7FFFFFFF, force_FAT=False): + """ + Open a stream, either in FAT or MiniFAT according to its size. + (openstream helper) + + start: index of first sector + size: size of stream (or nothing if size is unknown) + force_FAT: if False (default), stream will be opened in FAT or MiniFAT + according to size. If True, it will always be opened in FAT. + """ + debug('OleFileIO.open(): sect=%d, size=%d, force_FAT=%s' % + (start, size, str(force_FAT))) + # stream size is compared to the MiniSectorCutoff threshold: + if size < self.minisectorcutoff and not force_FAT: + # ministream object + if not self.ministream: + # load MiniFAT if it wasn't already done: + self.loadminifat() + # The first sector index of the miniFAT stream is stored in the + # root directory entry: + size_ministream = self.root.size + debug('Opening MiniStream: sect=%d, size=%d' % + (self.root.isectStart, size_ministream)) + self.ministream = self._open(self.root.isectStart, + size_ministream, force_FAT=True) + return _OleStream(self.ministream, start, size, 0, + self.minisectorsize, self.minifat, + self.ministream.size) + else: + # standard stream + return _OleStream(self.fp, start, size, 512, + self.sectorsize, self.fat, self._filesize) + + + def _list(self, files, prefix, node): + """ + (listdir helper) + files: list of files to fill in + prefix: current location in storage tree (list of names) + node: current node (_OleDirectoryEntry object) + """ + prefix = prefix + [node.name] + for entry in node.kids: + if entry.kids: + self._list(files, prefix, entry) + else: + files.append(prefix[1:] + [entry.name]) + + + def listdir(self): + """ + Return a list of streams stored in this file + """ + files = [] + self._list(files, [], self.root) + return files + + + def _find(self, filename): + """ + Returns directory entry of given filename. (openstream helper) + Note: this method is case-insensitive. + + filename: path of stream in storage tree (except root entry), either: + - a string using Unix path syntax, for example: + 'storage_1/storage_1.2/stream' + - a list of storage filenames, path to the desired stream/storage. + Example: ['storage_1', 'storage_1.2', 'stream'] + return: sid of requested filename + raise IOError if file not found + """ + + # if filename is a string instead of a list, split it on slashes to + # convert to a list: + if isinstance(filename, basestring): + filename = filename.split('/') + # walk across storage tree, following given path: + node = self.root + for name in filename: + for kid in node.kids: + if kid.name.lower() == name.lower(): + break + else: + raise IOError, "file not found" + node = kid + return node.sid + + + def openstream(self, filename): + """ + Open a stream as a read-only file object (StringIO). + + filename: path of stream in storage tree (except root entry), either: + - a string using Unix path syntax, for example: + 'storage_1/storage_1.2/stream' + - a list of storage filenames, path to the desired stream/storage. + Example: ['storage_1', 'storage_1.2', 'stream'] + return: file object (read-only) + raise IOError if filename not found, or if this is not a stream. + """ + sid = self._find(filename) + entry = self.direntries[sid] + if entry.entry_type != STGTY_STREAM: + raise IOError, "this file is not a stream" + return self._open(entry.isectStart, entry.size) + + + def get_type(self, filename): + """ + Test if given filename exists as a stream or a storage in the OLE + container, and return its type. + + filename: path of stream in storage tree. (see openstream for syntax) + return: False if object does not exist, its entry type (>0) otherwise: + - STGTY_STREAM: a stream + - STGTY_STORAGE: a storage + - STGTY_ROOT: the root entry + """ + try: + sid = self._find(filename) + entry = self.direntries[sid] + return entry.entry_type + except: + return False + + + def exists(self, filename): + """ + Test if given filename exists as a stream or a storage in the OLE + container. + + filename: path of stream in storage tree. (see openstream for syntax) + return: True if object exist, else False. + """ + try: + sid = self._find(filename) + return True + except: + return False + + + def get_size(self, filename): + """ + Return size of a stream in the OLE container, in bytes. + + filename: path of stream in storage tree (see openstream for syntax) + return: size in bytes (long integer) + raise: IOError if file not found, TypeError if this is not a stream. + """ + sid = self._find(filename) + entry = self.direntries[sid] + if entry.entry_type != STGTY_STREAM: + #TODO: Should it return zero instead of raising an exception ? + raise TypeError, 'object is not an OLE stream' + return entry.size + + + def get_rootentry_name(self): + """ + Return root entry name. Should usually be 'Root Entry' or 'R' in most + implementations. + """ + return self.root.name + + + def getproperties(self, filename): + """ + Return properties described in substream. + + filename: path of stream in storage tree (see openstream for syntax) + return: a dictionary of values indexed by id (integer) + """ + fp = self.openstream(filename) + + data = {} + + # header + s = fp.read(28) + clsid = _clsid(s[8:24]) + + # format id + s = fp.read(20) + fmtid = _clsid(s[:16]) + fp.seek(i32(s, 16)) + + # get section + s = "****" + fp.read(i32(fp.read(4))-4) + + for i in range(i32(s, 4)): + + id = i32(s, 8+i*8) + offset = i32(s, 12+i*8) + type = i32(s, offset) + + debug ('property id=%d: type=%d offset=%X' % (id, type, offset)) + + # test for common types first (should perhaps use + # a dictionary instead?) + + if type == VT_I2: + value = i16(s, offset+4) + if value >= 32768: + value = value - 65536 + elif type == VT_UI2: + value = i16(s, offset+4) + elif type in (VT_I4, VT_ERROR): + value = i32(s, offset+4) + elif type == VT_UI4: + value = i32(s, offset+4) # FIXME + elif type in (VT_BSTR, VT_LPSTR): + count = i32(s, offset+4) + value = s[offset+8:offset+8+count-1] + elif type == VT_BLOB: + count = i32(s, offset+4) + value = s[offset+8:offset+8+count] + elif type == VT_LPWSTR: + count = i32(s, offset+4) + value = _unicode(s[offset+8:offset+8+count*2]) + elif type == VT_FILETIME: + value = long(i32(s, offset+4)) + (long(i32(s, offset+8))<<32) + # FIXME: this is a 64-bit int: "number of 100ns periods + # since Jan 1,1601". Should map this to Python time + value = value / 10000000L # seconds + elif type == VT_UI1: + value = ord(s[offset+4]) + elif type == VT_CLSID: + value = _clsid(s[offset+4:offset+20]) + elif type == VT_CF: + count = i32(s, offset+4) + value = s[offset+8:offset+8+count] + else: + value = None # everything else yields "None" + + # FIXME: add support for VT_VECTOR + + #print "%08x" % id, repr(value), + #print "(%s)" % VT[i32(s, offset) & 0xFFF] + + data[id] = value + + return data + +# +# -------------------------------------------------------------------- +# This script can be used to dump the directory of any OLE2 structured +# storage file. + +if __name__ == "__main__": + + import sys + + # [PL] display quick usage info if launched from command-line + if len(sys.argv) <= 1: + print __doc__ + print """ +Launched from command line, this script parses OLE files and prints info. + +Usage: OleFileIO_PL.py [-d] [-c] [file2 ...] + +Options: +-d : debug mode (display a lot of debug information, for developers only) +-c : check all streams (for debugging purposes) +""" + sys.exit() + + check_streams = False + for filename in sys.argv[1:]: +## try: + # OPTIONS: + if filename == '-d': + # option to switch debug mode on: + set_debug_mode(True) + continue + if filename == '-c': + # option to switch check streams mode on: + check_streams = True + continue + + ole = OleFileIO(filename, raise_defects=DEFECT_INCORRECT) + print "-" * 68 + print filename + print "-" * 68 + ole.dumpdirectory() + for streamname in ole.listdir(): + if streamname[-1][0] == "\005": + print streamname, ": properties" + props = ole.getproperties(streamname) + props = props.items() + props.sort() + for k, v in props: + #[PL]: avoid to display too large or binary values: + if isinstance(v, basestring): + if len(v) > 50: + v = v[:50] + # quick and dirty binary check: + for c in (1,2,3,4,5,6,7,11,12,14,15,16,17,18,19,20, + 21,22,23,24,25,26,27,28,29,30,31): + if chr(c) in v: + v = '(binary data)' + break + print " ", k, v + + if check_streams: + # Read all streams to check if there are errors: + print '\nChecking streams...' + for streamname in ole.listdir(): + # print name using repr() to convert binary chars to \xNN: + print '-', repr('/'.join(streamname)),'-', + st_type = ole.get_type(streamname) + if st_type == STGTY_STREAM: + print 'size %d' % ole.get_size(streamname) + # just try to read stream in memory: + ole.openstream(streamname) + else: + print 'NOT a stream : type=%d' % st_type + print '' + + #[PL] Test a few new methods: + root = ole.get_rootentry_name() + print 'Root entry name: "%s"' % root + if ole.exists('worddocument'): + print "This is a Word document." + print "type of stream 'WordDocument':", ole.get_type('worddocument') + print "size :", ole.get_size('worddocument') + if ole.exists('macros/vba'): + print "This document may contain VBA macros." +## except IOError, v: +## print "***", "cannot read", file, "-", v diff --git a/oletools/thirdparty/OleFileIO_PL/README.txt b/oletools/thirdparty/OleFileIO_PL/README.txt new file mode 100644 index 0000000..b26c1b4 --- /dev/null +++ b/oletools/thirdparty/OleFileIO_PL/README.txt @@ -0,0 +1,173 @@ +OleFileIO\_PL +============= + +`OleFileIO\_PL `_ is a Python +module to read `Microsoft OLE2 files (also called Structured Storage, +Compound File Binary Format or Compound Document File +Format) `_, +such as Microsoft Office documents, Image Composer and FlashPix files, +Outlook messages, ... + +This is an improved version of the OleFileIO module from +`PIL `_, the excellent +Python Imaging Library, created and maintained by Fredrik Lundh. The API +is still compatible with PIL, but I have improved the internal +implementation significantly, with bugfixes and a more robust design. + +As far as I know, this module is now the most complete and robust Python +implementation to read MS OLE2 files, portable on several operating +systems. (please tell me if you know other similar Python modules) + +WARNING: THIS IS (STILL) WORK IN PROGRESS. + +Main improvements over PIL version: +----------------------------------- + +- Better compatibility with Python 2.4 up to 2.7 +- Support for files larger than 6.8MB +- Robust: many checks to detect malformed files +- Improved API +- Added setup.py and install.bat to ease installation + +News +---- + +- 2012-09-11 v0.23: added support for file-like objects, fixed `issue + #8 `_ +- 2012-02-17 v0.22: fixed issues #7 (bug in getproperties) and #2 + (added close method) +- 2011-10-20: code hosted on bitbucket to ease contributions and bug + tracking +- 2010-01-24 v0.21: fixed support for big-endian CPUs, such as PowerPC + Macs. +- 2009-12-11 v0.20: small bugfix in OleFileIO.open when filename is not + plain str. +- 2009-12-10 v0.19: fixed support for 64 bits platforms (thanks to Ben + G. and Martijn for reporting the bug) +- see changelog in source code for more info. + +Download: +--------- + +The archive is available on `the project +page `_. + +How to use this module: +----------------------- + +See sample code at the end of the module, and also docstrings. + +Here are a few examples: + +:: + + import OleFileIO_PL + + # Test if a file is an OLE container: + assert OleFileIO_PL.isOleFile('myfile.doc') + + # Open an OLE file from disk: + ole = OleFileIO_PL.OleFileIO('myfile.doc') + + # Get list of streams: + print ole.listdir() + + # Test if known streams/storages exist: + if ole.exists('worddocument'): + print "This is a Word document." + print "size :", ole.get_size('worddocument') + if ole.exists('macros/vba'): + print "This document seems to contain VBA macros." + + # Extract the "Pictures" stream from a PPT file: + if ole.exists('Pictures'): + pics = ole.openstream('Pictures') + data = pics.read() + f = open('Pictures.bin', 'w') + f.write(data) + f.close() + + # Close the OLE file: + ole.close() + + # Work with a file-like object (e.g. StringIO) instead of a file on disk: + data = open('myfile.doc', 'rb').read() + f = StringIO.StringIO(data) + ole = OleFileIO_PL.OleFileIO(f) + print ole.listdir() + ole.close() + +It can also be used as a script from the command-line to display the +structure of an OLE file, for example: + +:: + + OleFileIO_PL.py myfile.doc + +A real-life example: `using OleFileIO\_PL for malware analysis and +forensics `_. + +How to contribute: +------------------ + +The code is available in `a Mercurial repository on +bitbucket `_. You may use +it to submit enhancements or to report any issue. + +If you would like to help us improve this module, or simply provide +feedback, you may also send an e-mail to decalage(at)laposte.net. You +can help in many ways: + +- test this module on different platforms / Python versions +- find and report bugs +- improve documentation, code samples, docstrings +- write unittest test cases +- provide tricky malformed files + +How to report bugs: +------------------- + +To report a bug, for example a normal file which is not parsed +correctly, please use the `issue reporting +page `_, +or send an e-mail with an attachment containing the debugging output of +OleFileIO\_PL. + +For this, launch the following command : + +:: + + OleFileIO_PL.py -d -c file >debug.txt + +License +------- + +OleFileIO\_PL is open-source. + +OleFileIO\_PL changes are Copyright (c) 2005-2012 by Philippe Lagadec. + +The Python Imaging Library (PIL) is + +- Copyright (c) 1997-2005 by Secret Labs AB + +- Copyright (c) 1995-2005 by Fredrik Lundh + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify, and distribute this software and its +associated documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appears in all copies, +and that both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Secret Labs AB or the +author not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR +ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER +RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF +CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/oletools/thirdparty/OleFileIO_PL/__init__.py b/oletools/thirdparty/OleFileIO_PL/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/oletools/thirdparty/OleFileIO_PL/__init__.py diff --git a/oletools/thirdparty/__init__.py b/oletools/thirdparty/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/oletools/thirdparty/__init__.py diff --git a/oletools/thirdparty/easygui/LICENSE.txt b/oletools/thirdparty/easygui/LICENSE.txt new file mode 100644 index 0000000..b04511b --- /dev/null +++ b/oletools/thirdparty/easygui/LICENSE.txt @@ -0,0 +1,32 @@ +LICENSE INFORMATION + +EasyGui version 0.96 + +Copyright (c) 2010, Stephen Raymond Ferg + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/oletools/thirdparty/easygui/__init__.py b/oletools/thirdparty/easygui/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/oletools/thirdparty/easygui/__init__.py diff --git a/oletools/thirdparty/easygui/easygui.py b/oletools/thirdparty/easygui/easygui.py new file mode 100644 index 0000000..016ffd5 --- /dev/null +++ b/oletools/thirdparty/easygui/easygui.py @@ -0,0 +1,2492 @@ +""" +@version: 0.96(2010-08-29) + +@note: +ABOUT EASYGUI + +EasyGui provides an easy-to-use interface for simple GUI interaction +with a user. It does not require the programmer to know anything about +tkinter, frames, widgets, callbacks or lambda. All GUI interactions are +invoked by simple function calls that return results. + +@note: +WARNING about using EasyGui with IDLE + +You may encounter problems using IDLE to run programs that use EasyGui. Try it +and find out. EasyGui is a collection of Tkinter routines that run their own +event loops. IDLE is also a Tkinter application, with its own event loop. The +two may conflict, with unpredictable results. If you find that you have +problems, try running your EasyGui program outside of IDLE. + +Note that EasyGui requires Tk release 8.0 or greater. + +@note: +LICENSE INFORMATION + +EasyGui version 0.96 + +Copyright (c) 2010, Stephen Raymond Ferg + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + + 3. The name of the author may not be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +@note: +ABOUT THE EASYGUI LICENSE + +This license is what is generally known as the "modified BSD license", +aka "revised BSD", "new BSD", "3-clause BSD". +See http://www.opensource.org/licenses/bsd-license.php + +This license is GPL-compatible. +See http://en.wikipedia.org/wiki/License_compatibility +See http://www.gnu.org/licenses/license-list.html#GPLCompatibleLicenses + +The BSD License is less restrictive than GPL. +It allows software released under the license to be incorporated into proprietary products. +Works based on the software may be released under a proprietary license or as closed source software. +http://en.wikipedia.org/wiki/BSD_licenses#3-clause_license_.28.22New_BSD_License.22.29 + +""" +egversion = __doc__.split()[1] + +__all__ = ['ynbox' + , 'ccbox' + , 'boolbox' + , 'indexbox' + , 'msgbox' + , 'buttonbox' + , 'integerbox' + , 'multenterbox' + , 'enterbox' + , 'exceptionbox' + , 'choicebox' + , 'codebox' + , 'textbox' + , 'diropenbox' + , 'fileopenbox' + , 'filesavebox' + , 'passwordbox' + , 'multpasswordbox' + , 'multchoicebox' + , 'abouteasygui' + , 'egversion' + , 'egdemo' + , 'EgStore' + ] + +import sys, os +import string +import pickle +import traceback + + +#-------------------------------------------------- +# check python version and take appropriate action +#-------------------------------------------------- +""" +From the python documentation: + +sys.hexversion contains the version number encoded as a single integer. This is +guaranteed to increase with each version, including proper support for non- +production releases. For example, to test that the Python interpreter is at +least version 1.5.2, use: + +if sys.hexversion >= 0x010502F0: + # use some advanced feature + ... +else: + # use an alternative implementation or warn the user + ... +""" + + +if sys.hexversion >= 0x020600F0: + runningPython26 = True +else: + runningPython26 = False + +if sys.hexversion >= 0x030000F0: + runningPython3 = True +else: + runningPython3 = False + +try: + from PIL import Image as PILImage + from PIL import ImageTk as PILImageTk + PILisLoaded = True +except: + PILisLoaded = False + + +if runningPython3: + from tkinter import * + import tkinter.filedialog as tk_FileDialog + from io import StringIO +else: + from Tkinter import * + import tkFileDialog as tk_FileDialog + from StringIO import StringIO + +def write(*args): + args = [str(arg) for arg in args] + args = " ".join(args) + sys.stdout.write(args) + +def writeln(*args): + write(*args) + sys.stdout.write("\n") + +say = writeln + + +if TkVersion < 8.0 : + stars = "*"*75 + writeln("""\n\n\n""" + stars + """ +You are running Tk version: """ + str(TkVersion) + """ +You must be using Tk version 8.0 or greater to use EasyGui. +Terminating. +""" + stars + """\n\n\n""") + sys.exit(0) + +def dq(s): + return '"%s"' % s + +rootWindowPosition = "+300+200" + +PROPORTIONAL_FONT_FAMILY = ("MS", "Sans", "Serif") +MONOSPACE_FONT_FAMILY = ("Courier") + +PROPORTIONAL_FONT_SIZE = 10 +MONOSPACE_FONT_SIZE = 9 #a little smaller, because it it more legible at a smaller size +TEXT_ENTRY_FONT_SIZE = 12 # a little larger makes it easier to see + +#STANDARD_SELECTION_EVENTS = ["Return", "Button-1"] +STANDARD_SELECTION_EVENTS = ["Return", "Button-1", "space"] + +# Initialize some global variables that will be reset later +__choiceboxMultipleSelect = None +__widgetTexts = None +__replyButtonText = None +__choiceboxResults = None +__firstWidget = None +__enterboxText = None +__enterboxDefaultText="" +__multenterboxText = "" +choiceboxChoices = None +choiceboxWidget = None +entryWidget = None +boxRoot = None +ImageErrorMsg = ( + "\n\n---------------------------------------------\n" + "Error: %s\n%s") +#------------------------------------------------------------------- +# various boxes built on top of the basic buttonbox +#----------------------------------------------------------------------- + +#----------------------------------------------------------------------- +# ynbox +#----------------------------------------------------------------------- +def ynbox(msg="Shall I continue?" + , title=" " + , choices=("Yes", "No") + , image=None + ): + """ + Display a msgbox with choices of Yes and No. + + The default is "Yes". + + The returned value is calculated this way:: + if the first choice ("Yes") is chosen, or if the dialog is cancelled: + return 1 + else: + return 0 + + If invoked without a msg argument, displays a generic request for a confirmation + that the user wishes to continue. So it can be used this way:: + if ynbox(): pass # continue + else: sys.exit(0) # exit the program + + @arg msg: the msg to be displayed. + @arg title: the window title + @arg choices: a list or tuple of the choices to be displayed + """ + return boolbox(msg, title, choices, image=image) + + +#----------------------------------------------------------------------- +# ccbox +#----------------------------------------------------------------------- +def ccbox(msg="Shall I continue?" + , title=" " + , choices=("Continue", "Cancel") + , image=None + ): + """ + Display a msgbox with choices of Continue and Cancel. + + The default is "Continue". + + The returned value is calculated this way:: + if the first choice ("Continue") is chosen, or if the dialog is cancelled: + return 1 + else: + return 0 + + If invoked without a msg argument, displays a generic request for a confirmation + that the user wishes to continue. So it can be used this way:: + + if ccbox(): + pass # continue + else: + sys.exit(0) # exit the program + + @arg msg: the msg to be displayed. + @arg title: the window title + @arg choices: a list or tuple of the choices to be displayed + """ + return boolbox(msg, title, choices, image=image) + + +#----------------------------------------------------------------------- +# boolbox +#----------------------------------------------------------------------- +def boolbox(msg="Shall I continue?" + , title=" " + , choices=("Yes","No") + , image=None + ): + """ + Display a boolean msgbox. + + The default is the first choice. + + The returned value is calculated this way:: + if the first choice is chosen, or if the dialog is cancelled: + returns 1 + else: + returns 0 + """ + reply = buttonbox(msg=msg, choices=choices, title=title, image=image) + if reply == choices[0]: return 1 + else: return 0 + + +#----------------------------------------------------------------------- +# indexbox +#----------------------------------------------------------------------- +def indexbox(msg="Shall I continue?" + , title=" " + , choices=("Yes","No") + , image=None + ): + """ + Display a buttonbox with the specified choices. + Return the index of the choice selected. + """ + reply = buttonbox(msg=msg, choices=choices, title=title, image=image) + index = -1 + for choice in choices: + index = index + 1 + if reply == choice: return index + raise AssertionError( + "There is a program logic error in the EasyGui code for indexbox.") + + +#----------------------------------------------------------------------- +# msgbox +#----------------------------------------------------------------------- +def msgbox(msg="(Your message goes here)", title=" ", ok_button="OK",image=None,root=None): + """ + Display a messagebox + """ + if type(ok_button) != type("OK"): + raise AssertionError("The 'ok_button' argument to msgbox must be a string.") + + return buttonbox(msg=msg, title=title, choices=[ok_button], image=image,root=root) + + +#------------------------------------------------------------------- +# buttonbox +#------------------------------------------------------------------- +def buttonbox(msg="",title=" " + ,choices=("Button1", "Button2", "Button3") + , image=None + , root=None + ): + """ + Display a msg, a title, and a set of buttons. + The buttons are defined by the members of the choices list. + Return the text of the button that the user selected. + + @arg msg: the msg to be displayed. + @arg title: the window title + @arg choices: a list or tuple of the choices to be displayed + """ + global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame + + + # Initialize __replyButtonText to the first choice. + # This is what will be used if the window is closed by the close button. + __replyButtonText = choices[0] + + if root: + root.withdraw() + boxRoot = Toplevel(master=root) + boxRoot.withdraw() + else: + boxRoot = Tk() + boxRoot.withdraw() + + boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) + boxRoot.title(title) + boxRoot.iconname('Dialog') + boxRoot.geometry(rootWindowPosition) + boxRoot.minsize(400, 100) + + # ------------- define the messageFrame --------------------------------- + messageFrame = Frame(master=boxRoot) + messageFrame.pack(side=TOP, fill=BOTH) + + # ------------- define the imageFrame --------------------------------- + tk_Image = None + if image: + imageFilename = os.path.normpath(image) + junk,ext = os.path.splitext(imageFilename) + + if os.path.exists(imageFilename): + if ext.lower() in [".gif", ".pgm", ".ppm"]: + tk_Image = PhotoImage(master=boxRoot, file=imageFilename) + else: + if PILisLoaded: + try: + pil_Image = PILImage.open(imageFilename) + tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot) + except: + msg += ImageErrorMsg % (imageFilename, + "\nThe Python Imaging Library (PIL) could not convert this file to a displayable image." + "\n\nPIL reports:\n" + exception_format()) + + else: # PIL is not loaded + msg += ImageErrorMsg % (imageFilename, + "\nI could not import the Python Imaging Library (PIL) to display the image.\n\n" + "You may need to install PIL\n" + "(http://www.pythonware.com/products/pil/)\n" + "to display " + ext + " image files.") + + else: + msg += ImageErrorMsg % (imageFilename, "\nImage file not found.") + + if tk_Image: + imageFrame = Frame(master=boxRoot) + imageFrame.pack(side=TOP, fill=BOTH) + label = Label(imageFrame,image=tk_Image) + label.image = tk_Image # keep a reference! + label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m') + + # ------------- define the buttonsFrame --------------------------------- + buttonsFrame = Frame(master=boxRoot) + buttonsFrame.pack(side=TOP, fill=BOTH) + + # -------------------- place the widgets in the frames ----------------------- + messageWidget = Message(messageFrame, text=msg, width=400) + messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) + messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m') + + __put_buttons_in_buttonframe(choices) + + # -------------- the action begins ----------- + # put the focus on the first button + __firstWidget.focus_force() + + boxRoot.deiconify() + boxRoot.mainloop() + boxRoot.destroy() + if root: root.deiconify() + return __replyButtonText + + +#------------------------------------------------------------------- +# integerbox +#------------------------------------------------------------------- +def integerbox(msg="" + , title=" " + , default="" + , lowerbound=0 + , upperbound=99 + , image = None + , root = None + , **invalidKeywordArguments + ): + """ + Show a box in which a user can enter an integer. + + In addition to arguments for msg and title, this function accepts + integer arguments for "default", "lowerbound", and "upperbound". + + The default argument may be None. + + When the user enters some text, the text is checked to verify that it + can be converted to an integer between the lowerbound and upperbound. + + If it can be, the integer (not the text) is returned. + + If it cannot, then an error msg is displayed, and the integerbox is + redisplayed. + + If the user cancels the operation, None is returned. + + NOTE that the "argLowerBound" and "argUpperBound" arguments are no longer + supported. They have been replaced by "upperbound" and "lowerbound". + """ + if "argLowerBound" in invalidKeywordArguments: + raise AssertionError( + "\nintegerbox no longer supports the 'argLowerBound' argument.\n" + + "Use 'lowerbound' instead.\n\n") + if "argUpperBound" in invalidKeywordArguments: + raise AssertionError( + "\nintegerbox no longer supports the 'argUpperBound' argument.\n" + + "Use 'upperbound' instead.\n\n") + + if default != "": + if type(default) != type(1): + raise AssertionError( + "integerbox received a non-integer value for " + + "default of " + dq(str(default)) , "Error") + + if type(lowerbound) != type(1): + raise AssertionError( + "integerbox received a non-integer value for " + + "lowerbound of " + dq(str(lowerbound)) , "Error") + + if type(upperbound) != type(1): + raise AssertionError( + "integerbox received a non-integer value for " + + "upperbound of " + dq(str(upperbound)) , "Error") + + if msg == "": + msg = ("Enter an integer between " + str(lowerbound) + + " and " + + str(upperbound) + ) + + while 1: + reply = enterbox(msg, title, str(default), image=image, root=root) + if reply == None: return None + + try: + reply = int(reply) + except: + msgbox ("The value that you entered:\n\t%s\nis not an integer." % dq(str(reply)) + , "Error") + continue + + if reply < lowerbound: + msgbox ("The value that you entered is less than the lower bound of " + + str(lowerbound) + ".", "Error") + continue + + if reply > upperbound: + msgbox ("The value that you entered is greater than the upper bound of " + + str(upperbound) + ".", "Error") + continue + + # reply has passed all validation checks. + # It is an integer between the specified bounds. + return reply + +#------------------------------------------------------------------- +# multenterbox +#------------------------------------------------------------------- +def multenterbox(msg="Fill in values for the fields." + , title=" " + , fields=() + , values=() + ): + r""" + Show screen with multiple data entry fields. + + If there are fewer values than names, the list of values is padded with + empty strings until the number of values is the same as the number of names. + + If there are more values than names, the list of values + is truncated so that there are as many values as names. + + Returns a list of the values of the fields, + or None if the user cancels the operation. + + Here is some example code, that shows how values returned from + multenterbox can be checked for validity before they are accepted:: + ---------------------------------------------------------------------- + msg = "Enter your personal information" + title = "Credit Card Application" + fieldNames = ["Name","Street Address","City","State","ZipCode"] + fieldValues = [] # we start with blanks for the values + fieldValues = multenterbox(msg,title, fieldNames) + + # make sure that none of the fields was left blank + while 1: + if fieldValues == None: break + errmsg = "" + for i in range(len(fieldNames)): + if fieldValues[i].strip() == "": + errmsg += ('"%s" is a required field.\n\n' % fieldNames[i]) + if errmsg == "": + break # no problems found + fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) + + writeln("Reply was: %s" % str(fieldValues)) + ---------------------------------------------------------------------- + + @arg msg: the msg to be displayed. + @arg title: the window title + @arg fields: a list of fieldnames. + @arg values: a list of field values + """ + return __multfillablebox(msg,title,fields,values,None) + + +#----------------------------------------------------------------------- +# multpasswordbox +#----------------------------------------------------------------------- +def multpasswordbox(msg="Fill in values for the fields." + , title=" " + , fields=tuple() + ,values=tuple() + ): + r""" + Same interface as multenterbox. But in multpassword box, + the last of the fields is assumed to be a password, and + is masked with asterisks. + + Example + ======= + + Here is some example code, that shows how values returned from + multpasswordbox can be checked for validity before they are accepted:: + msg = "Enter logon information" + title = "Demo of multpasswordbox" + fieldNames = ["Server ID", "User ID", "Password"] + fieldValues = [] # we start with blanks for the values + fieldValues = multpasswordbox(msg,title, fieldNames) + + # make sure that none of the fields was left blank + while 1: + if fieldValues == None: break + errmsg = "" + for i in range(len(fieldNames)): + if fieldValues[i].strip() == "": + errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) + if errmsg == "": break # no problems found + fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) + + writeln("Reply was: %s" % str(fieldValues)) + """ + return __multfillablebox(msg,title,fields,values,"*") + +def bindArrows(widget): + widget.bind("", tabRight) + widget.bind("" , tabLeft) + + widget.bind("",tabRight) + widget.bind("" , tabLeft) + +def tabRight(event): + boxRoot.event_generate("") + +def tabLeft(event): + boxRoot.event_generate("") + +#----------------------------------------------------------------------- +# __multfillablebox +#----------------------------------------------------------------------- +def __multfillablebox(msg="Fill in values for the fields." + , title=" " + , fields=() + , values=() + , mask = None + ): + global boxRoot, __multenterboxText, __multenterboxDefaultText, cancelButton, entryWidget, okButton + + choices = ["OK", "Cancel"] + if len(fields) == 0: return None + + fields = list(fields[:]) # convert possible tuples to a list + values = list(values[:]) # convert possible tuples to a list + + if len(values) == len(fields): pass + elif len(values) > len(fields): + fields = fields[0:len(values)] + else: + while len(values) < len(fields): + values.append("") + + boxRoot = Tk() + + boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) + boxRoot.title(title) + boxRoot.iconname('Dialog') + boxRoot.geometry(rootWindowPosition) + boxRoot.bind("", __multenterboxCancel) + + # -------------------- put subframes in the boxRoot -------------------- + messageFrame = Frame(master=boxRoot) + messageFrame.pack(side=TOP, fill=BOTH) + + #-------------------- the msg widget ---------------------------- + messageWidget = Message(messageFrame, width="4.5i", text=msg) + messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) + messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m') + + global entryWidgets + entryWidgets = [] + + lastWidgetIndex = len(fields) - 1 + + for widgetIndex in range(len(fields)): + argFieldName = fields[widgetIndex] + argFieldValue = values[widgetIndex] + entryFrame = Frame(master=boxRoot) + entryFrame.pack(side=TOP, fill=BOTH) + + # --------- entryWidget ---------------------------------------------- + labelWidget = Label(entryFrame, text=argFieldName) + labelWidget.pack(side=LEFT) + + entryWidget = Entry(entryFrame, width=40,highlightthickness=2) + entryWidgets.append(entryWidget) + entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE)) + entryWidget.pack(side=RIGHT, padx="3m") + + bindArrows(entryWidget) + + entryWidget.bind("", __multenterboxGetText) + entryWidget.bind("", __multenterboxCancel) + + # for the last entryWidget, if this is a multpasswordbox, + # show the contents as just asterisks + if widgetIndex == lastWidgetIndex: + if mask: + entryWidgets[widgetIndex].configure(show=mask) + + # put text into the entryWidget + entryWidgets[widgetIndex].insert(0,argFieldValue) + widgetIndex += 1 + + # ------------------ ok button ------------------------------- + buttonsFrame = Frame(master=boxRoot) + buttonsFrame.pack(side=BOTTOM, fill=BOTH) + + okButton = Button(buttonsFrame, takefocus=1, text="OK") + bindArrows(okButton) + okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m') + + # for the commandButton, bind activation events to the activation event handler + commandButton = okButton + handler = __multenterboxGetText + for selectionEvent in STANDARD_SELECTION_EVENTS: + commandButton.bind("<%s>" % selectionEvent, handler) + + + # ------------------ cancel button ------------------------------- + cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel") + bindArrows(cancelButton) + cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m') + + # for the commandButton, bind activation events to the activation event handler + commandButton = cancelButton + handler = __multenterboxCancel + for selectionEvent in STANDARD_SELECTION_EVENTS: + commandButton.bind("<%s>" % selectionEvent, handler) + + + # ------------------- time for action! ----------------- + entryWidgets[0].focus_force() # put the focus on the entryWidget + boxRoot.mainloop() # run it! + + # -------- after the run has completed ---------------------------------- + boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now + return __multenterboxText + + +#----------------------------------------------------------------------- +# __multenterboxGetText +#----------------------------------------------------------------------- +def __multenterboxGetText(event): + global __multenterboxText + + __multenterboxText = [] + for entryWidget in entryWidgets: + __multenterboxText.append(entryWidget.get()) + boxRoot.quit() + + +def __multenterboxCancel(event): + global __multenterboxText + __multenterboxText = None + boxRoot.quit() + + +#------------------------------------------------------------------- +# enterbox +#------------------------------------------------------------------- +def enterbox(msg="Enter something." + , title=" " + , default="" + , strip=True + , image=None + , root=None + ): + """ + Show a box in which a user can enter some text. + + You may optionally specify some default text, which will appear in the + enterbox when it is displayed. + + Returns the text that the user entered, or None if he cancels the operation. + + By default, enterbox strips its result (i.e. removes leading and trailing + whitespace). (If you want it not to strip, use keyword argument: strip=False.) + This makes it easier to test the results of the call:: + + reply = enterbox(....) + if reply: + ... + else: + ... + """ + result = __fillablebox(msg, title, default=default, mask=None,image=image,root=root) + if result and strip: + result = result.strip() + return result + + +def passwordbox(msg="Enter your password." + , title=" " + , default="" + , image=None + , root=None + ): + """ + Show a box in which a user can enter a password. + The text is masked with asterisks, so the password is not displayed. + Returns the text that the user entered, or None if he cancels the operation. + """ + return __fillablebox(msg, title, default, mask="*",image=image,root=root) + + +def __fillablebox(msg + , title="" + , default="" + , mask=None + , image=None + , root=None + ): + """ + Show a box in which a user can enter some text. + You may optionally specify some default text, which will appear in the + enterbox when it is displayed. + Returns the text that the user entered, or None if he cancels the operation. + """ + + global boxRoot, __enterboxText, __enterboxDefaultText + global cancelButton, entryWidget, okButton + + if title == None: title == "" + if default == None: default = "" + __enterboxDefaultText = default + __enterboxText = __enterboxDefaultText + + if root: + root.withdraw() + boxRoot = Toplevel(master=root) + boxRoot.withdraw() + else: + boxRoot = Tk() + boxRoot.withdraw() + + boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) + boxRoot.title(title) + boxRoot.iconname('Dialog') + boxRoot.geometry(rootWindowPosition) + boxRoot.bind("", __enterboxCancel) + + # ------------- define the messageFrame --------------------------------- + messageFrame = Frame(master=boxRoot) + messageFrame.pack(side=TOP, fill=BOTH) + + # ------------- define the imageFrame --------------------------------- + tk_Image = None + if image: + imageFilename = os.path.normpath(image) + junk,ext = os.path.splitext(imageFilename) + + if os.path.exists(imageFilename): + if ext.lower() in [".gif", ".pgm", ".ppm"]: + tk_Image = PhotoImage(master=boxRoot, file=imageFilename) + else: + if PILisLoaded: + try: + pil_Image = PILImage.open(imageFilename) + tk_Image = PILImageTk.PhotoImage(pil_Image, master=boxRoot) + except: + msg += ImageErrorMsg % (imageFilename, + "\nThe Python Imaging Library (PIL) could not convert this file to a displayable image." + "\n\nPIL reports:\n" + exception_format()) + + else: # PIL is not loaded + msg += ImageErrorMsg % (imageFilename, + "\nI could not import the Python Imaging Library (PIL) to display the image.\n\n" + "You may need to install PIL\n" + "(http://www.pythonware.com/products/pil/)\n" + "to display " + ext + " image files.") + + else: + msg += ImageErrorMsg % (imageFilename, "\nImage file not found.") + + if tk_Image: + imageFrame = Frame(master=boxRoot) + imageFrame.pack(side=TOP, fill=BOTH) + label = Label(imageFrame,image=tk_Image) + label.image = tk_Image # keep a reference! + label.pack(side=TOP, expand=YES, fill=X, padx='1m', pady='1m') + + # ------------- define the buttonsFrame --------------------------------- + buttonsFrame = Frame(master=boxRoot) + buttonsFrame.pack(side=TOP, fill=BOTH) + + + # ------------- define the entryFrame --------------------------------- + entryFrame = Frame(master=boxRoot) + entryFrame.pack(side=TOP, fill=BOTH) + + # ------------- define the buttonsFrame --------------------------------- + buttonsFrame = Frame(master=boxRoot) + buttonsFrame.pack(side=TOP, fill=BOTH) + + #-------------------- the msg widget ---------------------------- + messageWidget = Message(messageFrame, width="4.5i", text=msg) + messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) + messageWidget.pack(side=RIGHT, expand=1, fill=BOTH, padx='3m', pady='3m') + + # --------- entryWidget ---------------------------------------------- + entryWidget = Entry(entryFrame, width=40) + bindArrows(entryWidget) + entryWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,TEXT_ENTRY_FONT_SIZE)) + if mask: + entryWidget.configure(show=mask) + entryWidget.pack(side=LEFT, padx="3m") + entryWidget.bind("", __enterboxGetText) + entryWidget.bind("", __enterboxCancel) + # put text into the entryWidget + entryWidget.insert(0,__enterboxDefaultText) + + # ------------------ ok button ------------------------------- + okButton = Button(buttonsFrame, takefocus=1, text="OK") + bindArrows(okButton) + okButton.pack(expand=1, side=LEFT, padx='3m', pady='3m', ipadx='2m', ipady='1m') + + # for the commandButton, bind activation events to the activation event handler + commandButton = okButton + handler = __enterboxGetText + for selectionEvent in STANDARD_SELECTION_EVENTS: + commandButton.bind("<%s>" % selectionEvent, handler) + + + # ------------------ cancel button ------------------------------- + cancelButton = Button(buttonsFrame, takefocus=1, text="Cancel") + bindArrows(cancelButton) + cancelButton.pack(expand=1, side=RIGHT, padx='3m', pady='3m', ipadx='2m', ipady='1m') + + # for the commandButton, bind activation events to the activation event handler + commandButton = cancelButton + handler = __enterboxCancel + for selectionEvent in STANDARD_SELECTION_EVENTS: + commandButton.bind("<%s>" % selectionEvent, handler) + + # ------------------- time for action! ----------------- + entryWidget.focus_force() # put the focus on the entryWidget + boxRoot.deiconify() + boxRoot.mainloop() # run it! + + # -------- after the run has completed ---------------------------------- + if root: root.deiconify() + boxRoot.destroy() # button_click didn't destroy boxRoot, so we do it now + return __enterboxText + + +def __enterboxGetText(event): + global __enterboxText + + __enterboxText = entryWidget.get() + boxRoot.quit() + + +def __enterboxRestore(event): + global entryWidget + + entryWidget.delete(0,len(entryWidget.get())) + entryWidget.insert(0, __enterboxDefaultText) + + +def __enterboxCancel(event): + global __enterboxText + + __enterboxText = None + boxRoot.quit() + +def denyWindowManagerClose(): + """ don't allow WindowManager close + """ + x = Tk() + x.withdraw() + x.bell() + x.destroy() + + + +#------------------------------------------------------------------- +# multchoicebox +#------------------------------------------------------------------- +def multchoicebox(msg="Pick as many items as you like." + , title=" " + , choices=() + , **kwargs + ): + """ + Present the user with a list of choices. + allow him to select multiple items and return them in a list. + if the user doesn't choose anything from the list, return the empty list. + return None if he cancelled selection. + + @arg msg: the msg to be displayed. + @arg title: the window title + @arg choices: a list or tuple of the choices to be displayed + """ + if len(choices) == 0: choices = ["Program logic error - no choices were specified."] + + global __choiceboxMultipleSelect + __choiceboxMultipleSelect = 1 + return __choicebox(msg, title, choices) + + +#----------------------------------------------------------------------- +# choicebox +#----------------------------------------------------------------------- +def choicebox(msg="Pick something." + , title=" " + , choices=() + ): + """ + Present the user with a list of choices. + return the choice that he selects. + return None if he cancels the selection selection. + + @arg msg: the msg to be displayed. + @arg title: the window title + @arg choices: a list or tuple of the choices to be displayed + """ + if len(choices) == 0: choices = ["Program logic error - no choices were specified."] + + global __choiceboxMultipleSelect + __choiceboxMultipleSelect = 0 + return __choicebox(msg,title,choices) + + +#----------------------------------------------------------------------- +# __choicebox +#----------------------------------------------------------------------- +def __choicebox(msg + , title + , choices + ): + """ + internal routine to support choicebox() and multchoicebox() + """ + global boxRoot, __choiceboxResults, choiceboxWidget, defaultText + global choiceboxWidget, choiceboxChoices + #------------------------------------------------------------------- + # If choices is a tuple, we make it a list so we can sort it. + # If choices is already a list, we make a new list, so that when + # we sort the choices, we don't affect the list object that we + # were given. + #------------------------------------------------------------------- + choices = list(choices[:]) + if len(choices) == 0: + choices = ["Program logic error - no choices were specified."] + defaultButtons = ["OK", "Cancel"] + + # make sure all choices are strings + for index in range(len(choices)): + choices[index] = str(choices[index]) + + lines_to_show = min(len(choices), 20) + lines_to_show = 20 + + if title == None: title = "" + + # Initialize __choiceboxResults + # This is the value that will be returned if the user clicks the close icon + __choiceboxResults = None + + boxRoot = Tk() + boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) + screen_width = boxRoot.winfo_screenwidth() + screen_height = boxRoot.winfo_screenheight() + root_width = int((screen_width * 0.8)) + root_height = int((screen_height * 0.5)) + root_xpos = int((screen_width * 0.1)) + root_ypos = int((screen_height * 0.05)) + + boxRoot.title(title) + boxRoot.iconname('Dialog') + rootWindowPosition = "+0+0" + boxRoot.geometry(rootWindowPosition) + boxRoot.expand=NO + boxRoot.minsize(root_width, root_height) + rootWindowPosition = "+" + str(root_xpos) + "+" + str(root_ypos) + boxRoot.geometry(rootWindowPosition) + + # ---------------- put the frames in the window ----------------------------------------- + message_and_buttonsFrame = Frame(master=boxRoot) + message_and_buttonsFrame.pack(side=TOP, fill=X, expand=NO) + + messageFrame = Frame(message_and_buttonsFrame) + messageFrame.pack(side=LEFT, fill=X, expand=YES) + #messageFrame.pack(side=TOP, fill=X, expand=YES) + + buttonsFrame = Frame(message_and_buttonsFrame) + buttonsFrame.pack(side=RIGHT, expand=NO, pady=0) + #buttonsFrame.pack(side=TOP, expand=YES, pady=0) + + choiceboxFrame = Frame(master=boxRoot) + choiceboxFrame.pack(side=BOTTOM, fill=BOTH, expand=YES) + + # -------------------------- put the widgets in the frames ------------------------------ + + # ---------- put a msg widget in the msg frame------------------- + messageWidget = Message(messageFrame, anchor=NW, text=msg, width=int(root_width * 0.9)) + messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) + messageWidget.pack(side=LEFT, expand=YES, fill=BOTH, padx='1m', pady='1m') + + # -------- put the choiceboxWidget in the choiceboxFrame --------------------------- + choiceboxWidget = Listbox(choiceboxFrame + , height=lines_to_show + , borderwidth="1m" + , relief="flat" + , bg="white" + ) + + if __choiceboxMultipleSelect: + choiceboxWidget.configure(selectmode=MULTIPLE) + + choiceboxWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) + + # add a vertical scrollbar to the frame + rightScrollbar = Scrollbar(choiceboxFrame, orient=VERTICAL, command=choiceboxWidget.yview) + choiceboxWidget.configure(yscrollcommand = rightScrollbar.set) + + # add a horizontal scrollbar to the frame + bottomScrollbar = Scrollbar(choiceboxFrame, orient=HORIZONTAL, command=choiceboxWidget.xview) + choiceboxWidget.configure(xscrollcommand = bottomScrollbar.set) + + # pack the Listbox and the scrollbars. Note that although we must define + # the textArea first, we must pack it last, so that the bottomScrollbar will + # be located properly. + + bottomScrollbar.pack(side=BOTTOM, fill = X) + rightScrollbar.pack(side=RIGHT, fill = Y) + + choiceboxWidget.pack(side=LEFT, padx="1m", pady="1m", expand=YES, fill=BOTH) + + #--------------------------------------------------- + # sort the choices + # eliminate duplicates + # put the choices into the choiceboxWidget + #--------------------------------------------------- + for index in range(len(choices)): + choices[index] = str(choices[index]) + + if runningPython3: + choices.sort(key=str.lower) + else: + choices.sort( lambda x,y: cmp(x.lower(), y.lower())) # case-insensitive sort + + lastInserted = None + choiceboxChoices = [] + for choice in choices: + if choice == lastInserted: pass + else: + choiceboxWidget.insert(END, choice) + choiceboxChoices.append(choice) + lastInserted = choice + + boxRoot.bind('', KeyboardListener) + + # put the buttons in the buttonsFrame + if len(choices) > 0: + okButton = Button(buttonsFrame, takefocus=YES, text="OK", height=1, width=6) + bindArrows(okButton) + okButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") + + # for the commandButton, bind activation events to the activation event handler + commandButton = okButton + handler = __choiceboxGetChoice + for selectionEvent in STANDARD_SELECTION_EVENTS: + commandButton.bind("<%s>" % selectionEvent, handler) + + # now bind the keyboard events + choiceboxWidget.bind("", __choiceboxGetChoice) + choiceboxWidget.bind("", __choiceboxGetChoice) + else: + # now bind the keyboard events + choiceboxWidget.bind("", __choiceboxCancel) + choiceboxWidget.bind("", __choiceboxCancel) + + cancelButton = Button(buttonsFrame, takefocus=YES, text="Cancel", height=1, width=6) + bindArrows(cancelButton) + cancelButton.pack(expand=NO, side=BOTTOM, padx='2m', pady='1m', ipady="1m", ipadx="2m") + + # for the commandButton, bind activation events to the activation event handler + commandButton = cancelButton + handler = __choiceboxCancel + for selectionEvent in STANDARD_SELECTION_EVENTS: + commandButton.bind("<%s>" % selectionEvent, handler) + + + # add special buttons for multiple select features + if len(choices) > 0 and __choiceboxMultipleSelect: + selectionButtonsFrame = Frame(messageFrame) + selectionButtonsFrame.pack(side=RIGHT, fill=Y, expand=NO) + + selectAllButton = Button(selectionButtonsFrame, text="Select All", height=1, width=6) + bindArrows(selectAllButton) + + selectAllButton.bind("",__choiceboxSelectAll) + selectAllButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") + + clearAllButton = Button(selectionButtonsFrame, text="Clear All", height=1, width=6) + bindArrows(clearAllButton) + clearAllButton.bind("",__choiceboxClearAll) + clearAllButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") + + + # -------------------- bind some keyboard events ---------------------------- + boxRoot.bind("", __choiceboxCancel) + + # --------------------- the action begins ----------------------------------- + # put the focus on the choiceboxWidget, and the select highlight on the first item + choiceboxWidget.select_set(0) + choiceboxWidget.focus_force() + + # --- run it! ----- + boxRoot.mainloop() + + boxRoot.destroy() + return __choiceboxResults + + +def __choiceboxGetChoice(event): + global boxRoot, __choiceboxResults, choiceboxWidget + + if __choiceboxMultipleSelect: + __choiceboxResults = [choiceboxWidget.get(index) for index in choiceboxWidget.curselection()] + + else: + choice_index = choiceboxWidget.curselection() + __choiceboxResults = choiceboxWidget.get(choice_index) + + # writeln("Debugging> mouse-event=", event, " event.type=", event.type) + # writeln("Debugging> choice=", choice_index, __choiceboxResults) + boxRoot.quit() + + +def __choiceboxSelectAll(event): + global choiceboxWidget, choiceboxChoices + + choiceboxWidget.selection_set(0, len(choiceboxChoices)-1) + +def __choiceboxClearAll(event): + global choiceboxWidget, choiceboxChoices + + choiceboxWidget.selection_clear(0, len(choiceboxChoices)-1) + + + +def __choiceboxCancel(event): + global boxRoot, __choiceboxResults + + __choiceboxResults = None + boxRoot.quit() + + +def KeyboardListener(event): + global choiceboxChoices, choiceboxWidget + key = event.keysym + if len(key) <= 1: + if key in string.printable: + # Find the key in the list. + # before we clear the list, remember the selected member + try: + start_n = int(choiceboxWidget.curselection()[0]) + except IndexError: + start_n = -1 + + ## clear the selection. + choiceboxWidget.selection_clear(0, 'end') + + ## start from previous selection +1 + for n in range(start_n+1, len(choiceboxChoices)): + item = choiceboxChoices[n] + if item[0].lower() == key.lower(): + choiceboxWidget.selection_set(first=n) + choiceboxWidget.see(n) + return + else: + # has not found it so loop from top + for n in range(len(choiceboxChoices)): + item = choiceboxChoices[n] + if item[0].lower() == key.lower(): + choiceboxWidget.selection_set(first = n) + choiceboxWidget.see(n) + return + + # nothing matched -- we'll look for the next logical choice + for n in range(len(choiceboxChoices)): + item = choiceboxChoices[n] + if item[0].lower() > key.lower(): + if n > 0: + choiceboxWidget.selection_set(first = (n-1)) + else: + choiceboxWidget.selection_set(first = 0) + choiceboxWidget.see(n) + return + + # still no match (nothing was greater than the key) + # we set the selection to the first item in the list + lastIndex = len(choiceboxChoices)-1 + choiceboxWidget.selection_set(first = lastIndex) + choiceboxWidget.see(lastIndex) + return + +#----------------------------------------------------------------------- +# exception_format +#----------------------------------------------------------------------- +def exception_format(): + """ + Convert exception info into a string suitable for display. + """ + return "".join(traceback.format_exception( + sys.exc_info()[0] + , sys.exc_info()[1] + , sys.exc_info()[2] + )) + +#----------------------------------------------------------------------- +# exceptionbox +#----------------------------------------------------------------------- +def exceptionbox(msg=None, title=None): + """ + Display a box that gives information about + an exception that has just been raised. + + The caller may optionally pass in a title for the window, or a + msg to accompany the error information. + + Note that you do not need to (and cannot) pass an exception object + as an argument. The latest exception will automatically be used. + """ + if title == None: title = "Error Report" + if msg == None: + msg = "An error (exception) has occurred in the program." + + codebox(msg, title, exception_format()) + +#------------------------------------------------------------------- +# codebox +#------------------------------------------------------------------- + +def codebox(msg="" + , title=" " + , text="" + ): + """ + Display some text in a monospaced font, with no line wrapping. + This function is suitable for displaying code and text that is + formatted using spaces. + + The text parameter should be a string, or a list or tuple of lines to be + displayed in the textbox. + """ + return textbox(msg, title, text, codebox=1 ) + +#------------------------------------------------------------------- +# textbox +#------------------------------------------------------------------- +def textbox(msg="" + , title=" " + , text="" + , codebox=0 + ): + """ + Display some text in a proportional font with line wrapping at word breaks. + This function is suitable for displaying general written text. + + The text parameter should be a string, or a list or tuple of lines to be + displayed in the textbox. + """ + + if msg == None: msg = "" + if title == None: title = "" + + global boxRoot, __replyButtonText, __widgetTexts, buttonsFrame + global rootWindowPosition + choices = ["OK"] + __replyButtonText = choices[0] + + + boxRoot = Tk() + + boxRoot.protocol('WM_DELETE_WINDOW', denyWindowManagerClose ) + + screen_width = boxRoot.winfo_screenwidth() + screen_height = boxRoot.winfo_screenheight() + root_width = int((screen_width * 0.8)) + root_height = int((screen_height * 0.5)) + root_xpos = int((screen_width * 0.1)) + root_ypos = int((screen_height * 0.05)) + + boxRoot.title(title) + boxRoot.iconname('Dialog') + rootWindowPosition = "+0+0" + boxRoot.geometry(rootWindowPosition) + boxRoot.expand=NO + boxRoot.minsize(root_width, root_height) + rootWindowPosition = "+" + str(root_xpos) + "+" + str(root_ypos) + boxRoot.geometry(rootWindowPosition) + + mainframe = Frame(master=boxRoot) + mainframe.pack(side=TOP, fill=BOTH, expand=YES) + + # ---- put frames in the window ----------------------------------- + # we pack the textboxFrame first, so it will expand first + textboxFrame = Frame(mainframe, borderwidth=3) + textboxFrame.pack(side=BOTTOM , fill=BOTH, expand=YES) + + message_and_buttonsFrame = Frame(mainframe) + message_and_buttonsFrame.pack(side=TOP, fill=X, expand=NO) + + messageFrame = Frame(message_and_buttonsFrame) + messageFrame.pack(side=LEFT, fill=X, expand=YES) + + buttonsFrame = Frame(message_and_buttonsFrame) + buttonsFrame.pack(side=RIGHT, expand=NO) + + # -------------------- put widgets in the frames -------------------- + + # put a textArea in the top frame + if codebox: + character_width = int((root_width * 0.6) / MONOSPACE_FONT_SIZE) + textArea = Text(textboxFrame,height=25,width=character_width, padx="2m", pady="1m") + textArea.configure(wrap=NONE) + textArea.configure(font=(MONOSPACE_FONT_FAMILY, MONOSPACE_FONT_SIZE)) + + else: + character_width = int((root_width * 0.6) / MONOSPACE_FONT_SIZE) + textArea = Text( + textboxFrame + , height=25 + , width=character_width + , padx="2m" + , pady="1m" + ) + textArea.configure(wrap=WORD) + textArea.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) + + + # some simple keybindings for scrolling + mainframe.bind("" , textArea.yview_scroll( 1,PAGES)) + mainframe.bind("", textArea.yview_scroll(-1,PAGES)) + + mainframe.bind("", textArea.xview_scroll( 1,PAGES)) + mainframe.bind("" , textArea.xview_scroll(-1,PAGES)) + + mainframe.bind("", textArea.yview_scroll( 1,UNITS)) + mainframe.bind("" , textArea.yview_scroll(-1,UNITS)) + + + # add a vertical scrollbar to the frame + rightScrollbar = Scrollbar(textboxFrame, orient=VERTICAL, command=textArea.yview) + textArea.configure(yscrollcommand = rightScrollbar.set) + + # add a horizontal scrollbar to the frame + bottomScrollbar = Scrollbar(textboxFrame, orient=HORIZONTAL, command=textArea.xview) + textArea.configure(xscrollcommand = bottomScrollbar.set) + + # pack the textArea and the scrollbars. Note that although we must define + # the textArea first, we must pack it last, so that the bottomScrollbar will + # be located properly. + + # Note that we need a bottom scrollbar only for code. + # Text will be displayed with wordwrap, so we don't need to have a horizontal + # scroll for it. + if codebox: + bottomScrollbar.pack(side=BOTTOM, fill=X) + rightScrollbar.pack(side=RIGHT, fill=Y) + + textArea.pack(side=LEFT, fill=BOTH, expand=YES) + + + # ---------- put a msg widget in the msg frame------------------- + messageWidget = Message(messageFrame, anchor=NW, text=msg, width=int(root_width * 0.9)) + messageWidget.configure(font=(PROPORTIONAL_FONT_FAMILY,PROPORTIONAL_FONT_SIZE)) + messageWidget.pack(side=LEFT, expand=YES, fill=BOTH, padx='1m', pady='1m') + + # put the buttons in the buttonsFrame + okButton = Button(buttonsFrame, takefocus=YES, text="OK", height=1, width=6) + okButton.pack(expand=NO, side=TOP, padx='2m', pady='1m', ipady="1m", ipadx="2m") + + # for the commandButton, bind activation events to the activation event handler + commandButton = okButton + handler = __textboxOK + for selectionEvent in ["Return","Button-1","Escape"]: + commandButton.bind("<%s>" % selectionEvent, handler) + + + # ----------------- the action begins ---------------------------------------- + try: + # load the text into the textArea + if type(text) == type("abc"): pass + else: + try: + text = "".join(text) # convert a list or a tuple to a string + except: + msgbox("Exception when trying to convert "+ str(type(text)) + " to text in textArea") + sys.exit(16) + textArea.insert(END,text, "normal") + + except: + msgbox("Exception when trying to load the textArea.") + sys.exit(16) + + try: + okButton.focus_force() + except: + msgbox("Exception when trying to put focus on okButton.") + sys.exit(16) + + boxRoot.mainloop() + + # this line MUST go before the line that destroys boxRoot + areaText = textArea.get(0.0,END) + boxRoot.destroy() + return areaText # return __replyButtonText + +#------------------------------------------------------------------- +# __textboxOK +#------------------------------------------------------------------- +def __textboxOK(event): + global boxRoot + boxRoot.quit() + + + +#------------------------------------------------------------------- +# diropenbox +#------------------------------------------------------------------- +def diropenbox(msg=None + , title=None + , default=None + ): + """ + A dialog to get a directory name. + Note that the msg argument, if specified, is ignored. + + Returns the name of a directory, or None if user chose to cancel. + + If the "default" argument specifies a directory name, and that + directory exists, then the dialog box will start with that directory. + """ + title=getFileDialogTitle(msg,title) + localRoot = Tk() + localRoot.withdraw() + if not default: default = None + f = tk_FileDialog.askdirectory( + parent=localRoot + , title=title + , initialdir=default + , initialfile=None + ) + localRoot.destroy() + if not f: return None + return os.path.normpath(f) + + + +#------------------------------------------------------------------- +# getFileDialogTitle +#------------------------------------------------------------------- +def getFileDialogTitle(msg + , title + ): + if msg and title: return "%s - %s" % (title,msg) + if msg and not title: return str(msg) + if title and not msg: return str(title) + return None # no message and no title + +#------------------------------------------------------------------- +# class FileTypeObject for use with fileopenbox +#------------------------------------------------------------------- +class FileTypeObject: + def __init__(self,filemask): + if len(filemask) == 0: + raise AssertionError('Filetype argument is empty.') + + self.masks = [] + + if type(filemask) == type("abc"): # a string + self.initializeFromString(filemask) + + elif type(filemask) == type([]): # a list + if len(filemask) < 2: + raise AssertionError('Invalid filemask.\n' + +'List contains less than 2 members: "%s"' % filemask) + else: + self.name = filemask[-1] + self.masks = list(filemask[:-1] ) + else: + raise AssertionError('Invalid filemask: "%s"' % filemask) + + def __eq__(self,other): + if self.name == other.name: return True + return False + + def add(self,other): + for mask in other.masks: + if mask in self.masks: pass + else: self.masks.append(mask) + + def toTuple(self): + return (self.name,tuple(self.masks)) + + def isAll(self): + if self.name == "All files": return True + return False + + def initializeFromString(self, filemask): + # remove everything except the extension from the filemask + self.ext = os.path.splitext(filemask)[1] + if self.ext == "" : self.ext = ".*" + if self.ext == ".": self.ext = ".*" + self.name = self.getName() + self.masks = ["*" + self.ext] + + def getName(self): + e = self.ext + if e == ".*" : return "All files" + if e == ".txt": return "Text files" + if e == ".py" : return "Python files" + if e == ".pyc" : return "Python files" + if e == ".xls": return "Excel files" + if e.startswith("."): + return e[1:].upper() + " files" + return e.upper() + " files" + + +#------------------------------------------------------------------- +# fileopenbox +#------------------------------------------------------------------- +def fileopenbox(msg=None + , title=None + , default="*" + , filetypes=None + ): + """ + A dialog to get a file name. + + About the "default" argument + ============================ + The "default" argument specifies a filepath that (normally) + contains one or more wildcards. + fileopenbox will display only files that match the default filepath. + If omitted, defaults to "*" (all files in the current directory). + + WINDOWS EXAMPLE:: + ...default="c:/myjunk/*.py" + will open in directory c:\myjunk\ and show all Python files. + + WINDOWS EXAMPLE:: + ...default="c:/myjunk/test*.py" + will open in directory c:\myjunk\ and show all Python files + whose names begin with "test". + + + Note that on Windows, fileopenbox automatically changes the path + separator to the Windows path separator (backslash). + + About the "filetypes" argument + ============================== + If specified, it should contain a list of items, + where each item is either:: + - a string containing a filemask # e.g. "*.txt" + - a list of strings, where all of the strings except the last one + are filemasks (each beginning with "*.", + such as "*.txt" for text files, "*.py" for Python files, etc.). + and the last string contains a filetype description + + EXAMPLE:: + filetypes = ["*.css", ["*.htm", "*.html", "HTML files"] ] + + NOTE THAT + ========= + + If the filetypes list does not contain ("All files","*"), + it will be added. + + If the filetypes list does not contain a filemask that includes + the extension of the "default" argument, it will be added. + For example, if default="*abc.py" + and no filetypes argument was specified, then + "*.py" will automatically be added to the filetypes argument. + + @rtype: string or None + @return: the name of a file, or None if user chose to cancel + + @arg msg: the msg to be displayed. + @arg title: the window title + @arg default: filepath with wildcards + @arg filetypes: filemasks that a user can choose, e.g. "*.txt" + """ + localRoot = Tk() + localRoot.withdraw() + + initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes) + + #------------------------------------------------------------ + # if initialfile contains no wildcards; we don't want an + # initial file. It won't be used anyway. + # Also: if initialbase is simply "*", we don't want an + # initialfile; it is not doing any useful work. + #------------------------------------------------------------ + if (initialfile.find("*") < 0) and (initialfile.find("?") < 0): + initialfile = None + elif initialbase == "*": + initialfile = None + + f = tk_FileDialog.askopenfilename(parent=localRoot + , title=getFileDialogTitle(msg,title) + , initialdir=initialdir + , initialfile=initialfile + , filetypes=filetypes + ) + + localRoot.destroy() + + if not f: return None + return os.path.normpath(f) + + +#------------------------------------------------------------------- +# filesavebox +#------------------------------------------------------------------- +def filesavebox(msg=None + , title=None + , default="" + , filetypes=None + ): + """ + A file to get the name of a file to save. + Returns the name of a file, or None if user chose to cancel. + + The "default" argument should contain a filename (i.e. the + current name of the file to be saved). It may also be empty, + or contain a filemask that includes wildcards. + + The "filetypes" argument works like the "filetypes" argument to + fileopenbox. + """ + + localRoot = Tk() + localRoot.withdraw() + + initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes) + + f = tk_FileDialog.asksaveasfilename(parent=localRoot + , title=getFileDialogTitle(msg,title) + , initialfile=initialfile + , initialdir=initialdir + , filetypes=filetypes + ) + localRoot.destroy() + if not f: return None + return os.path.normpath(f) + + +#------------------------------------------------------------------- +# +# fileboxSetup +# +#------------------------------------------------------------------- +def fileboxSetup(default,filetypes): + if not default: default = os.path.join(".","*") + initialdir, initialfile = os.path.split(default) + if not initialdir : initialdir = "." + if not initialfile: initialfile = "*" + initialbase, initialext = os.path.splitext(initialfile) + initialFileTypeObject = FileTypeObject(initialfile) + + allFileTypeObject = FileTypeObject("*") + ALL_filetypes_was_specified = False + + if not filetypes: filetypes= [] + filetypeObjects = [] + + for filemask in filetypes: + fto = FileTypeObject(filemask) + + if fto.isAll(): + ALL_filetypes_was_specified = True # remember this + + if fto == initialFileTypeObject: + initialFileTypeObject.add(fto) # add fto to initialFileTypeObject + else: + filetypeObjects.append(fto) + + #------------------------------------------------------------------ + # make sure that the list of filetypes includes the ALL FILES type. + #------------------------------------------------------------------ + if ALL_filetypes_was_specified: + pass + elif allFileTypeObject == initialFileTypeObject: + pass + else: + filetypeObjects.insert(0,allFileTypeObject) + #------------------------------------------------------------------ + # Make sure that the list includes the initialFileTypeObject + # in the position in the list that will make it the default. + # This changed between Python version 2.5 and 2.6 + #------------------------------------------------------------------ + if len(filetypeObjects) == 0: + filetypeObjects.append(initialFileTypeObject) + + if initialFileTypeObject in (filetypeObjects[0], filetypeObjects[-1]): + pass + else: + if runningPython26: + filetypeObjects.append(initialFileTypeObject) + else: + filetypeObjects.insert(0,initialFileTypeObject) + + filetypes = [fto.toTuple() for fto in filetypeObjects] + + return initialbase, initialfile, initialdir, filetypes + +#------------------------------------------------------------------- +# utility routines +#------------------------------------------------------------------- +# These routines are used by several other functions in the EasyGui module. + +def __buttonEvent(event): + """ + Handle an event that is generated by a person clicking a button. + """ + global boxRoot, __widgetTexts, __replyButtonText + __replyButtonText = __widgetTexts[event.widget] + boxRoot.quit() # quit the main loop + + +def __put_buttons_in_buttonframe(choices): + """Put the buttons in the buttons frame + """ + global __widgetTexts, __firstWidget, buttonsFrame + + __firstWidget = None + __widgetTexts = {} + + i = 0 + + for buttonText in choices: + tempButton = Button(buttonsFrame, takefocus=1, text=buttonText) + bindArrows(tempButton) + tempButton.pack(expand=YES, side=LEFT, padx='1m', pady='1m', ipadx='2m', ipady='1m') + + # remember the text associated with this widget + __widgetTexts[tempButton] = buttonText + + # remember the first widget, so we can put the focus there + if i == 0: + __firstWidget = tempButton + i = 1 + + # for the commandButton, bind activation events to the activation event handler + commandButton = tempButton + handler = __buttonEvent + for selectionEvent in STANDARD_SELECTION_EVENTS: + commandButton.bind("<%s>" % selectionEvent, handler) + +#----------------------------------------------------------------------- +# +# class EgStore +# +#----------------------------------------------------------------------- +class EgStore: + r""" +A class to support persistent storage. + +You can use EgStore to support the storage and retrieval +of user settings for an EasyGui application. + + +# Example A +#----------------------------------------------------------------------- +# define a class named Settings as a subclass of EgStore +#----------------------------------------------------------------------- +class Settings(EgStore): +:: + def __init__(self, filename): # filename is required + #------------------------------------------------- + # Specify default/initial values for variables that + # this particular application wants to remember. + #------------------------------------------------- + self.userId = "" + self.targetServer = "" + + #------------------------------------------------- + # For subclasses of EgStore, these must be + # the last two statements in __init__ + #------------------------------------------------- + self.filename = filename # this is required + self.restore() # restore values from the storage file if possible + + + +# Example B +#----------------------------------------------------------------------- +# create settings, a persistent Settings object +#----------------------------------------------------------------------- +settingsFile = "myApp_settings.txt" +settings = Settings(settingsFile) + +user = "obama_barak" +server = "whitehouse1" +settings.userId = user +settings.targetServer = server +settings.store() # persist the settings + +# run code that gets a new value for userId, and persist the settings +user = "biden_joe" +settings.userId = user +settings.store() + + +# Example C +#----------------------------------------------------------------------- +# recover the Settings instance, change an attribute, and store it again. +#----------------------------------------------------------------------- +settings = Settings(settingsFile) +settings.userId = "vanrossum_g" +settings.store() + +""" + def __init__(self, filename): # obtaining filename is required + self.filename = None + raise NotImplementedError() + + def restore(self): + """ + Set the values of whatever attributes are recoverable + from the pickle file. + + Populate the attributes (the __dict__) of the EgStore object + from the attributes (the __dict__) of the pickled object. + + If the pickled object has attributes that have been initialized + in the EgStore object, then those attributes of the EgStore object + will be replaced by the values of the corresponding attributes + in the pickled object. + + If the pickled object is missing some attributes that have + been initialized in the EgStore object, then those attributes + of the EgStore object will retain the values that they were + initialized with. + + If the pickled object has some attributes that were not + initialized in the EgStore object, then those attributes + will be ignored. + + IN SUMMARY: + + After the recover() operation, the EgStore object will have all, + and only, the attributes that it had when it was initialized. + + Where possible, those attributes will have values recovered + from the pickled object. + """ + if not os.path.exists(self.filename): return self + if not os.path.isfile(self.filename): return self + + try: + f = open(self.filename,"rb") + unpickledObject = pickle.load(f) + f.close() + + for key in list(self.__dict__.keys()): + default = self.__dict__[key] + self.__dict__[key] = unpickledObject.__dict__.get(key,default) + except: + pass + + return self + + def store(self): + """ + Save the attributes of the EgStore object to a pickle file. + Note that if the directory for the pickle file does not already exist, + the store operation will fail. + """ + f = open(self.filename, "wb") + pickle.dump(self, f) + f.close() + + + def kill(self): + """ + Delete my persistent file (i.e. pickle file), if it exists. + """ + if os.path.isfile(self.filename): + os.remove(self.filename) + return + + def __str__(self): + """ + return my contents as a string in an easy-to-read format. + """ + # find the length of the longest attribute name + longest_key_length = 0 + keys = [] + for key in self.__dict__.keys(): + keys.append(key) + longest_key_length = max(longest_key_length, len(key)) + + keys.sort() # sort the attribute names + lines = [] + for key in keys: + value = self.__dict__[key] + key = key.ljust(longest_key_length) + lines.append("%s : %s\n" % (key,repr(value)) ) + return "".join(lines) # return a string showing the attributes + + + + +#----------------------------------------------------------------------- +# +# test/demo easygui +# +#----------------------------------------------------------------------- +def egdemo(): + """ + Run the EasyGui demo. + """ + # clear the console + writeln("\n" * 100) + + intro_message = ("Pick the kind of box that you wish to demo.\n" + + "\n * Python version " + sys.version + + "\n * EasyGui version " + egversion + + "\n * Tk version " + str(TkVersion) + ) + + #========================================== END DEMONSTRATION DATA + + + while 1: # do forever + choices = [ + "msgbox", + "buttonbox", + "buttonbox(image) -- a buttonbox that displays an image", + "choicebox", + "multchoicebox", + "textbox", + "ynbox", + "ccbox", + "enterbox", + "enterbox(image) -- an enterbox that displays an image", + "exceptionbox", + "codebox", + "integerbox", + "boolbox", + "indexbox", + "filesavebox", + "fileopenbox", + "passwordbox", + "multenterbox", + "multpasswordbox", + "diropenbox", + "About EasyGui", + " Help" + ] + choice = choicebox(msg=intro_message + , title="EasyGui " + egversion + , choices=choices) + + if not choice: return + + reply = choice.split() + + if reply[0] == "msgbox": + reply = msgbox("short msg", "This is a long title") + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "About": + reply = abouteasygui() + + elif reply[0] == "Help": + _demo_help() + + elif reply[0] == "buttonbox": + reply = buttonbox() + writeln("Reply was: %s" % repr(reply)) + + title = "Demo of Buttonbox with many, many buttons!" + msg = "This buttonbox shows what happens when you specify too many buttons." + reply = buttonbox(msg=msg, title=title, choices=choices) + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "buttonbox(image)": + _demo_buttonbox_with_image() + + elif reply[0] == "boolbox": + reply = boolbox() + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "enterbox": + image = "python_and_check_logo.gif" + message = "Enter the name of your best friend."\ + "\n(Result will be stripped.)" + reply = enterbox(message, "Love!", " Suzy Smith ") + writeln("Reply was: %s" % repr(reply)) + + message = "Enter the name of your best friend."\ + "\n(Result will NOT be stripped.)" + reply = enterbox(message, "Love!", " Suzy Smith ",strip=False) + writeln("Reply was: %s" % repr(reply)) + + reply = enterbox("Enter the name of your worst enemy:", "Hate!") + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "enterbox(image)": + image = "python_and_check_logo.gif" + message = "What kind of snake is this?" + reply = enterbox(message, "Quiz",image=image) + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "exceptionbox": + try: + thisWillCauseADivideByZeroException = 1/0 + except: + exceptionbox() + + elif reply[0] == "integerbox": + reply = integerbox( + "Enter a number between 3 and 333", + "Demo: integerbox WITH a default value", + 222, 3, 333) + writeln("Reply was: %s" % repr(reply)) + + reply = integerbox( + "Enter a number between 0 and 99", + "Demo: integerbox WITHOUT a default value" + ) + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "diropenbox" : _demo_diropenbox() + elif reply[0] == "fileopenbox": _demo_fileopenbox() + elif reply[0] == "filesavebox": _demo_filesavebox() + + elif reply[0] == "indexbox": + title = reply[0] + msg = "Demo of " + reply[0] + choices = ["Choice1", "Choice2", "Choice3", "Choice4"] + reply = indexbox(msg, title, choices) + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "passwordbox": + reply = passwordbox("Demo of password box WITHOUT default" + + "\n\nEnter your secret password", "Member Logon") + writeln("Reply was: %s" % str(reply)) + + reply = passwordbox("Demo of password box WITH default" + + "\n\nEnter your secret password", "Member Logon", "alfie") + writeln("Reply was: %s" % str(reply)) + + elif reply[0] == "multenterbox": + msg = "Enter your personal information" + title = "Credit Card Application" + fieldNames = ["Name","Street Address","City","State","ZipCode"] + fieldValues = [] # we start with blanks for the values + fieldValues = multenterbox(msg,title, fieldNames) + + # make sure that none of the fields was left blank + while 1: + if fieldValues == None: break + errmsg = "" + for i in range(len(fieldNames)): + if fieldValues[i].strip() == "": + errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) + if errmsg == "": break # no problems found + fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) + + writeln("Reply was: %s" % str(fieldValues)) + + elif reply[0] == "multpasswordbox": + msg = "Enter logon information" + title = "Demo of multpasswordbox" + fieldNames = ["Server ID", "User ID", "Password"] + fieldValues = [] # we start with blanks for the values + fieldValues = multpasswordbox(msg,title, fieldNames) + + # make sure that none of the fields was left blank + while 1: + if fieldValues == None: break + errmsg = "" + for i in range(len(fieldNames)): + if fieldValues[i].strip() == "": + errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) + if errmsg == "": break # no problems found + fieldValues = multpasswordbox(errmsg, title, fieldNames, fieldValues) + + writeln("Reply was: %s" % str(fieldValues)) + + elif reply[0] == "ynbox": + title = "Demo of ynbox" + msg = "Were you expecting the Spanish Inquisition?" + reply = ynbox(msg, title) + writeln("Reply was: %s" % repr(reply)) + if reply: + msgbox("NOBODY expects the Spanish Inquisition!", "Wrong!") + + elif reply[0] == "ccbox": + title = "Demo of ccbox" + reply = ccbox(msg,title) + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "choicebox": + title = "Demo of choicebox" + longchoice = "This is an example of a very long option which you may or may not wish to choose."*2 + listChoices = ["nnn", "ddd", "eee", "fff", "aaa", longchoice + , "aaa", "bbb", "ccc", "ggg", "hhh", "iii", "jjj", "kkk", "LLL", "mmm" , "nnn", "ooo", "ppp", "qqq", "rrr", "sss", "ttt", "uuu", "vvv"] + + msg = "Pick something. " + ("A wrapable sentence of text ?! "*30) + "\nA separate line of text."*6 + reply = choicebox(msg=msg, choices=listChoices) + writeln("Reply was: %s" % repr(reply)) + + msg = "Pick something. " + reply = choicebox(msg=msg, title=title, choices=listChoices) + writeln("Reply was: %s" % repr(reply)) + + msg = "Pick something. " + reply = choicebox(msg="The list of choices is empty!", choices=[]) + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "multchoicebox": + listChoices = ["aaa", "bbb", "ccc", "ggg", "hhh", "iii", "jjj", "kkk" + , "LLL", "mmm" , "nnn", "ooo", "ppp", "qqq" + , "rrr", "sss", "ttt", "uuu", "vvv"] + + msg = "Pick as many choices as you wish." + reply = multchoicebox(msg,"Demo of multchoicebox", listChoices) + writeln("Reply was: %s" % repr(reply)) + + elif reply[0] == "textbox": _demo_textbox(reply[0]) + elif reply[0] == "codebox": _demo_codebox(reply[0]) + + else: + msgbox("Choice\n\n" + choice + "\n\nis not recognized", "Program Logic Error") + return + + +def _demo_textbox(reply): + text_snippet = ((\ +"""It was the best of times, and it was the worst of times. The rich ate cake, and the poor had cake recommended to them, but wished only for enough cash to buy bread. The time was ripe for revolution! """ \ +*5)+"\n\n")*10 + title = "Demo of textbox" + msg = "Here is some sample text. " * 16 + reply = textbox(msg, title, text_snippet) + writeln("Reply was: %s" % str(reply)) + +def _demo_codebox(reply): + code_snippet = ("dafsdfa dasflkj pp[oadsij asdfp;ij asdfpjkop asdfpok asdfpok asdfpok"*3) +"\n"+\ +"""# here is some dummy Python code +for someItem in myListOfStuff: + do something(someItem) + do something() + do something() + if somethingElse(someItem): + doSomethingEvenMoreInteresting() + +"""*16 + msg = "Here is some sample code. " * 16 + reply = codebox(msg, "Code Sample", code_snippet) + writeln("Reply was: %s" % repr(reply)) + + +def _demo_buttonbox_with_image(): + + msg = "Do you like this picture?\nIt is " + choices = ["Yes","No","No opinion"] + + for image in [ + "python_and_check_logo.gif" + ,"python_and_check_logo.jpg" + ,"python_and_check_logo.png" + ,"zzzzz.gif"]: + + reply=buttonbox(msg + image,image=image,choices=choices) + writeln("Reply was: %s" % repr(reply)) + + +def _demo_help(): + savedStdout = sys.stdout # save the sys.stdout file object + sys.stdout = capturedOutput = StringIO() + help("easygui") + sys.stdout = savedStdout # restore the sys.stdout file object + codebox("EasyGui Help",text=capturedOutput.getvalue()) + +def _demo_filesavebox(): + filename = "myNewFile.txt" + title = "File SaveAs" + msg ="Save file as:" + + f = filesavebox(msg,title,default=filename) + writeln("You chose to save file: %s" % f) + +def _demo_diropenbox(): + title = "Demo of diropenbox" + msg = "Pick the directory that you wish to open." + d = diropenbox(msg, title) + writeln("You chose directory...: %s" % d) + + d = diropenbox(msg, title,default="./") + writeln("You chose directory...: %s" % d) + + d = diropenbox(msg, title,default="c:/") + writeln("You chose directory...: %s" % d) + + +def _demo_fileopenbox(): + msg = "Python files" + title = "Open files" + default="*.py" + f = fileopenbox(msg,title,default=default) + writeln("You chose to open file: %s" % f) + + default="./*.gif" + filetypes = ["*.jpg",["*.zip","*.tgs","*.gz", "Archive files"],["*.htm", "*.html","HTML files"]] + f = fileopenbox(msg,title,default=default,filetypes=filetypes) + writeln("You chose to open file: %s" % f) + + """#deadcode -- testing ---------------------------------------- + f = fileopenbox(None,None,default=default) + writeln("You chose to open file: %s" % f) + + f = fileopenbox(None,title,default=default) + writeln("You chose to open file: %s" % f) + + f = fileopenbox(msg,None,default=default) + writeln("You chose to open file: %s" % f) + + f = fileopenbox(default=default) + writeln("You chose to open file: %s" % f) + + f = fileopenbox(default=None) + writeln("You chose to open file: %s" % f) + #----------------------------------------------------deadcode """ + + +def _dummy(): + pass + +EASYGUI_ABOUT_INFORMATION = ''' +======================================================================== +0.96(2010-08-29) +======================================================================== +This version fixes some problems with version independence. + +BUG FIXES +------------------------------------------------------ + * A statement with Python 2.x-style exception-handling syntax raised + a syntax error when running under Python 3.x. + Thanks to David Williams for reporting this problem. + + * Under some circumstances, PIL was unable to display non-gif images + that it should have been able to display. + The cause appears to be non-version-independent import syntax. + PIL modules are now imported with a version-independent syntax. + Thanks to Horst Jens for reporting this problem. + +LICENSE CHANGE +------------------------------------------------------ +Starting with this version, EasyGui is licensed under what is generally known as +the "modified BSD license" (aka "revised BSD", "new BSD", "3-clause BSD"). +This license is GPL-compatible but less restrictive than GPL. +Earlier versions were licensed under the Creative Commons Attribution License 2.0. + + +======================================================================== +0.95(2010-06-12) +======================================================================== + +ENHANCEMENTS +------------------------------------------------------ + * Previous versions of EasyGui could display only .gif image files using the + msgbox "image" argument. This version can now display all image-file formats + supported by PIL the Python Imaging Library) if PIL is installed. + If msgbox is asked to open a non-gif image file, it attempts to import + PIL and to use PIL to convert the image file to a displayable format. + If PIL cannot be imported (probably because PIL is not installed) + EasyGui displays an error message saying that PIL must be installed in order + to display the image file. + + Note that + http://www.pythonware.com/products/pil/ + says that PIL doesn't yet support Python 3.x. + + +======================================================================== +0.94(2010-06-06) +======================================================================== + +ENHANCEMENTS +------------------------------------------------------ + * The codebox and textbox functions now return the contents of the box, rather + than simply the name of the button ("Yes"). This makes it possible to use + codebox and textbox as data-entry widgets. A big "thank you!" to Dominic + Comtois for requesting this feature, patiently explaining his requirement, + and helping to discover the tkinter techniques to implement it. + + NOTE THAT in theory this change breaks backward compatibility. But because + (in previous versions of EasyGui) the value returned by codebox and textbox + was meaningless, no application should have been checking it. So in actual + practice, this change should not break backward compatibility. + + * Added support for SPACEBAR to command buttons. Now, when keyboard + focus is on a command button, a press of the SPACEBAR will act like + a press of the ENTER key; it will activate the command button. + + * Added support for keyboard navigation with the arrow keys (up,down,left,right) + to the fields and buttons in enterbox, multenterbox and multpasswordbox, + and to the buttons in choicebox and all buttonboxes. + + * added highlightthickness=2 to entry fields in multenterbox and + multpasswordbox. Now it is easier to tell which entry field has + keyboard focus. + + +BUG FIXES +------------------------------------------------------ + * In EgStore, the pickle file is now opened with "rb" and "wb" rather than + with "r" and "w". This change is necessary for compatibility with Python 3+. + Thanks to Marshall Mattingly for reporting this problem and providing the fix. + + * In integerbox, the actual argument names did not match the names described + in the docstring. Thanks to Daniel Zingaro of at University of Toronto for + reporting this problem. + + * In integerbox, the "argLowerBound" and "argUpperBound" arguments have been + renamed to "lowerbound" and "upperbound" and the docstring has been corrected. + + NOTE THAT THIS CHANGE TO THE ARGUMENT-NAMES BREAKS BACKWARD COMPATIBILITY. + If argLowerBound or argUpperBound are used, an AssertionError with an + explanatory error message is raised. + + * In choicebox, the signature to choicebox incorrectly showed choicebox as + accepting a "buttons" argument. The signature has been fixed. + + +======================================================================== +0.93(2009-07-07) +======================================================================== + +ENHANCEMENTS +------------------------------------------------------ + + * Added exceptionbox to display stack trace of exceptions + + * modified names of some font-related constants to make it + easier to customize them + + +======================================================================== +0.92(2009-06-22) +======================================================================== + +ENHANCEMENTS +------------------------------------------------------ + + * Added EgStore class to to provide basic easy-to-use persistence. + +BUG FIXES +------------------------------------------------------ + + * Fixed a bug that was preventing Linux users from copying text out of + a textbox and a codebox. This was not a problem for Windows users. + +''' + +def abouteasygui(): + """ + shows the easygui revision history + """ + codebox("About EasyGui\n"+egversion,"EasyGui",EASYGUI_ABOUT_INFORMATION) + return None + + + +if __name__ == '__main__': + if True: + egdemo() + else: + # test the new root feature + root = Tk() + msg = """This is a test of a main Tk() window in which we will place an easygui msgbox. + It will be an interesting experiment.\n\n""" + messageWidget = Message(root, text=msg, width=1000) + messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m') + messageWidget = Message(root, text=msg, width=1000) + messageWidget.pack(side=TOP, expand=YES, fill=X, padx='3m', pady='3m') + + + msgbox("this is a test of passing in boxRoot", root=root) + msgbox("this is a second test of passing in boxRoot", root=root) + + reply = enterbox("Enter something", root=root) + writeln("You wrote:", reply) + + reply = enterbox("Enter something else", root=root) + writeln("You wrote:", reply) + root.destroy() diff --git a/oletools/thirdparty/xxxswf/LICENSE.txt b/oletools/thirdparty/xxxswf/LICENSE.txt new file mode 100644 index 0000000..9c42dab --- /dev/null +++ b/oletools/thirdparty/xxxswf/LICENSE.txt @@ -0,0 +1,3 @@ +xxxswf.py is published by Alexander Hanel on +http://hooked-on-mnemonics.blogspot.nl/2011/12/xxxswfpy.html +without explicit license. \ No newline at end of file diff --git a/oletools/thirdparty/xxxswf/__init__.py b/oletools/thirdparty/xxxswf/__init__.py new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/oletools/thirdparty/xxxswf/__init__.py diff --git a/oletools/thirdparty/xxxswf/xxxswf.py b/oletools/thirdparty/xxxswf/xxxswf.py new file mode 100644 index 0000000..1a47878 --- /dev/null +++ b/oletools/thirdparty/xxxswf/xxxswf.py @@ -0,0 +1,371 @@ +# xxxswf.py was created by alexander dot hanel at gmail dot com +# version 0.1 +# Date - 12-07-2011 +# To do list +# - Tag Parser +# - ActionScript Decompiler + +import fnmatch +import hashlib +import imp +import math +import os +import re +import struct +import sys +import time +from StringIO import StringIO +from optparse import OptionParser +import zlib + +def checkMD5(md5): +# checks if MD5 has been seen in MD5 Dictionary +# MD5Dict contains the MD5 and the CVE +# For { 'MD5':'CVE', 'MD5-1':'CVE-1', 'MD5-2':'CVE-2'} + MD5Dict = {'c46299a5015c6d31ad5766cb49e4ab4b':'CVE-XXXX-XXXX'} + if MD5Dict.get(md5): + print '\t[BAD] MD5 Match on', MD5Dict.get(md5) + return + +def bad(f): + for idx, x in enumerate(findSWF(f)): + tmp = verifySWF(f,x) + if tmp != None: + yaraScan(tmp) + checkMD5(hashBuff(tmp)) + return + +def yaraScan(d): +# d = buffer of the read file +# Scans SWF using Yara + # test if yara module is installed + # if not Yara can be downloaded from http://code.google.com/p/yara-project/ + try: + imp.find_module('yara') + import yara + except ImportError: + print '\t[ERROR] Yara module not installed - aborting scan' + return + # test for yara compile errors + try: + r = yara.compile(r'rules.yar') + except: + pass + print '\t[ERROR] Yara compile error - aborting scan' + return + # get matches + m = r.match(data=d) + # print matches + for X in m: + print '\t[BAD] Yara Signature Hit:', X + return + +def findSWF(d): +# d = buffer of the read file +# Search for SWF Header Sigs in files + return [tmp.start() for tmp in re.finditer('CWS|FWS', d.read())] + +def hashBuff(d): +# d = buffer of the read file +# This function hashes the buffer +# source: http://stackoverflow.com/q/5853830 + if type(d) is str: + d = StringIO(d) + md5 = hashlib.md5() + while True: + data = d.read(128) + if not data: + break + md5.update(data) + return md5.hexdigest() + +def verifySWF(f,addr): + # Start of SWF + f.seek(addr) + # Read Header + header = f.read(3) + # Read Version + ver = struct.unpack(' 20: + print ' - [ERROR] Invalid SWF Version' + return None + + if 'CWS' in header: + try: + f.read(3) + tmp = 'FWS' + f.read(5) + zlib.decompress(f.read()) + print ' - CWS Header' + return tmp + + except: + pass + print '- [ERROR]: Zlib decompression error. Invalid CWS SWF' + return None + + elif 'FWS' in header: + try: + tmp = f.read(size) + print ' - FWS Header' + return tmp + + except: + pass + print ' - [ERROR] Invalid SWF Size' + return None + + else: + print ' - [Error] Logic Error Blame Programmer' + return None + +def headerInfo(f): +# f is the already opended file handle +# Yes, the format is is a rip off SWFDump. Can you blame me? Their tool is awesome. + # SWFDump FORMAT + # [HEADER] File version: 8 + # [HEADER] File is zlib compressed. Ratio: 52% + # [HEADER] File size: 37536 + # [HEADER] Frame rate: 18.000000 + # [HEADER] Frame count: 323 + # [HEADER] Movie width: 217.00 + # [HEADER] Movie height: 85.00 + if type(f) is str: + f = StringIO(f) + sig = f.read(3) + print '\t[HEADER] File header:', sig + if 'C' in sig: + print '\t[HEADER] File is zlib compressed.' + version = struct.unpack('> 3 + print '\t[HEADER] Rect Nbit:', nbit + # Curretely the nbit is static at 15. This could be modified in the + # future. If larger than 9 this will break the struct unpack. Will have + # to revist must be a more effective way to deal with bits. Tried to keep + # the algo but damn this is ugly... + f.seek(ta) + rect = struct.unpack('>Q', f.read(int(math.ceil((nbit*4)/8.0))))[0] + tmp = struct.unpack('>7)[2:].zfill(1) + # bin requires Python 2.6 or higher + # skips string '0b' and the nbit + rect = bin(rect)[7:] + xmin = int(rect[0:nbit-1],2) + print '\t[HEADER] Rect Xmin:', xmin + xmax = int(rect[nbit:(nbit*2)-1],2) + print '\t[HEADER] Rect Xmax:', xmax + ymin = int(rect[nbit*2:(nbit*3)-1],2) + print '\t[HEADER] Rect Ymin:', ymin + # one bit needs to be added, my math might be off here + ymax = int(rect[nbit*3:(nbit*4)-1] + str(tmp) ,2) + print '\t[HEADER] Rect Ymax:', ymax + framerate = struct.unpack('