Merge ../MormonChannel
authorepage <epage@1a2a05ed-a369-0410-af37-574249971199>
Fri, 28 May 2010 02:42:35 +0000 (02:42 +0000)
committerepage <epage@1a2a05ed-a369-0410-af37-574249971199>
Fri, 28 May 2010 02:42:35 +0000 (02:42 +0000)
git-svn-id: https://dev.lds.org/svn/mormonchannel/trunk/maemo/trunk@501 1a2a05ed-a369-0410-af37-574249971199

81 files changed:
.gitignore [new file with mode: 0644]
Makefile [new file with mode: 0644]
README [new file with mode: 0644]
data/COPYRIGHT [new file with mode: 0644]
data/LDSHomeIcon.png [new file with mode: 0644]
data/MormonMessagesIcon.png [new file with mode: 0644]
data/ScripturesWebIcon.png [new file with mode: 0644]
data/conference.png [new file with mode: 0644]
data/conference_bg.png [new file with mode: 0644]
data/home.png [new file with mode: 0644]
data/icon.png [new file with mode: 0644]
data/loading.gif [new file with mode: 0644]
data/magazine_bg.png [new file with mode: 0644]
data/magazines.png [new file with mode: 0644]
data/more.png [new file with mode: 0644]
data/next.png [new file with mode: 0644]
data/nomagazineimage.png [new file with mode: 0644]
data/pause.png [new file with mode: 0644]
data/pausepressed.png [new file with mode: 0644]
data/play.png [new file with mode: 0644]
data/playpressed.png [new file with mode: 0644]
data/prev.png [new file with mode: 0644]
data/radio.png [new file with mode: 0644]
data/radio_header.png [new file with mode: 0644]
data/scripture_bg.png [new file with mode: 0644]
data/scriptures.png [new file with mode: 0644]
data/small_home.png [new file with mode: 0644]
data/small_next.png [new file with mode: 0644]
data/small_pause.png [new file with mode: 0644]
data/small_pausepressed.png [new file with mode: 0644]
data/small_play.png [new file with mode: 0644]
data/small_playpressed.png [new file with mode: 0644]
data/small_prev.png [new file with mode: 0644]
data/small_stop.png [new file with mode: 0644]
data/small_stoppressed.png [new file with mode: 0644]
data/stop.png [new file with mode: 0644]
data/stoppressed.png [new file with mode: 0644]
src/LICENSE [new file with mode: 0644]
src/MormonChannel.py [new file with mode: 0755]
src/__init__.py [new file with mode: 0644]
src/backend.py [new file with mode: 0755]
src/banners.py [new file with mode: 0644]
src/browser_emu.py [new file with mode: 0644]
src/call_monitor.py [new file with mode: 0644]
src/constants.py [new file with mode: 0644]
src/gtk_toolbox.py [new file with mode: 0644]
src/hildonize.py [new file with mode: 0644]
src/imagestore.py [new file with mode: 0644]
src/mormonchannel_gtk.py [new file with mode: 0755]
src/player.py [new file with mode: 0644]
src/presenter.py [new file with mode: 0644]
src/stream.py [new file with mode: 0644]
src/stream_index.py [new file with mode: 0644]
src/util/__init__.py [new file with mode: 0644]
src/util/algorithms.py [new file with mode: 0644]
src/util/concurrent.py [new file with mode: 0644]
src/util/coroutines.py [new file with mode: 0755]
src/util/go_utils.py [new file with mode: 0644]
src/util/io.py [new file with mode: 0644]
src/util/linux.py [new file with mode: 0644]
src/util/misc.py [new file with mode: 0644]
src/util/overloading.py [new file with mode: 0644]
src/util/time_utils.py [new file with mode: 0644]
src/util/tp_utils.py [new file with mode: 0644]
src/windows/__init__.py [new file with mode: 0644]
src/windows/_base.py [new file with mode: 0644]
src/windows/conferences.py [new file with mode: 0644]
src/windows/magazines.py [new file with mode: 0644]
src/windows/radio.py [new file with mode: 0644]
src/windows/scriptures.py [new file with mode: 0644]
src/windows/source.py [new file with mode: 0644]
support/builddeb.py [new file with mode: 0755]
support/fake_py2deb.py [new file with mode: 0644]
support/py2deb.py [new file with mode: 0644]
support/pylint.rc [new file with mode: 0644]
support/test_syntax.py [new file with mode: 0755]
support/todo.py [new file with mode: 0755]
tests/test_utils.py [new file with mode: 0644]
www/download.html [new file with mode: 0644]
www/index.html [new file with mode: 0644]
www/screenshots.html [new file with mode: 0644]

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..1948f58
--- /dev/null
@@ -0,0 +1,2 @@
+*.pyc
+.profile
diff --git a/Makefile b/Makefile
new file mode 100644 (file)
index 0000000..223fd3b
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,106 @@
+PROJECT_NAME=MormonChannel
+SOURCE_PATH=src
+SOURCE=$(shell find $(SOURCE_PATH) -iname "*.py")
+PROGRAM=$(SOURCE_PATH)/mormonchannel_gtk.py
+DATA_TYPES=*.ini *.map *.glade *.png
+DATA=$(foreach type, $(DATA_TYPES), $(shell find $(SOURCE_PATH) -iname "$(type)"))
+OBJ=$(SOURCE:.py=.pyc)
+BUILD_PATH=./build
+TAG_FILE=~/.ctags/$(PROJECT_NAME).tags
+TODO_FILE=./TODO
+
+DEBUGGER=winpdb
+UNIT_TEST=nosetests --with-doctest -w .
+SYNTAX_TEST=support/test_syntax.py
+STYLE_TEST=../../Python/tools/pep8.py --ignore=W191,E501
+LINT_RC=./support/pylint.rc
+LINT=pylint --rcfile=$(LINT_RC)
+PROFILE_GEN=python -m cProfile -o .profile
+PROFILE_VIEW=python -m pstats .profile
+TODO_FINDER=support/todo.py
+CTAGS=ctags-exuberant
+
+.PHONY: all run profile debug test build lint tags todo clean distclean
+
+all: test
+
+run: $(OBJ)
+       $(PROGRAM)
+
+profile: $(OBJ)
+       $(PROFILE_GEN) $(PROGRAM)
+       $(PROFILE_VIEW)
+
+debug: $(OBJ)
+       $(DEBUGGER) $(PROGRAM)
+
+test: $(OBJ)
+       $(UNIT_TEST)
+
+package: $(OBJ)
+       rm -Rf $(BUILD_PATH)
+
+       mkdir -p $(BUILD_PATH)/generic
+       cp $(SOURCE_PATH)/constants.py  $(BUILD_PATH)/generic
+       cp $(SOURCE_PATH)/$(PROJECT_NAME).py  $(BUILD_PATH)/generic
+       $(foreach file, $(DATA), cp $(file) $(BUILD_PATH)/generic/$(subst /,-,$(file)) ; )
+       $(foreach file, $(SOURCE), cp $(file) $(BUILD_PATH)/generic/$(subst /,-,$(file)) ; )
+       #$(foreach file, $(OBJ), cp $(file) $(BUILD_PATH)/generic/$(subst /,-,$(file)) ; )
+       cp support/$(PROJECT_NAME).desktop $(BUILD_PATH)/generic
+       cp support/icons/hicolor/26x26/hildon/$(PROJECT_NAME).png $(BUILD_PATH)/generic/26x26-$(PROJECT_NAME).png
+       cp support/icons/hicolor/64x64/hildon/$(PROJECT_NAME).png $(BUILD_PATH)/generic/64x64-$(PROJECT_NAME).png
+       cp support/icons/hicolor/scalable/hildon/$(PROJECT_NAME).png $(BUILD_PATH)/generic/scale-$(PROJECT_NAME).png
+       cp support/builddeb.py $(BUILD_PATH)/generic
+       cp support/py2deb.py $(BUILD_PATH)/generic
+       cp support/fake_py2deb.py $(BUILD_PATH)/generic
+
+       mkdir -p $(BUILD_PATH)/diablo
+       cp -R $(BUILD_PATH)/generic/* $(BUILD_PATH)/diablo
+       cd $(BUILD_PATH)/diablo ; python builddeb.py diablo
+       mkdir -p $(BUILD_PATH)/fremantle
+       cp -R $(BUILD_PATH)/generic/* $(BUILD_PATH)/fremantle
+       cd $(BUILD_PATH)/fremantle ; python builddeb.py fremantle
+       mkdir -p $(BUILD_PATH)/debian
+       cp -R $(BUILD_PATH)/generic/* $(BUILD_PATH)/debian
+       cd $(BUILD_PATH)/debian ; python builddeb.py debian
+
+upload:
+       dput fremantle-extras-builder $(BUILD_PATH)/fremantle/$(PROJECT_NAME)*.changes
+       dput diablo-extras-builder $(BUILD_PATH)/diablo/$(PROJECT_NAME)*.changes
+       cp $(BUILD_PATH)/debian/*.deb ./www/$(PROJECT_NAME).deb
+
+lint: $(OBJ)
+       $(foreach file, $(SOURCE), $(LINT) $(file) ; )
+
+tags: $(TAG_FILE) 
+
+todo: $(TODO_FILE)
+
+clean:
+       rm -Rf $(OBJ)
+       rm -Rf $(BUILD_PATH)
+       rm -Rf $(TODO_FILE)
+
+distclean:
+       rm -Rf $(OBJ)
+       rm -Rf $(BUILD_PATH)
+       rm -Rf $(TAG_FILE)
+       find $(SOURCE_PATH) -name "*.*~" | xargs rm -f
+       find $(SOURCE_PATH) -name "*.swp" | xargs rm -f
+       find $(SOURCE_PATH) -name "*.bak" | xargs rm -f
+       find $(SOURCE_PATH) -name ".*.swp" | xargs rm -f
+
+$(TAG_FILE): $(OBJ)
+       mkdir -p $(dir $(TAG_FILE))
+       $(CTAGS) -o $(TAG_FILE) $(SOURCE)
+
+$(TODO_FILE): $(SOURCE)
+       @- $(TODO_FINDER) $(SOURCE) > $(TODO_FILE)
+
+%.pyc: %.py
+       $(SYNTAX_TEST) $<
+
+#Makefile Debugging
+#Target to print any variable, can be added to the dependencies of any other target
+#Userfule flags for make, -d, -p, -n
+print-%: ; @$(error $* is $($*) ($(value $*)) (from $(origin $*)))
diff --git a/README b/README
new file mode 100644 (file)
index 0000000..ac2fe23
--- /dev/null
+++ b/README
@@ -0,0 +1,4 @@
+Building a package
+===================
+Run
+       make package
diff --git a/data/COPYRIGHT b/data/COPYRIGHT
new file mode 100644 (file)
index 0000000..1bbeb88
--- /dev/null
@@ -0,0 +1 @@
+Copyright 2010 Intellectual Reserve, Inc.
diff --git a/data/LDSHomeIcon.png b/data/LDSHomeIcon.png
new file mode 100644 (file)
index 0000000..2d57046
Binary files /dev/null and b/data/LDSHomeIcon.png differ
diff --git a/data/MormonMessagesIcon.png b/data/MormonMessagesIcon.png
new file mode 100644 (file)
index 0000000..163d1ff
Binary files /dev/null and b/data/MormonMessagesIcon.png differ
diff --git a/data/ScripturesWebIcon.png b/data/ScripturesWebIcon.png
new file mode 100644 (file)
index 0000000..cd39caf
Binary files /dev/null and b/data/ScripturesWebIcon.png differ
diff --git a/data/conference.png b/data/conference.png
new file mode 100644 (file)
index 0000000..6f62f08
Binary files /dev/null and b/data/conference.png differ
diff --git a/data/conference_bg.png b/data/conference_bg.png
new file mode 100644 (file)
index 0000000..e769494
Binary files /dev/null and b/data/conference_bg.png differ
diff --git a/data/home.png b/data/home.png
new file mode 100644 (file)
index 0000000..57dc225
Binary files /dev/null and b/data/home.png differ
diff --git a/data/icon.png b/data/icon.png
new file mode 100644 (file)
index 0000000..e4949a6
Binary files /dev/null and b/data/icon.png differ
diff --git a/data/loading.gif b/data/loading.gif
new file mode 100644 (file)
index 0000000..f864d5f
Binary files /dev/null and b/data/loading.gif differ
diff --git a/data/magazine_bg.png b/data/magazine_bg.png
new file mode 100644 (file)
index 0000000..a6d8300
Binary files /dev/null and b/data/magazine_bg.png differ
diff --git a/data/magazines.png b/data/magazines.png
new file mode 100644 (file)
index 0000000..f30fe0e
Binary files /dev/null and b/data/magazines.png differ
diff --git a/data/more.png b/data/more.png
new file mode 100644 (file)
index 0000000..9824447
Binary files /dev/null and b/data/more.png differ
diff --git a/data/next.png b/data/next.png
new file mode 100644 (file)
index 0000000..cfc53dd
Binary files /dev/null and b/data/next.png differ
diff --git a/data/nomagazineimage.png b/data/nomagazineimage.png
new file mode 100644 (file)
index 0000000..1533015
Binary files /dev/null and b/data/nomagazineimage.png differ
diff --git a/data/pause.png b/data/pause.png
new file mode 100644 (file)
index 0000000..e9d5aa6
Binary files /dev/null and b/data/pause.png differ
diff --git a/data/pausepressed.png b/data/pausepressed.png
new file mode 100644 (file)
index 0000000..34d1775
Binary files /dev/null and b/data/pausepressed.png differ
diff --git a/data/play.png b/data/play.png
new file mode 100644 (file)
index 0000000..c863850
Binary files /dev/null and b/data/play.png differ
diff --git a/data/playpressed.png b/data/playpressed.png
new file mode 100644 (file)
index 0000000..c3bd807
Binary files /dev/null and b/data/playpressed.png differ
diff --git a/data/prev.png b/data/prev.png
new file mode 100644 (file)
index 0000000..cacd89e
Binary files /dev/null and b/data/prev.png differ
diff --git a/data/radio.png b/data/radio.png
new file mode 100644 (file)
index 0000000..7c70633
Binary files /dev/null and b/data/radio.png differ
diff --git a/data/radio_header.png b/data/radio_header.png
new file mode 100644 (file)
index 0000000..f4faa65
Binary files /dev/null and b/data/radio_header.png differ
diff --git a/data/scripture_bg.png b/data/scripture_bg.png
new file mode 100644 (file)
index 0000000..dcd095d
Binary files /dev/null and b/data/scripture_bg.png differ
diff --git a/data/scriptures.png b/data/scriptures.png
new file mode 100644 (file)
index 0000000..c8c06bf
Binary files /dev/null and b/data/scriptures.png differ
diff --git a/data/small_home.png b/data/small_home.png
new file mode 100644 (file)
index 0000000..54e61f7
Binary files /dev/null and b/data/small_home.png differ
diff --git a/data/small_next.png b/data/small_next.png
new file mode 100644 (file)
index 0000000..367a8b5
Binary files /dev/null and b/data/small_next.png differ
diff --git a/data/small_pause.png b/data/small_pause.png
new file mode 100644 (file)
index 0000000..7bdbfb8
Binary files /dev/null and b/data/small_pause.png differ
diff --git a/data/small_pausepressed.png b/data/small_pausepressed.png
new file mode 100644 (file)
index 0000000..f523d16
Binary files /dev/null and b/data/small_pausepressed.png differ
diff --git a/data/small_play.png b/data/small_play.png
new file mode 100644 (file)
index 0000000..c9a0fc7
Binary files /dev/null and b/data/small_play.png differ
diff --git a/data/small_playpressed.png b/data/small_playpressed.png
new file mode 100644 (file)
index 0000000..c11e995
Binary files /dev/null and b/data/small_playpressed.png differ
diff --git a/data/small_prev.png b/data/small_prev.png
new file mode 100644 (file)
index 0000000..3140836
Binary files /dev/null and b/data/small_prev.png differ
diff --git a/data/small_stop.png b/data/small_stop.png
new file mode 100644 (file)
index 0000000..67a0d9e
Binary files /dev/null and b/data/small_stop.png differ
diff --git a/data/small_stoppressed.png b/data/small_stoppressed.png
new file mode 100644 (file)
index 0000000..a712592
Binary files /dev/null and b/data/small_stoppressed.png differ
diff --git a/data/stop.png b/data/stop.png
new file mode 100644 (file)
index 0000000..abffa48
Binary files /dev/null and b/data/stop.png differ
diff --git a/data/stoppressed.png b/data/stoppressed.png
new file mode 100644 (file)
index 0000000..6f895d2
Binary files /dev/null and b/data/stoppressed.png differ
diff --git a/src/LICENSE b/src/LICENSE
new file mode 100644 (file)
index 0000000..5ab7695
--- /dev/null
@@ -0,0 +1,504 @@
+                 GNU LESSER GENERAL PUBLIC LICENSE
+                      Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL.  It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+                           Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+  This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it.  You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+  When we speak of free software, we are referring to freedom of use,
+not price.  Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+  To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights.  These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+  For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you.  You must make sure that they, too, receive or can get the source
+code.  If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it.  And you must show them these terms so they know their rights.
+
+  We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+  To protect each distributor, we want to make it very clear that
+there is no warranty for the free library.  Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+\f
+  Finally, software patents pose a constant threat to the existence of
+any free program.  We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder.  Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+  Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License.  This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License.  We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+  When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library.  The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom.  The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+  We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License.  It also provides other free software developers Less
+of an advantage over competing non-free programs.  These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries.  However, the Lesser license provides advantages in certain
+special circumstances.
+
+  For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard.  To achieve this, non-free programs must be
+allowed to use the library.  A more frequent case is that a free
+library does the same job as widely used non-free libraries.  In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+  In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software.  For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+  Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.  Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library".  The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+\f
+                 GNU LESSER GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+  A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+  The "Library", below, refers to any such software library or work
+which has been distributed under these terms.  A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language.  (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+  "Source code" for a work means the preferred form of the work for
+making modifications to it.  For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+  Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it).  Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+  
+  1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+  You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+\f
+  2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) The modified work must itself be a software library.
+
+    b) You must cause the files modified to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    c) You must cause the whole of the work to be licensed at no
+    charge to all third parties under the terms of this License.
+
+    d) If a facility in the modified Library refers to a function or a
+    table of data to be supplied by an application program that uses
+    the facility, other than as an argument passed when the facility
+    is invoked, then you must make a good faith effort to ensure that,
+    in the event an application does not supply such function or
+    table, the facility still operates, and performs whatever part of
+    its purpose remains meaningful.
+
+    (For example, a function in a library to compute square roots has
+    a purpose that is entirely well-defined independent of the
+    application.  Therefore, Subsection 2d requires that any
+    application-supplied function or table used by this function must
+    be optional: if the application does not supply it, the square
+    root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library.  To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License.  (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.)  Do not make any other change in
+these notices.
+\f
+  Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+  This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+  4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+  If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library".  Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+  However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library".  The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+  When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library.  The
+threshold for this to be true is not precisely defined by law.
+
+  If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work.  (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+  Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+\f
+  6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+  You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License.  You must supply a copy of this License.  If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License.  Also, you must do one
+of these things:
+
+    a) Accompany the work with the complete corresponding
+    machine-readable source code for the Library including whatever
+    changes were used in the work (which must be distributed under
+    Sections 1 and 2 above); and, if the work is an executable linked
+    with the Library, with the complete machine-readable "work that
+    uses the Library", as object code and/or source code, so that the
+    user can modify the Library and then relink to produce a modified
+    executable containing the modified Library.  (It is understood
+    that the user who changes the contents of definitions files in the
+    Library will not necessarily be able to recompile the application
+    to use the modified definitions.)
+
+    b) Use a suitable shared library mechanism for linking with the
+    Library.  A suitable mechanism is one that (1) uses at run time a
+    copy of the library already present on the user's computer system,
+    rather than copying library functions into the executable, and (2)
+    will operate properly with a modified version of the library, if
+    the user installs one, as long as the modified version is
+    interface-compatible with the version that the work was made with.
+
+    c) Accompany the work with a written offer, valid for at
+    least three years, to give the same user the materials
+    specified in Subsection 6a, above, for a charge no more
+    than the cost of performing this distribution.
+
+    d) If distribution of the work is made by offering access to copy
+    from a designated place, offer equivalent access to copy the above
+    specified materials from the same place.
+
+    e) Verify that the user has already received a copy of these
+    materials or that you have already sent this user a copy.
+
+  For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it.  However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+  It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system.  Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+\f
+  7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+    a) Accompany the combined library with a copy of the same work
+    based on the Library, uncombined with any other library
+    facilities.  This must be distributed under the terms of the
+    Sections above.
+
+    b) Give prominent notice with the combined library of the fact
+    that part of it is a work based on the Library, and explaining
+    where to find the accompanying uncombined form of the same work.
+
+  8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License.  Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License.  However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+  9. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Library or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+  10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+\f
+  11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded.  In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+  13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation.  If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+\f
+  14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission.  For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this.  Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+                           NO WARRANTY
+
+  15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+                    END OF TERMS AND CONDITIONS
+\f
+           How to Apply These Terms to Your New Libraries
+
+  If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change.  You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+  To apply these terms, attach the following notices to the library.  It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the library's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the
+  library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+  <signature of Ty Coon>, 1 April 1990
+  Ty Coon, President of Vice
+
+That's all there is to it!
+
+
diff --git a/src/MormonChannel.py b/src/MormonChannel.py
new file mode 100755 (executable)
index 0000000..333caff
--- /dev/null
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Copyright (C) 2007 Christoph Würstle
+This program is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License version 2 as
+published by the Free Software Foundation.
+"""
+
+import os
+import sys
+import logging
+
+_moduleLogger = logging.getLogger(__name__)
+sys.path.append('/usr/lib/mormonchannel')
+
+
+import constants
+import mormonchannel_gtk
+
+
+if __name__ == "__main__":
+       try:
+               os.makedirs(constants._data_path_)
+       except OSError, e:
+               if e.errno != 17:
+                       raise
+
+       try:
+               os.makedirs(constants._cache_path_)
+       except OSError, e:
+               if e.errno != 17:
+                       raise
+
+       logFormat = '(%(asctime)s) %(levelname)-5s %(threadName)s.%(name)s: %(message)s'
+       logging.basicConfig(level=logging.DEBUG, filename=constants._user_logpath_, format=logFormat)
+       _moduleLogger.info("%s %s-%s" % (constants.__app_name__, constants.__version__, constants.__build__))
+       _moduleLogger.info("OS: %s" % (os.uname()[0], ))
+       _moduleLogger.info("Kernel: %s (%s) for %s" % os.uname()[2:])
+       _moduleLogger.info("Hostname: %s" % os.uname()[1])
+
+       mormonchannel_gtk.run()
diff --git a/src/__init__.py b/src/__init__.py
new file mode 100644 (file)
index 0000000..d3a51da
--- /dev/null
@@ -0,0 +1,3 @@
+#!/usr/bin/env python
+
+import util
diff --git a/src/backend.py b/src/backend.py
new file mode 100755 (executable)
index 0000000..00efca6
--- /dev/null
@@ -0,0 +1,184 @@
+#!/usr/bin/env python
+
+import urllib
+from xml.etree import ElementTree
+import logging
+
+import browser_emu
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class Backend(object):
+
+       def __init__(self):
+               self._browser = browser_emu.MozillaEmulator()
+
+       def get_languages(self):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.languages.query",
+               )
+               languages = tree.find("languages")
+               return self._process_list(languages, ["name"])
+
+       def get_radio_channels(self):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.radiochannels.query",
+               )
+               channels = tree.find("channels")
+               return self._process_list(channels, ["description", "url", "port"])
+
+       def get_radio_channel_programming(self, chanId, date=None):
+               if date is not None:
+                       tree = self._get_page_with_validation(
+                               action="lds.radio.radiochannels.programming.query",
+                               channelID=chanId,
+                               date=date,
+                       )
+               else:
+                       tree = self._get_page_with_validation(
+                               action="lds.radio.radiochannels.programming.query",
+                               channelID=chanId,
+                       )
+               programs = tree.find("programs")
+               return self._process_list(programs, ["date", "time", "title", "shortdescription", "artist"])
+
+       def get_conferences(self, langId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.conferences.query",
+                       languageID=langId,
+               )
+               conferences = tree.find("conferences")
+               return self._process_list(conferences, ["title", "full_title", "month", "year"])
+
+       def get_conference_sessions(self, confId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.conferences.sessions.query",
+                       conferenceID=confId,
+               )
+               items = tree.find("sessions")
+               return self._process_list(items, ["title", "short_title", "order"])
+
+       def get_conference_talks(self, sessionId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.conferences.sessions.talks.query",
+                       sessionID=sessionId,
+               )
+               items = tree.find("talks")
+               return self._process_list(items, ["title", "order", "url", "speaker"])
+
+       def get_magazines(self, langId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.magazines.query",
+                       languageID=langId,
+               )
+               magazines = tree.find("magazines")
+               return self._process_list(magazines, ["title"])
+
+       def get_magazine_issues(self, magId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.magazines.issues.query",
+                       magazineID=magId,
+               )
+               items = tree.find("issues")
+               return self._process_list(items, ["title", "year", "month", "pictureURL"])
+
+       def get_magazine_articles(self, issueId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.magazines.issues.articles.query",
+                       issueID=issueId,
+               )
+               items = tree.find("articles")
+               return self._process_list(items, ["title", "author", "url"])
+
+       def get_scriptures(self, langId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.scriptures.query",
+                       languageID=langId,
+               )
+               scriptures = tree.find("scriptures")
+               return self._process_list(scriptures, ["title"])
+
+       def get_scripture_books(self, scriptId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.scriptures.books.query",
+                       scriptureID=scriptId,
+               )
+               items = tree.find("books")
+               return self._process_list(items, ["title"])
+
+       def get_scripture_chapters(self, bookId):
+               tree = self._get_page_with_validation(
+                       action="lds.radio.scriptures.books.chapters.query",
+                       bookID=bookId,
+               )
+               items = tree.find("chapters")
+               return self._process_list(items, ["title", "url"])
+
+       def _get_page_with_validation(self, **params):
+               encodedParams = urllib.urlencode(params)
+               page = self._browser.download("http://tech.lds.org/radio?%s" % encodedParams)
+               if not page:
+                       raise RuntimeError("Blank page")
+               tree = ElementTree.fromstring(page)
+
+               if tree.tag == "apiresults":
+                       desc = tree.find("ErrorDescription")
+                       raise RuntimeError(desc.text)
+               else:
+                       results = tree.find("apiresults")
+                       if not results.attrib["success"]:
+                               raise RuntimeError("Could not determine radio languages")
+
+               return tree
+
+       def _process_list(self, tree, elements):
+               for item in tree.getchildren():
+                       data = {"id": item.attrib["ID"]}
+                       for element in elements:
+                               data[element] = item.find(element).text
+                       yield data
+
+
+if __name__ == "__main__":
+       b = Backend()
+
+       print list(b.get_languages())
+
+       if False:
+               channels = list(b.get_radio_channels())
+               print channels
+               for chanData in channels:
+                       programs = list(b.get_radio_channel_programming(chanData["id"]))
+                       print programs
+
+       if False:
+               confs = list(b.get_conferences(1))
+               print confs
+               for confData in confs:
+                       sessions = list(b.get_conference_sessions(confData["id"]))
+                       for sessionData in sessions:
+                               print sessionData
+                               talks = list(b.get_conference_talks(sessionData["id"]))
+                               print talks
+
+       if False:
+               mags = list(b.get_magazines(1))
+               print mags
+               for magData in mags:
+                       issues = list(b.get_magazine_issues(magData["id"]))
+                       for issueData in issues:
+                               print issueData
+                               articles = list(b.get_magazine_articles(issueData["id"]))
+                               print articles
+
+       if False:
+               mags = list(b.get_scriptures(1))
+               print mags
+               for magData in mags:
+                       books = list(b.get_scripture_books(magData["id"]))
+                       for bookData in books:
+                               print bookData
+                               chapters = list(b.get_scripture_chapters(bookData["id"]))
+                               print chapters
diff --git a/src/banners.py b/src/banners.py
new file mode 100644 (file)
index 0000000..afa5281
--- /dev/null
@@ -0,0 +1,99 @@
+import sys
+import logging
+
+import gtk
+
+import util.misc as misc_utils
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class GenericBanner(object):
+
+       def __init__(self):
+               self._indicator = gtk.Image()
+
+               self._label = gtk.Label()
+
+               self._layout = gtk.HBox()
+               self._layout.pack_start(self._indicator, False, False)
+               self._layout.pack_start(self._label, False, True)
+
+       @property
+       def toplevel(self):
+               return self._layout
+
+       def show(self, icon, message):
+               assert not self._label.get_text(), self._label.get_text()
+               if isinstance(icon, gtk.gdk.PixbufAnimation):
+                       self._indicator.set_from_animation(icon)
+               elif isinstance(icon, gtk.gdk.Pixbuf):
+                       self._indicator.set_from_pixbuf(icon)
+               else:
+                       self._indicator.set_from_stock(icon)
+               self._label.set_text(message)
+               self.toplevel.show()
+
+       def hide(self):
+               self._label.set_text("")
+               self.toplevel.hide()
+
+
+class StackingBanner(object):
+
+       ICON_SIZE = 32
+
+       def __init__(self):
+               self._indicator = gtk.Image()
+
+               self._message = gtk.Label()
+
+               self._closeImage = gtk.Image()
+               self._closeImage.set_from_stock("gtk-close", self.ICON_SIZE)
+
+               self._layout = gtk.HBox()
+               self._layout.pack_start(self._indicator, False, False)
+               self._layout.pack_start(self._message, True, True)
+               self._layout.pack_start(self._closeImage, False, False)
+
+               self._events = gtk.EventBox()
+               self._events.add(self._layout)
+               self._events.connect("button_release_event", self._on_close)
+
+               self._messages = []
+
+       @property
+       def toplevel(self):
+               return self._events
+
+       def push_message(self, message, icon=""):
+               self._messages.append((message, icon))
+               if 1 == len(self._messages):
+                       self._update_message()
+
+       def push_exception(self):
+               userMessage = str(sys.exc_info()[1])
+               self.push_message(userMessage, "gtk-dialog-error")
+               _moduleLogger.exception(userMessage)
+
+       def pop_message(self):
+               del self._messages[0]
+               self._update_message()
+
+       def _update_message(self):
+               if 0 == len(self._messages):
+                       self.toplevel.hide()
+               else:
+                       message, icon = self._messages[0]
+                       self._message.set_text(message)
+                       if icon:
+                               self._indicator.set_from_stock(icon)
+                               self._indicator.show()
+                       else:
+                               self._indicator.hide()
+                       self.toplevel.show()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_close(self, *args):
+               self.pop_message()
diff --git a/src/browser_emu.py b/src/browser_emu.py
new file mode 100644 (file)
index 0000000..12d5e61
--- /dev/null
@@ -0,0 +1,199 @@
+"""
+@author:         Laszlo Nagy
+@copyright:   (c) 2005 by Szoftver Messias Bt.
+@licence:       BSD style
+
+Objects of the MozillaEmulator class can emulate a browser that is capable of:
+
+       - cookie management
+       - configurable user agent string
+       - GET and POST
+       - multipart POST (send files)
+       - receive content into file
+
+I have seen many requests on the python mailing list about how to emulate a browser. I'm using this class for years now, without any problems. This is how you can use it:
+
+       1. Use firefox
+       2. Install and open the livehttpheaders plugin
+       3. Use the website manually with firefox
+       4. Check the GET and POST requests in the livehttpheaders capture window
+       5. Create an instance of the above class and send the same GET and POST requests to the server.
+
+Optional steps:
+
+       - You can change user agent string in the build_opened method
+       - The "encode_multipart_formdata" function can be used alone to create POST data from a list of field values and files
+"""
+
+import urllib2
+import cookielib
+import logging
+
+import socket
+
+
+_moduleLogger = logging.getLogger("browser_emu")
+socket.setdefaulttimeout(20)
+
+
+class MozillaEmulator(object):
+
+       def __init__(self, trycount = 1):
+               """Create a new MozillaEmulator object.
+
+               @param trycount: The download() method will retry the operation if it
+               fails. You can specify -1 for infinite retrying.  A value of 0 means no
+               retrying. A value of 1 means one retry. etc."""
+               self.debug = False
+               self.trycount = trycount
+               self._cookies = cookielib.LWPCookieJar()
+               self._loadedFromCookies = False
+
+       def load_cookies(self, path):
+               assert not self._loadedFromCookies, "Load cookies only once"
+               if path is None:
+                       return
+
+               self._cookies.filename = path
+               try:
+                       self._cookies.load()
+               except cookielib.LoadError:
+                       _moduleLogger.exception("Bad cookie file")
+               except IOError:
+                       _moduleLogger.exception("No cookie file")
+               except Exception, e:
+                       _moduleLogger.exception("Unknown error with cookies")
+               else:
+                       self._loadedFromCookies = True
+
+               return self._loadedFromCookies
+
+       def save_cookies(self):
+               if self._loadedFromCookies:
+                       self._cookies.save()
+
+       def clear_cookies(self):
+               if self._loadedFromCookies:
+                       self._cookies.clear()
+
+       def download(self, url,
+                       postdata = None, extraheaders = None, forbidRedirect = False,
+                       trycount = None, only_head = False,
+               ):
+               """Download an URL with GET or POST methods.
+
+               @param postdata: It can be a string that will be POST-ed to the URL.
+                       When None is given, the method will be GET instead.
+               @param extraheaders: You can add/modify HTTP headers with a dict here.
+               @param forbidRedirect: Set this flag if you do not want to handle
+                       HTTP 301 and 302 redirects.
+               @param trycount: Specify the maximum number of retries here.
+                       0 means no retry on error. Using -1 means infinite retring.
+                       None means the default value (that is self.trycount).
+               @param only_head: Create the openerdirector and return it. In other
+                       words, this will not retrieve any content except HTTP headers.
+
+               @return: The raw HTML page data
+               """
+               _moduleLogger.debug("Performing download of %s" % url)
+
+               if extraheaders is None:
+                       extraheaders = {}
+               if trycount is None:
+                       trycount = self.trycount
+               cnt = 0
+
+               while True:
+                       try:
+                               req, u = self._build_opener(url, postdata, extraheaders, forbidRedirect)
+                               openerdirector = u.open(req)
+                               if self.debug:
+                                       _moduleLogger.info("%r - %r" % (req.get_method(), url))
+                                       _moduleLogger.info("%r - %r" % (openerdirector.code, openerdirector.msg))
+                                       _moduleLogger.info("%r" % (openerdirector.headers))
+                               self._cookies.extract_cookies(openerdirector, req)
+                               if only_head:
+                                       return openerdirector
+
+                               return self._read(openerdirector, trycount)
+                       except urllib2.URLError, e:
+                               _moduleLogger.debug("%s: %s" % (e, url))
+                               cnt += 1
+                               if (-1 < trycount) and (trycount < cnt):
+                                       raise
+
+                       # Retry :-)
+                       _moduleLogger.debug("MozillaEmulator: urllib2.URLError, retrying %d" % cnt)
+
+       def _build_opener(self, url, postdata = None, extraheaders = None, forbidRedirect = False):
+               if extraheaders is None:
+                       extraheaders = {}
+
+               txheaders = {
+                       'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png',
+                       'Accept-Language': 'en,en-us;q=0.5',
+                       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
+               }
+               for key, value in extraheaders.iteritems():
+                       txheaders[key] = value
+               req = urllib2.Request(url, postdata, txheaders)
+               self._cookies.add_cookie_header(req)
+               if forbidRedirect:
+                       redirector = HTTPNoRedirector()
+                       #_moduleLogger.info("Redirection disabled")
+               else:
+                       redirector = urllib2.HTTPRedirectHandler()
+                       #_moduleLogger.info("Redirection enabled")
+
+               http_handler = urllib2.HTTPHandler(debuglevel=self.debug)
+               https_handler = urllib2.HTTPSHandler(debuglevel=self.debug)
+
+               u = urllib2.build_opener(
+                       http_handler,
+                       https_handler,
+                       urllib2.HTTPCookieProcessor(self._cookies),
+                       redirector
+               )
+               u.addheaders = [(
+                       'User-Agent',
+                       'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.4) Gecko/20091016 Firefox/3.5.4 (.NET CLR 3.5.30729)'
+               )]
+               if not postdata is None:
+                       req.add_data(postdata)
+               return (req, u)
+
+       def _read(self, openerdirector, trycount):
+               chunks = []
+
+               chunk = openerdirector.read()
+               chunks.append(chunk)
+               #while chunk and cnt < trycount:
+               #       time.sleep(1)
+               #       cnt += 1
+               #       chunk = openerdirector.read()
+               #       chunks.append(chunk)
+
+               data = "".join(chunks)
+
+               if "Content-Length" in openerdirector.info():
+                       assert len(data) == int(openerdirector.info()["Content-Length"]), "The packet header promised %s of data but only was able to read %s of data" % (
+                               openerdirector.info()["Content-Length"],
+                               len(data),
+                       )
+
+               return data
+
+
+class HTTPNoRedirector(urllib2.HTTPRedirectHandler):
+       """This is a custom http redirect handler that FORBIDS redirection."""
+
+       def http_error_302(self, req, fp, code, msg, headers):
+               e = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
+               if e.code in (301, 302):
+                       if 'location' in headers:
+                               newurl = headers.getheaders('location')[0]
+                       elif 'uri' in headers:
+                               newurl = headers.getheaders('uri')[0]
+                       e.newurl = newurl
+               _moduleLogger.info("New url: %s" % e.newurl)
+               raise e
diff --git a/src/call_monitor.py b/src/call_monitor.py
new file mode 100644 (file)
index 0000000..97be5a7
--- /dev/null
@@ -0,0 +1,145 @@
+import logging
+
+import gobject
+import dbus
+import telepathy
+
+import gtk_toolbox
+
+
+_moduleLogger = logging.getLogger(__name__)
+DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties'
+
+
+class NewChannelSignaller(object):
+
+       def __init__(self, on_new_channel):
+               self._sessionBus = dbus.SessionBus()
+               self._on_user_new_channel = on_new_channel
+
+       def start(self):
+               self._sessionBus.add_signal_receiver(
+                       self._on_new_channel,
+                       "NewChannel",
+                       "org.freedesktop.Telepathy.Connection",
+                       None,
+                       None
+               )
+
+       def stop(self):
+               self._sessionBus.remove_signal_receiver(
+                       self._on_new_channel,
+                       "NewChannel",
+                       "org.freedesktop.Telepathy.Connection",
+                       None,
+                       None
+               )
+
+       @gtk_toolbox.log_exception(_moduleLogger)
+       def _on_new_channel(
+               self, channelObjectPath, channelType, handleType, handle, supressHandler
+       ):
+               connObjectPath = channel_path_to_conn_path(channelObjectPath)
+               serviceName = path_to_service_name(channelObjectPath)
+               try:
+                       self._on_user_new_channel(
+                               self._sessionBus, serviceName, connObjectPath, channelObjectPath, channelType
+                       )
+               except Exception:
+                       _moduleLogger.exception("Blocking exception from being passed up")
+
+
+class ChannelClosed(object):
+
+       def __init__(self, bus, conn, chan, on_closed):
+               self.__on_closed = on_closed
+
+               chan[telepathy.interfaces.CHANNEL].connect_to_signal(
+                       "Closed",
+                       self._on_closed,
+               )
+
+       @gtk_toolbox.log_exception(_moduleLogger)
+       def _on_closed(self):
+               self.__on_closed(self)
+
+
+class CallMonitor(gobject.GObject):
+
+       __gsignals__ = {
+               'call_start' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (),
+               ),
+               'call_end' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (),
+               ),
+       }
+
+       def __init__(self):
+               gobject.GObject.__init__(self)
+               self._isActive = False
+               self._newChannelMonitor = NewChannelSignaller(self._on_new_channel)
+               self._channelClosedMonitors = []
+
+       def start(self):
+               self._isActive = True
+               self._newChannelMonitor.start()
+
+       def stop(self):
+               self._isActive = False
+               self._newChannelMonitor.stop()
+
+       def _on_new_channel(self, sessionBus, serviceName, connObjectPath, channelObjectPath, channelType):
+               if not self._isActive:
+                       return
+
+               if channelType != telepathy.interfaces.CHANNEL_TYPE_STREAMED_MEDIA:
+                       return
+
+               cmName = cm_from_path(connObjectPath)
+               conn = telepathy.client.Connection(serviceName, connObjectPath)
+               try:
+                       chan = telepathy.client.Channel(serviceName, channelObjectPath)
+               except dbus.exceptions.UnknownMethodException:
+                       _moduleLogger.exception("Client might not have implemented a deprecated method")
+                       return
+
+               missDetection = ChannelClosed(
+                       sessionBus, conn, chan, self._on_close
+               )
+               self._outstandingRequests.append(missDetection)
+               if len(self._outstandingRequests) == 1:
+                       self.emit("call_start")
+
+       def _on_close(self, channelCloseMonitor):
+               self._outstandingRequests.remove(channelCloseMonitor)
+               if not self._outstandingRequests:
+                       self.emit("call_stop")
+
+
+def channel_path_to_conn_path(channelObjectPath):
+       """
+       >>> channel_path_to_conn_path("/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME/Channel1")
+       '/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME'
+       """
+       return channelObjectPath.rsplit("/", 1)[0]
+
+
+def path_to_service_name(path):
+       """
+       >>> path_to_service_name("/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME/Channel1")
+       'org.freedesktop.Telepathy.ConnectionManager.theonering.gv.USERNAME'
+       """
+       return ".".join(path[1:].split("/")[0:7])
+
+
+def cm_from_path(path):
+       """
+       >>> cm_from_path("/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME/Channel1")
+       'theonering'
+       """
+       return path[1:].split("/")[4]
diff --git a/src/constants.py b/src/constants.py
new file mode 100644 (file)
index 0000000..b5ff820
--- /dev/null
@@ -0,0 +1,11 @@
+import os
+
+__pretty_app_name__ = "Mormon Channel"
+__app_name__ = "MormonChannel"
+__version__ = "1.0.0"
+__build__ = 0
+__app_magic__ = 0x1AFF5
+_data_path_ = os.path.join(os.path.expanduser("~"), ".%s" % __app_name__)
+_user_settings_ = "%s/settings.ini" % _data_path_
+_cache_path_ = "%s/cache" % _data_path_
+_user_logpath_ = "%s/%s.log" % (_data_path_, __app_name__)
diff --git a/src/gtk_toolbox.py b/src/gtk_toolbox.py
new file mode 100644 (file)
index 0000000..784c871
--- /dev/null
@@ -0,0 +1,577 @@
+#!/usr/bin/python
+
+from __future__ import with_statement
+
+import os
+import errno
+import sys
+import time
+import itertools
+import functools
+import contextlib
+import logging
+import threading
+import Queue
+
+import gobject
+import gtk
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+def get_screen_orientation():
+       width, height = gtk.gdk.get_default_root_window().get_size()
+       if width < height:
+               return gtk.ORIENTATION_VERTICAL
+       else:
+               return gtk.ORIENTATION_HORIZONTAL
+
+
+def orientation_change_connect(handler, *args):
+       """
+       @param handler(orientation, *args) -> None(?)
+       """
+       initialScreenOrientation = get_screen_orientation()
+       orientationAndArgs = list(itertools.chain((initialScreenOrientation, ), args))
+
+       def _on_screen_size_changed(screen):
+               newScreenOrientation = get_screen_orientation()
+               if newScreenOrientation != orientationAndArgs[0]:
+                       orientationAndArgs[0] = newScreenOrientation
+                       handler(*orientationAndArgs)
+
+       rootScreen = gtk.gdk.get_default_root_window()
+       return gtk.connect(rootScreen, "size-changed", _on_screen_size_changed)
+
+
+@contextlib.contextmanager
+def flock(path, timeout=-1):
+       WAIT_FOREVER = -1
+       DELAY = 0.1
+       timeSpent = 0
+
+       acquired = False
+
+       while timeSpent <= timeout or timeout == WAIT_FOREVER:
+               try:
+                       fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR)
+                       acquired = True
+                       break
+               except OSError, e:
+                       if e.errno != errno.EEXIST:
+                               raise
+               time.sleep(DELAY)
+               timeSpent += DELAY
+
+       assert acquired, "Failed to grab file-lock %s within timeout %d" % (path, timeout)
+
+       try:
+               yield fd
+       finally:
+               os.unlink(path)
+
+
+@contextlib.contextmanager
+def gtk_lock():
+       gtk.gdk.threads_enter()
+       try:
+               yield
+       finally:
+               gtk.gdk.threads_leave()
+
+
+def find_parent_window(widget):
+       while True:
+               parent = widget.get_parent()
+               if isinstance(parent, gtk.Window):
+                       return parent
+               widget = parent
+
+
+def make_idler(func):
+       """
+       Decorator that makes a generator-function into a function that will continue execution on next call
+       """
+       a = []
+
+       @functools.wraps(func)
+       def decorated_func(*args, **kwds):
+               if not a:
+                       a.append(func(*args, **kwds))
+               try:
+                       a[0].next()
+                       return True
+               except StopIteration:
+                       del a[:]
+                       return False
+
+       return decorated_func
+
+
+def asynchronous_gtk_message(original_func):
+       """
+       @note Idea came from http://www.aclevername.com/articles/python-webgui/
+       """
+
+       def execute(allArgs):
+               args, kwargs = allArgs
+               with gtk_lock():
+                       original_func(*args, **kwargs)
+               return False
+
+       @functools.wraps(original_func)
+       def delayed_func(*args, **kwargs):
+               gobject.idle_add(execute, (args, kwargs))
+
+       return delayed_func
+
+
+def synchronous_gtk_message(original_func):
+       """
+       @note Idea came from http://www.aclevername.com/articles/python-webgui/
+       """
+
+       @functools.wraps(original_func)
+       def immediate_func(*args, **kwargs):
+               with gtk_lock():
+                       return original_func(*args, **kwargs)
+
+       return immediate_func
+
+
+def autostart(func):
+       """
+       >>> @autostart
+       ... def grep_sink(pattern):
+       ...     print "Looking for %s" % pattern
+       ...     while True:
+       ...             line = yield
+       ...             if pattern in line:
+       ...                     print line,
+       >>> g = grep_sink("python")
+       Looking for python
+       >>> g.send("Yeah but no but yeah but no")
+       >>> g.send("A series of tubes")
+       >>> g.send("python generators rock!")
+       python generators rock!
+       >>> g.close()
+       """
+
+       @functools.wraps(func)
+       def start(*args, **kwargs):
+               cr = func(*args, **kwargs)
+               cr.next()
+               return cr
+
+       return start
+
+
+@autostart
+def printer_sink(format = "%s"):
+       """
+       >>> pr = printer_sink("%r")
+       >>> pr.send("Hello")
+       'Hello'
+       >>> pr.send("5")
+       '5'
+       >>> pr.send(5)
+       5
+       >>> p = printer_sink()
+       >>> p.send("Hello")
+       Hello
+       >>> p.send("World")
+       World
+       >>> # p.throw(RuntimeError, "Goodbye")
+       >>> # p.send("Meh")
+       >>> # p.close()
+       """
+       while True:
+               item = yield
+               print format % (item, )
+
+
+@autostart
+def null_sink():
+       """
+       Good for uses like with cochain to pick up any slack
+       """
+       while True:
+               item = yield
+
+
+@autostart
+def comap(function, target):
+       """
+       >>> p = printer_sink()
+       >>> cm = comap(lambda x: x+1, p)
+       >>> cm.send((0, ))
+       1
+       >>> cm.send((1.0, ))
+       2.0
+       >>> cm.send((-2, ))
+       -1
+       """
+       while True:
+               try:
+                       item = yield
+                       mappedItem = function(*item)
+                       target.send(mappedItem)
+               except Exception, e:
+                       _moduleLogger.exception("Forwarding exception!")
+                       target.throw(e.__class__, str(e))
+
+
+def _flush_queue(queue):
+       while not queue.empty():
+               yield queue.get()
+
+
+@autostart
+def queue_sink(queue):
+       """
+       >>> q = Queue.Queue()
+       >>> qs = queue_sink(q)
+       >>> qs.send("Hello")
+       >>> qs.send("World")
+       >>> qs.throw(RuntimeError, "Goodbye")
+       >>> qs.send("Meh")
+       >>> qs.close()
+       >>> print [i for i in _flush_queue(q)]
+       [(None, 'Hello'), (None, 'World'), (<type 'exceptions.RuntimeError'>, 'Goodbye'), (None, 'Meh'), (<type 'exceptions.GeneratorExit'>, None)]
+       """
+       while True:
+               try:
+                       item = yield
+                       queue.put((None, item))
+               except Exception, e:
+                       queue.put((e.__class__, str(e)))
+               except GeneratorExit:
+                       queue.put((GeneratorExit, None))
+                       raise
+
+
+def decode_item(item, target):
+       if item[0] is None:
+               target.send(item[1])
+               return False
+       elif item[0] is GeneratorExit:
+               target.close()
+               return True
+       else:
+               target.throw(item[0], item[1])
+               return False
+
+
+def nonqueue_source(queue, target):
+       isDone = False
+       while not isDone:
+               item = queue.get()
+               isDone = decode_item(item, target)
+               while not queue.empty():
+                       queue.get_nowait()
+
+
+def threaded_stage(target, thread_factory = threading.Thread):
+       messages = Queue.Queue()
+
+       run_source = functools.partial(nonqueue_source, messages, target)
+       thread = thread_factory(target=run_source)
+       thread.setDaemon(True)
+       thread.start()
+
+       # Sink running in current thread
+       return queue_sink(messages)
+
+
+def log_exception(logger):
+
+       def log_exception_decorator(func):
+
+               @functools.wraps(func)
+               def wrapper(*args, **kwds):
+                       try:
+                               return func(*args, **kwds)
+                       except Exception:
+                               logger.exception(func.__name__)
+
+               return wrapper
+
+       return log_exception_decorator
+
+
+class LoginWindow(object):
+
+       def __init__(self, widgetTree):
+               """
+               @note Thread agnostic
+               """
+               self._dialog = widgetTree.get_widget("loginDialog")
+               self._parentWindow = widgetTree.get_widget("mainWindow")
+               self._serviceCombo = widgetTree.get_widget("serviceCombo")
+               self._usernameEntry = widgetTree.get_widget("usernameentry")
+               self._passwordEntry = widgetTree.get_widget("passwordentry")
+
+               self._serviceList = gtk.ListStore(gobject.TYPE_INT, gobject.TYPE_STRING)
+               self._serviceCombo.set_model(self._serviceList)
+               cell = gtk.CellRendererText()
+               self._serviceCombo.pack_start(cell, True)
+               self._serviceCombo.add_attribute(cell, 'text', 1)
+               self._serviceCombo.set_active(0)
+
+               widgetTree.get_widget("loginbutton").connect("clicked", self._on_loginbutton_clicked)
+               widgetTree.get_widget("logins_close_button").connect("clicked", self._on_loginclose_clicked)
+
+       def request_credentials(self,
+               parentWindow = None,
+               defaultCredentials = ("", "")
+       ):
+               """
+               @note UI Thread
+               """
+               if parentWindow is None:
+                       parentWindow = self._parentWindow
+
+               self._serviceCombo.hide()
+               self._serviceList.clear()
+
+               self._usernameEntry.set_text(defaultCredentials[0])
+               self._passwordEntry.set_text(defaultCredentials[1])
+
+               try:
+                       self._dialog.set_transient_for(parentWindow)
+                       self._dialog.set_default_response(gtk.RESPONSE_OK)
+                       response = self._dialog.run()
+                       if response != gtk.RESPONSE_OK:
+                               raise RuntimeError("Login Cancelled")
+
+                       username = self._usernameEntry.get_text()
+                       password = self._passwordEntry.get_text()
+                       self._passwordEntry.set_text("")
+               finally:
+                       self._dialog.hide()
+
+               return username, password
+
+       def request_credentials_from(self,
+               services,
+               parentWindow = None,
+               defaultCredentials = ("", "")
+       ):
+               """
+               @note UI Thread
+               """
+               if parentWindow is None:
+                       parentWindow = self._parentWindow
+
+               self._serviceList.clear()
+               for serviceIdserviceName in services:
+                       self._serviceList.append(serviceIdserviceName)
+               self._serviceCombo.set_active(0)
+               self._serviceCombo.show()
+
+               self._usernameEntry.set_text(defaultCredentials[0])
+               self._passwordEntry.set_text(defaultCredentials[1])
+
+               try:
+                       self._dialog.set_transient_for(parentWindow)
+                       self._dialog.set_default_response(gtk.RESPONSE_OK)
+                       response = self._dialog.run()
+                       if response != gtk.RESPONSE_OK:
+                               raise RuntimeError("Login Cancelled")
+
+                       username = self._usernameEntry.get_text()
+                       password = self._passwordEntry.get_text()
+               finally:
+                       self._dialog.hide()
+
+               itr = self._serviceCombo.get_active_iter()
+               serviceId = int(self._serviceList.get_value(itr, 0))
+               self._serviceList.clear()
+               return serviceId, username, password
+
+       def _on_loginbutton_clicked(self, *args):
+               self._dialog.response(gtk.RESPONSE_OK)
+
+       def _on_loginclose_clicked(self, *args):
+               self._dialog.response(gtk.RESPONSE_CANCEL)
+
+
+def safecall(f, errorDisplay=None, default=None, exception=Exception):
+       '''
+       Returns modified f. When the modified f is called and throws an
+       exception, the default value is returned
+       '''
+       def _safecall(*args, **argv):
+               try:
+                       return f(*args,**argv)
+               except exception, e:
+                       if errorDisplay is not None:
+                               errorDisplay.push_exception(e)
+                       return default
+       return _safecall
+
+
+class ErrorDisplay(object):
+
+       def __init__(self, widgetTree):
+               super(ErrorDisplay, self).__init__()
+               self.__errorBox = widgetTree.get_widget("errorEventBox")
+               self.__errorDescription = widgetTree.get_widget("errorDescription")
+               self.__errorClose = widgetTree.get_widget("errorClose")
+               self.__parentBox = self.__errorBox.get_parent()
+
+               self.__errorBox.connect("button_release_event", self._on_close)
+
+               self.__messages = []
+               self.__parentBox.remove(self.__errorBox)
+
+       def push_message_with_lock(self, message):
+               with gtk_lock():
+                       self.push_message(message)
+
+       def push_message(self, message):
+               self.__messages.append(message)
+               if 1 == len(self.__messages):
+                       self.__show_message(message)
+
+       def push_exception_with_lock(self):
+               with gtk_lock():
+                       self.push_exception()
+
+       def push_exception(self):
+               userMessage = str(sys.exc_info()[1])
+               self.push_message(userMessage)
+               _moduleLogger.exception(userMessage)
+
+       def pop_message(self):
+               del self.__messages[0]
+               if 0 == len(self.__messages):
+                       self.__hide_message()
+               else:
+                       self.__errorDescription.set_text(self.__messages[0])
+
+       def _on_close(self, *args):
+               self.pop_message()
+
+       def __show_message(self, message):
+               self.__errorDescription.set_text(message)
+               self.__parentBox.pack_start(self.__errorBox, False, False)
+               self.__parentBox.reorder_child(self.__errorBox, 1)
+
+       def __hide_message(self):
+               self.__errorDescription.set_text("")
+               self.__parentBox.remove(self.__errorBox)
+
+
+class DummyErrorDisplay(object):
+
+       def __init__(self):
+               super(DummyErrorDisplay, self).__init__()
+
+               self.__messages = []
+
+       def push_message_with_lock(self, message):
+               self.push_message(message)
+
+       def push_message(self, message):
+               if 0 < len(self.__messages):
+                       self.__messages.append(message)
+               else:
+                       self.__show_message(message)
+
+       def push_exception(self, exception = None):
+               userMessage = str(sys.exc_value)
+               _moduleLogger.exception(userMessage)
+
+       def pop_message(self):
+               if 0 < len(self.__messages):
+                       self.__show_message(self.__messages[0])
+                       del self.__messages[0]
+
+       def __show_message(self, message):
+               _moduleLogger.debug(message)
+
+
+class MessageBox(gtk.MessageDialog):
+
+       def __init__(self, message):
+               parent = None
+               gtk.MessageDialog.__init__(
+                       self,
+                       parent,
+                       gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
+                       gtk.MESSAGE_ERROR,
+                       gtk.BUTTONS_OK,
+                       message,
+               )
+               self.set_default_response(gtk.RESPONSE_OK)
+               self.connect('response', self._handle_clicked)
+
+       def _handle_clicked(self, *args):
+               self.destroy()
+
+
+class MessageBox2(gtk.MessageDialog):
+
+       def __init__(self, message):
+               parent = None
+               gtk.MessageDialog.__init__(
+                       self,
+                       parent,
+                       gtk.DIALOG_DESTROY_WITH_PARENT,
+                       gtk.MESSAGE_ERROR,
+                       gtk.BUTTONS_OK,
+                       message,
+               )
+               self.set_default_response(gtk.RESPONSE_OK)
+               self.connect('response', self._handle_clicked)
+
+       def _handle_clicked(self, *args):
+               self.destroy()
+
+
+class PopupCalendar(object):
+
+       def __init__(self, parent, displayDate, title = ""):
+               self._displayDate = displayDate
+
+               self._calendar = gtk.Calendar()
+               self._calendar.select_month(self._displayDate.month, self._displayDate.year)
+               self._calendar.select_day(self._displayDate.day)
+               self._calendar.set_display_options(
+                       gtk.CALENDAR_SHOW_HEADING |
+                       gtk.CALENDAR_SHOW_DAY_NAMES |
+                       gtk.CALENDAR_NO_MONTH_CHANGE |
+                       0
+               )
+               self._calendar.connect("day-selected", self._on_day_selected)
+
+               self._popupWindow = gtk.Window()
+               self._popupWindow.set_title(title)
+               self._popupWindow.add(self._calendar)
+               self._popupWindow.set_transient_for(parent)
+               self._popupWindow.set_modal(True)
+               self._popupWindow.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG)
+               self._popupWindow.set_skip_pager_hint(True)
+               self._popupWindow.set_skip_taskbar_hint(True)
+
+       def run(self):
+               self._popupWindow.show_all()
+
+       def _on_day_selected(self, *args):
+               try:
+                       self._calendar.select_month(self._displayDate.month, self._displayDate.year)
+                       self._calendar.select_day(self._displayDate.day)
+               except Exception, e:
+                       _moduleLogger.exception(e)
+
+
+if __name__ == "__main__":
+       if False:
+               import datetime
+               cal = PopupCalendar(None, datetime.datetime.now())
+               cal._popupWindow.connect("destroy", lambda w: gtk.main_quit())
+               cal.run()
+
+       gtk.main()
diff --git a/src/hildonize.py b/src/hildonize.py
new file mode 100644 (file)
index 0000000..c07f09b
--- /dev/null
@@ -0,0 +1,766 @@
+#!/usr/bin/env python
+
+"""
+Open Issues
+       @bug not all of a message is shown
+       @bug Buttons are too small
+"""
+
+
+import gobject
+import gtk
+import dbus
+
+
+class _NullHildonModule(object):
+       pass
+
+
+try:
+       import hildon as _hildon
+       hildon  = _hildon # Dumb but gets around pyflakiness
+except (ImportError, OSError):
+       hildon = _NullHildonModule
+
+
+IS_HILDON_SUPPORTED = hildon is not _NullHildonModule
+
+
+class _NullHildonProgram(object):
+
+       def add_window(self, window):
+               pass
+
+
+def _hildon_get_app_class():
+       return hildon.Program
+
+
+def _null_get_app_class():
+       return _NullHildonProgram
+
+
+try:
+       hildon.Program
+       get_app_class = _hildon_get_app_class
+except AttributeError:
+       get_app_class = _null_get_app_class
+
+
+def _hildon_set_application_name(name):
+       gtk.set_application_name(name)
+
+
+def _null_set_application_name(name):
+       pass
+
+
+try:
+       gtk.set_application_name
+       set_application_name = _hildon_set_application_name
+except AttributeError:
+       set_application_name = _null_set_application_name
+
+
+def _fremantle_hildonize_window(app, window):
+       oldWindow = window
+       newWindow = hildon.StackableWindow()
+       if oldWindow.get_child() is not None:
+               oldWindow.get_child().reparent(newWindow)
+       app.add_window(newWindow)
+       return newWindow
+
+
+def _hildon_hildonize_window(app, window):
+       oldWindow = window
+       newWindow = hildon.Window()
+       if oldWindow.get_child() is not None:
+               oldWindow.get_child().reparent(newWindow)
+       app.add_window(newWindow)
+       return newWindow
+
+
+def _null_hildonize_window(app, window):
+       return window
+
+
+try:
+       hildon.StackableWindow
+       hildonize_window = _fremantle_hildonize_window
+except AttributeError:
+       try:
+               hildon.Window
+               hildonize_window = _hildon_hildonize_window
+       except AttributeError:
+               hildonize_window = _null_hildonize_window
+
+
+def _fremantle_hildonize_menu(window, gtkMenu):
+       appMenu = hildon.AppMenu()
+       window.set_app_menu(appMenu)
+       gtkMenu.get_parent().remove(gtkMenu)
+       return appMenu
+
+
+def _hildon_hildonize_menu(window, gtkMenu):
+       hildonMenu = gtk.Menu()
+       for child in gtkMenu.get_children():
+               child.reparent(hildonMenu)
+       window.set_menu(hildonMenu)
+       gtkMenu.destroy()
+       return hildonMenu
+
+
+def _null_hildonize_menu(window, gtkMenu):
+       return gtkMenu
+
+
+try:
+       hildon.AppMenu
+       GTK_MENU_USED = False
+       IS_FREMANTLE_SUPPORTED = True
+       hildonize_menu = _fremantle_hildonize_menu
+except AttributeError:
+       GTK_MENU_USED = True
+       IS_FREMANTLE_SUPPORTED = False
+       if IS_HILDON_SUPPORTED:
+               hildonize_menu = _hildon_hildonize_menu
+       else:
+               hildonize_menu = _null_hildonize_menu
+
+
+def _hildon_set_button_auto_selectable(button):
+       button.set_theme_size(hildon.HILDON_SIZE_AUTO_HEIGHT)
+
+
+def _null_set_button_auto_selectable(button):
+       pass
+
+
+try:
+       hildon.HILDON_SIZE_AUTO_HEIGHT
+       gtk.Button.set_theme_size
+       set_button_auto_selectable = _hildon_set_button_auto_selectable
+except AttributeError:
+       set_button_auto_selectable = _null_set_button_auto_selectable
+
+
+def _hildon_set_button_finger_selectable(button):
+       button.set_theme_size(hildon.HILDON_SIZE_FINGER_HEIGHT)
+
+
+def _null_set_button_finger_selectable(button):
+       pass
+
+
+try:
+       hildon.HILDON_SIZE_FINGER_HEIGHT
+       gtk.Button.set_theme_size
+       set_button_finger_selectable = _hildon_set_button_finger_selectable
+except AttributeError:
+       set_button_finger_selectable = _null_set_button_finger_selectable
+
+
+def _hildon_set_button_thumb_selectable(button):
+       button.set_theme_size(hildon.HILDON_SIZE_THUMB_HEIGHT)
+
+
+def _null_set_button_thumb_selectable(button):
+       pass
+
+
+try:
+       hildon.HILDON_SIZE_THUMB_HEIGHT
+       gtk.Button.set_theme_size
+       set_button_thumb_selectable = _hildon_set_button_thumb_selectable
+except AttributeError:
+       set_button_thumb_selectable = _null_set_button_thumb_selectable
+
+
+def _hildon_set_cell_thumb_selectable(renderer):
+       renderer.set_property("scale", 1.5)
+
+
+def _null_set_cell_thumb_selectable(renderer):
+       renderer.set_property("scale", 1.5)
+
+
+if IS_HILDON_SUPPORTED:
+       set_cell_thumb_selectable = _hildon_set_cell_thumb_selectable
+else:
+       set_cell_thumb_selectable = _null_set_cell_thumb_selectable
+
+
+def _hildon_set_pix_cell_thumb_selectable(renderer):
+       renderer.set_property("stock-size", 48)
+
+
+def _null_set_pix_cell_thumb_selectable(renderer):
+       pass
+
+
+if IS_HILDON_SUPPORTED:
+       set_pix_cell_thumb_selectable = _hildon_set_pix_cell_thumb_selectable
+else:
+       set_pix_cell_thumb_selectable = _null_set_pix_cell_thumb_selectable
+
+
+def _fremantle_show_information_banner(parent, message):
+       hildon.hildon_banner_show_information(parent, "", message)
+
+
+def _hildon_show_information_banner(parent, message):
+       hildon.hildon_banner_show_information(parent, None, message)
+
+
+def _null_show_information_banner(parent, message):
+       pass
+
+
+if IS_FREMANTLE_SUPPORTED:
+       show_information_banner = _fremantle_show_information_banner
+else:
+       try:
+               hildon.hildon_banner_show_information
+               show_information_banner = _hildon_show_information_banner
+       except AttributeError:
+               show_information_banner = _null_show_information_banner
+
+
+def _fremantle_show_busy_banner_start(parent, message):
+       hildon.hildon_gtk_window_set_progress_indicator(parent, True)
+       return parent
+
+
+def _fremantle_show_busy_banner_end(banner):
+       hildon.hildon_gtk_window_set_progress_indicator(banner, False)
+
+
+def _hildon_show_busy_banner_start(parent, message):
+       return hildon.hildon_banner_show_animation(parent, None, message)
+
+
+def _hildon_show_busy_banner_end(banner):
+       banner.destroy()
+
+
+def _null_show_busy_banner_start(parent, message):
+       return None
+
+
+def _null_show_busy_banner_end(banner):
+       assert banner is None
+
+
+try:
+       hildon.hildon_gtk_window_set_progress_indicator
+       show_busy_banner_start = _fremantle_show_busy_banner_start
+       show_busy_banner_end = _fremantle_show_busy_banner_end
+except AttributeError:
+       try:
+               hildon.hildon_banner_show_animation
+               show_busy_banner_start = _hildon_show_busy_banner_start
+               show_busy_banner_end = _hildon_show_busy_banner_end
+       except AttributeError:
+               show_busy_banner_start = _null_show_busy_banner_start
+               show_busy_banner_end = _null_show_busy_banner_end
+
+
+def _hildon_hildonize_text_entry(textEntry):
+       textEntry.set_property('hildon-input-mode', 7)
+
+
+def _null_hildonize_text_entry(textEntry):
+       pass
+
+
+if IS_HILDON_SUPPORTED:
+       hildonize_text_entry = _hildon_hildonize_text_entry
+else:
+       hildonize_text_entry = _null_hildonize_text_entry
+
+
+def _hildon_window_to_portrait(window):
+       # gtk documentation is unclear whether this does a "=" or a "|="
+       flags = hildon.PORTRAIT_MODE_SUPPORT | hildon.PORTRAIT_MODE_REQUEST
+       hildon.hildon_gtk_window_set_portrait_flags(window, flags)
+
+
+def _hildon_window_to_landscape(window):
+       # gtk documentation is unclear whether this does a "=" or a "&= ~"
+       flags = hildon.PORTRAIT_MODE_SUPPORT
+       hildon.hildon_gtk_window_set_portrait_flags(window, flags)
+
+
+def _null_window_to_portrait(window):
+       pass
+
+
+def _null_window_to_landscape(window):
+       pass
+
+
+try:
+       hildon.PORTRAIT_MODE_SUPPORT
+       hildon.PORTRAIT_MODE_REQUEST
+       hildon.hildon_gtk_window_set_portrait_flags
+
+       window_to_portrait = _hildon_window_to_portrait
+       window_to_landscape = _hildon_window_to_landscape
+except AttributeError:
+       window_to_portrait = _null_window_to_portrait
+       window_to_landscape = _null_window_to_landscape
+
+
+def get_device_orientation():
+       bus = dbus.SystemBus()
+       try:
+               rawMceRequest = bus.get_object("com.nokia.mce", "/com/nokia/mce/request")
+               mceRequest = dbus.Interface(rawMceRequest, dbus_interface="com.nokia.mce.request")
+               orientation, standState, faceState, xAxis, yAxis, zAxis = mceRequest.get_device_orientation()
+       except dbus.exception.DBusException:
+               # catching for documentation purposes that when a system doesn't
+               # support this, this is what to expect
+               raise
+
+       if orientation == "":
+               return gtk.ORIENTATION_HORIZONTAL
+       elif orientation == "":
+               return gtk.ORIENTATION_VERTICAL
+       else:
+               raise RuntimeError("Unknown orientation: %s" % orientation)
+
+
+def _hildon_hildonize_password_entry(textEntry):
+       textEntry.set_property('hildon-input-mode', 7 | (1 << 29))
+
+
+def _null_hildonize_password_entry(textEntry):
+       pass
+
+
+if IS_HILDON_SUPPORTED:
+       hildonize_password_entry = _hildon_hildonize_password_entry
+else:
+       hildonize_password_entry = _null_hildonize_password_entry
+
+
+def _hildon_hildonize_combo_entry(comboEntry):
+       comboEntry.set_property('hildon-input-mode', 1 << 4)
+
+
+def _null_hildonize_combo_entry(textEntry):
+       pass
+
+
+if IS_HILDON_SUPPORTED:
+       hildonize_combo_entry = _hildon_hildonize_combo_entry
+else:
+       hildonize_combo_entry = _null_hildonize_combo_entry
+
+
+def _null_create_seekbar():
+       adjustment = gtk.Adjustment(0, 0, 101, 1, 5, 1)
+       seek = gtk.HScale(adjustment)
+       seek.set_draw_value(False)
+       return seek
+
+
+def _fremantle_create_seekbar():
+       seek = hildon.Seekbar()
+       seek.set_range(0.0, 100)
+       seek.set_draw_value(False)
+       seek.set_update_policy(gtk.UPDATE_DISCONTINUOUS)
+       return seek
+
+
+try:
+       hildon.Seekbar
+       create_seekbar = _fremantle_create_seekbar
+except AttributeError:
+       create_seekbar = _null_create_seekbar
+
+
+def _fremantle_hildonize_scrollwindow(scrolledWindow):
+       pannableWindow = hildon.PannableArea()
+
+       child = scrolledWindow.get_child()
+       scrolledWindow.remove(child)
+       pannableWindow.add(child)
+
+       parent = scrolledWindow.get_parent()
+       if parent is not None:
+               parent.remove(scrolledWindow)
+               parent.add(pannableWindow)
+
+       return pannableWindow
+
+
+def _hildon_hildonize_scrollwindow(scrolledWindow):
+       hildon.hildon_helper_set_thumb_scrollbar(scrolledWindow, True)
+       return scrolledWindow
+
+
+def _null_hildonize_scrollwindow(scrolledWindow):
+       return scrolledWindow
+
+
+try:
+       hildon.PannableArea
+       hildonize_scrollwindow = _fremantle_hildonize_scrollwindow
+       hildonize_scrollwindow_with_viewport = _hildon_hildonize_scrollwindow
+except AttributeError:
+       try:
+               hildon.hildon_helper_set_thumb_scrollbar
+               hildonize_scrollwindow = _hildon_hildonize_scrollwindow
+               hildonize_scrollwindow_with_viewport = _hildon_hildonize_scrollwindow
+       except AttributeError:
+               hildonize_scrollwindow = _null_hildonize_scrollwindow
+               hildonize_scrollwindow_with_viewport = _null_hildonize_scrollwindow
+
+
+def _hildon_request_number(parent, title, range, default):
+       spinner = hildon.NumberEditor(*range)
+       spinner.set_value(default)
+
+       dialog = gtk.Dialog(
+               title,
+               parent,
+               gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
+               (gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
+       )
+       dialog.set_default_response(gtk.RESPONSE_CANCEL)
+       dialog.get_child().add(spinner)
+
+       try:
+               dialog.show_all()
+               response = dialog.run()
+
+               if response == gtk.RESPONSE_OK:
+                       return spinner.get_value()
+               elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
+                       raise RuntimeError("User cancelled request")
+               else:
+                       raise RuntimeError("Unrecognized response %r", response)
+       finally:
+               dialog.hide()
+               dialog.destroy()
+
+
+def _null_request_number(parent, title, range, default):
+       adjustment = gtk.Adjustment(default, range[0], range[1], 1, 5, 0)
+       spinner = gtk.SpinButton(adjustment, 0, 0)
+       spinner.set_wrap(False)
+
+       dialog = gtk.Dialog(
+               title,
+               parent,
+               gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
+               (gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
+       )
+       dialog.set_default_response(gtk.RESPONSE_CANCEL)
+       dialog.get_child().add(spinner)
+
+       try:
+               dialog.show_all()
+               response = dialog.run()
+
+               if response == gtk.RESPONSE_OK:
+                       return spinner.get_value_as_int()
+               elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
+                       raise RuntimeError("User cancelled request")
+               else:
+                       raise RuntimeError("Unrecognized response %r", response)
+       finally:
+               dialog.hide()
+               dialog.destroy()
+
+
+try:
+       hildon.NumberEditor # TODO deprecated in fremantle
+       request_number = _hildon_request_number
+except AttributeError:
+       request_number = _null_request_number
+
+
+def _hildon_touch_selector(parent, title, items, defaultIndex):
+       model = gtk.ListStore(gobject.TYPE_STRING)
+       for item in items:
+               model.append((item, ))
+
+       selector = hildon.TouchSelector()
+       selector.append_text_column(model, True)
+       selector.set_column_selection_mode(hildon.TOUCH_SELECTOR_SELECTION_MODE_SINGLE)
+       selector.set_active(0, defaultIndex)
+
+       dialog = hildon.PickerDialog(parent)
+       dialog.set_selector(selector)
+
+       try:
+               dialog.show_all()
+               response = dialog.run()
+
+               if response == gtk.RESPONSE_OK:
+                       return selector.get_active(0)
+               elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
+                       raise RuntimeError("User cancelled request")
+               else:
+                       raise RuntimeError("Unrecognized response %r", response)
+       finally:
+               dialog.hide()
+               dialog.destroy()
+
+
+def _on_null_touch_selector_activated(treeView, path, column, dialog, pathData):
+       dialog.response(gtk.RESPONSE_OK)
+       pathData[0] = path
+
+
+def _null_touch_selector(parent, title, items, defaultIndex = -1):
+       parentSize = parent.get_size()
+
+       model = gtk.ListStore(gobject.TYPE_STRING)
+       for item in items:
+               model.append((item, ))
+
+       cell = gtk.CellRendererText()
+       set_cell_thumb_selectable(cell)
+       column = gtk.TreeViewColumn(title)
+       column.pack_start(cell, expand=True)
+       column.add_attribute(cell, "text", 0)
+
+       treeView = gtk.TreeView()
+       treeView.set_model(model)
+       treeView.append_column(column)
+       selection = treeView.get_selection()
+       selection.set_mode(gtk.SELECTION_SINGLE)
+       if 0 < defaultIndex:
+               selection.select_path((defaultIndex, ))
+
+       scrolledWin = gtk.ScrolledWindow()
+       scrolledWin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
+       scrolledWin.add(treeView)
+
+       dialog = gtk.Dialog(
+               title,
+               parent,
+               gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
+               (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
+       )
+       dialog.set_default_response(gtk.RESPONSE_CANCEL)
+       dialog.get_child().add(scrolledWin)
+       dialog.resize(parentSize[0], max(parentSize[1]-100, 100))
+
+       scrolledWin = hildonize_scrollwindow(scrolledWin)
+       pathData = [None]
+       treeView.connect("row-activated", _on_null_touch_selector_activated, dialog, pathData)
+
+       try:
+               dialog.show_all()
+               response = dialog.run()
+
+               if response == gtk.RESPONSE_OK:
+                       if pathData[0] is None:
+                               raise RuntimeError("No selection made")
+                       return pathData[0][0]
+               elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
+                       raise RuntimeError("User cancelled request")
+               else:
+                       raise RuntimeError("Unrecognized response %r", response)
+       finally:
+               dialog.hide()
+               dialog.destroy()
+
+
+try:
+       hildon.PickerDialog
+       hildon.TouchSelector
+       touch_selector = _hildon_touch_selector
+except AttributeError:
+       touch_selector = _null_touch_selector
+
+
+def _hildon_touch_selector_entry(parent, title, items, defaultItem):
+       # Got a segfault when using append_text_column with TouchSelectorEntry, so using this way
+       try:
+               selector = hildon.TouchSelectorEntry(text=True)
+       except TypeError:
+               selector = hildon.hildon_touch_selector_entry_new_text()
+       defaultIndex = -1
+       for i, item in enumerate(items):
+               selector.append_text(item)
+               if item == defaultItem:
+                       defaultIndex = i
+
+       dialog = hildon.PickerDialog(parent)
+       dialog.set_selector(selector)
+
+       if 0 < defaultIndex:
+               selector.set_active(0, defaultIndex)
+       else:
+               selector.get_entry().set_text(defaultItem)
+
+       try:
+               dialog.show_all()
+               response = dialog.run()
+       finally:
+               dialog.hide()
+
+       if response == gtk.RESPONSE_OK:
+               return selector.get_entry().get_text()
+       elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
+               raise RuntimeError("User cancelled request")
+       else:
+               raise RuntimeError("Unrecognized response %r", response)
+
+
+def _on_null_touch_selector_entry_entry_changed(entry, result, selection, defaultIndex):
+       custom = entry.get_text().strip()
+       if custom:
+               result[0] = custom
+               selection.unselect_all()
+       else:
+               result[0] = None
+               selection.select_path((defaultIndex, ))
+
+
+def _on_null_touch_selector_entry_entry_activated(customEntry, dialog, result):
+       dialog.response(gtk.RESPONSE_OK)
+       result[0] = customEntry.get_text()
+
+
+def _on_null_touch_selector_entry_tree_activated(treeView, path, column, dialog, result):
+       dialog.response(gtk.RESPONSE_OK)
+       model = treeView.get_model()
+       itr = model.get_iter(path)
+       if itr is not None:
+               result[0] = model.get_value(itr, 0)
+
+
+def _null_touch_selector_entry(parent, title, items, defaultItem):
+       parentSize = parent.get_size()
+
+       model = gtk.ListStore(gobject.TYPE_STRING)
+       defaultIndex = -1
+       for i, item in enumerate(items):
+               model.append((item, ))
+               if item == defaultItem:
+                       defaultIndex = i
+
+       cell = gtk.CellRendererText()
+       set_cell_thumb_selectable(cell)
+       column = gtk.TreeViewColumn(title)
+       column.pack_start(cell, expand=True)
+       column.add_attribute(cell, "text", 0)
+
+       treeView = gtk.TreeView()
+       treeView.set_model(model)
+       treeView.append_column(column)
+       selection = treeView.get_selection()
+       selection.set_mode(gtk.SELECTION_SINGLE)
+
+       scrolledWin = gtk.ScrolledWindow()
+       scrolledWin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
+       scrolledWin.add(treeView)
+
+       customEntry = gtk.Entry()
+
+       layout = gtk.VBox()
+       layout.pack_start(customEntry, expand=False)
+       layout.pack_start(scrolledWin)
+
+       dialog = gtk.Dialog(
+               title,
+               parent,
+               gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
+               (gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL),
+       )
+       dialog.set_default_response(gtk.RESPONSE_CANCEL)
+       dialog.get_child().add(layout)
+       dialog.resize(parentSize[0], max(parentSize[1]-100, 100))
+
+       scrolledWin = hildonize_scrollwindow(scrolledWin)
+
+       result = [None]
+       if 0 < defaultIndex:
+               selection.select_path((defaultIndex, ))
+               result[0] = defaultItem
+       else:
+               customEntry.set_text(defaultItem)
+
+       customEntry.connect("activate", _on_null_touch_selector_entry_entry_activated, dialog, result)
+       customEntry.connect("changed", _on_null_touch_selector_entry_entry_changed, result, selection, defaultIndex)
+       treeView.connect("row-activated", _on_null_touch_selector_entry_tree_activated, dialog, result)
+
+       try:
+               dialog.show_all()
+               response = dialog.run()
+
+               if response == gtk.RESPONSE_OK:
+                       _, itr = selection.get_selected()
+                       if itr is not None:
+                               return model.get_value(itr, 0)
+                       else:
+                               enteredText = customEntry.get_text().strip()
+                               if enteredText:
+                                       return enteredText
+                               elif result[0] is not None:
+                                       return result[0]
+                               else:
+                                       raise RuntimeError("No selection made")
+               elif response == gtk.RESPONSE_CANCEL or response == gtk.RESPONSE_DELETE_EVENT:
+                       raise RuntimeError("User cancelled request")
+               else:
+                       raise RuntimeError("Unrecognized response %r", response)
+       finally:
+               dialog.hide()
+               dialog.destroy()
+
+
+try:
+       hildon.PickerDialog
+       hildon.TouchSelectorEntry
+       touch_selector_entry = _hildon_touch_selector_entry
+except AttributeError:
+       touch_selector_entry = _null_touch_selector_entry
+
+
+if __name__ == "__main__":
+       app = get_app_class()()
+
+       label = gtk.Label("Hello World from a Label!")
+
+       win = gtk.Window()
+       win.add(label)
+       win = hildonize_window(app, win)
+       if False and IS_FREMANTLE_SUPPORTED:
+               appMenu = hildon.AppMenu()
+               for i in xrange(5):
+                       b = gtk.Button(str(i))
+                       appMenu.append(b)
+               win.set_app_menu(appMenu)
+               win.show_all()
+               appMenu.show_all()
+               gtk.main()
+       elif False:
+               print touch_selector(win, "Test", ["A", "B", "C", "D"], 2)
+       elif False:
+               print touch_selector_entry(win, "Test", ["A", "B", "C", "D"], "C")
+               print touch_selector_entry(win, "Test", ["A", "B", "C", "D"], "Blah")
+       elif False:
+               import pprint
+               name, value = "", ""
+               goodLocals = [
+                       (name, value) for (name, value) in locals().iteritems()
+                       if not name.startswith("_")
+               ]
+               pprint.pprint(goodLocals)
+       elif False:
+               import time
+               show_information_banner(win, "Hello World")
+               time.sleep(5)
+       elif False:
+               import time
+               banner = show_busy_banner_start(win, "Hello World")
+               time.sleep(5)
+               show_busy_banner_end(banner)
diff --git a/src/imagestore.py b/src/imagestore.py
new file mode 100644 (file)
index 0000000..0cb4813
--- /dev/null
@@ -0,0 +1,138 @@
+from __future__ import with_statement
+
+import os
+import logging
+
+import cairo
+import gtk
+
+import browser_emu
+from util import go_utils
+import util.misc as misc_utils
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class ImageStore(object):
+
+       STORE_LOOKUP = {
+               "next": "next.png",
+               "prev": "prev.png",
+               "home": "home.png",
+               "pause": "pause.png",
+               "play": "play.png",
+               "stop": "stop.png",
+               "pause_pressed": "pausepressed.png",
+               "play_pressed": "playpressed.png",
+               "stop_pressed": "stoppressed.png",
+
+               "small_next": "small_next.png",
+               "small_prev": "small_prev.png",
+               "small_home": "small_home.png",
+               "small_pause": "small_pause.png",
+               "small_play": "small_play.png",
+               "small_stop": "small_stop.png",
+               "small_pause_pressed": "small_pausepressed.png",
+               "small_play_pressed": "small_playpressed.png",
+               "small_stop_pressed": "small_stoppressed.png",
+
+               "loading": "loading.gif",
+
+               "radio_header": "radio_header.png",
+               "conference_background": "conference_bg.png",
+               "magazine_background": "magazine_bg.png",
+               "scripture_background": "scripture_bg.png",
+
+               "conferences": "conference.png",
+               "magazines": "magazines.png",
+               "mormonmessages": "mormonmessages.png",
+               "radio": "radio.png",
+               "scriptures": "scriptures.png",
+
+               "more": "more.png",
+               "icon": "icon.png",
+               "nomagazineimage": "nomagazineimage.png",
+       }
+
+       def __init__(self, storePath, cachePath):
+               self._storePath = storePath
+               self._cachePath = cachePath
+
+               self._browser = browser_emu.MozillaEmulator()
+               self._downloader = go_utils.AsyncPool()
+
+       def start(self):
+               self._downloader.start()
+
+       def stop(self):
+               self._downloader.stop()
+
+       def get_surface_from_store(self, imageName):
+               path = os.path.join(self._storePath, imageName)
+               image = cairo.ImageSurface.create_from_png(path)
+               return image
+
+       def get_image_from_store(self, imageName):
+               path = os.path.join(self._storePath, imageName)
+               image = gtk.Image()
+               image.set_from_file(path)
+               return image
+
+       def set_image_from_store(self, image, imageName):
+               path = os.path.join(self._storePath, imageName)
+               image.set_from_file(path)
+               return image
+
+       def get_pixbuf_from_store(self, imageName):
+               path = os.path.join(self._storePath, imageName)
+               return gtk.gdk.pixbuf_new_from_file(path)
+
+       def get_pixbuf_from_url(self, url, on_success, on_error):
+               # @ todo Test bad image for both paths
+               filepath = self._url_to_cache(url)
+               if os.path.exists(filepath):
+                       pix = gtk.gdk.pixbuf_new_from_file(filepath)
+                       try:
+                               on_success(pix)
+                       except Exception:
+                               pass
+                       doDownload = False
+               else:
+                       doDownload = True
+
+               if doDownload:
+                       self._get_image(
+                               url,
+                               lambda filepath: on_success(gtk.gdk.pixbuf_new_from_file(filepath)),
+                               on_error,
+                       )
+
+       def get_pixbuf_animation_from_store(self, imageName):
+               path = os.path.join(self._storePath, imageName)
+               return gtk.gdk.PixbufAnimation(path)
+
+       def _get_image(self, url, on_success, on_error):
+               self._downloader.add_task(
+                       self._browser.download,
+                       (url, ),
+                       {},
+                       lambda image: self._on_get_image(url, image, on_success, on_error),
+                       on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_get_image(self, url, image, on_success, on_error):
+               try:
+                       filepath = self._url_to_cache(url)
+                       _moduleLogger.info("Saved %s" % filepath)
+                       with open(filepath, "wb") as f:
+                               f.write(image)
+                       on_success(filepath)
+               except Exception, e:
+                       on_error(e)
+
+       def _url_to_cache(self, url):
+               filename = url.rsplit("/", 1)[-1]
+               filepath = os.path.join(self._cachePath, filename)
+               return filepath
diff --git a/src/mormonchannel_gtk.py b/src/mormonchannel_gtk.py
new file mode 100755 (executable)
index 0000000..e706a94
--- /dev/null
@@ -0,0 +1,158 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+@todo Need to confirm id's are persistent (not just for todos but broken behavior on transition)
+       @todo Track recent
+       @todo Persisted Pause
+       @todo Favorites
+@todo Sleep timer
+@todo Podcast integration
+       @todo Default with BYU Devotionals, http://speeches.byu.edu/?act=help&page=podcast
+       @todo Mormon Messages
+@todo Reverse order option.  Toggle between playing ascending/descending chronological order
+@todo Jump to website
+@todo Offline mode
+@todo Re-use windows for better performance
+@todo Make radio program updates only happen when the app has focus to reduce CPU wakes
+"""
+
+from __future__ import with_statement
+
+import os
+import gc
+import logging
+import ConfigParser
+
+import gobject
+import dbus
+import dbus.mainloop.glib
+import gtk
+
+try:
+       import osso
+except ImportError:
+       osso = None
+
+import constants
+import hildonize
+import util.misc as misc_utils
+
+import imagestore
+import player
+import stream_index
+import windows
+
+
+_moduleLogger = logging.getLogger(__name__)
+PROFILE_STARTUP = False
+
+
+class MormonChannelProgram(hildonize.get_app_class()):
+
+       def __init__(self):
+               super(MormonChannelProgram, self).__init__()
+               currentPath = os.path.abspath(__file__)
+               storePath = os.path.join(os.path.split(os.path.dirname(currentPath))[0], "data")
+               self._store = imagestore.ImageStore(storePath, constants._cache_path_)
+               self._index = stream_index.AudioIndex()
+               self._player = player.Player(self._index)
+
+               self._store.start()
+               self._index.start()
+               try:
+                       if not hildonize.IS_HILDON_SUPPORTED:
+                               _moduleLogger.info("No hildonization support")
+
+                       if osso is not None:
+                               self._osso_c = osso.Context(constants.__app_name__, constants.__version__, False)
+                               self._deviceState = osso.DeviceState(self._osso_c)
+                               self._deviceState.set_device_state_callback(self._on_device_state_change, 0)
+                       else:
+                               _moduleLogger.info("No osso support")
+                               self._osso_c = None
+                               self._deviceState = None
+
+                       self._sourceSelector = windows.source.SourceSelector(self, self._player, self._store, self._index)
+                       self._sourceSelector.window.connect("destroy", self._on_destroy)
+                       self._sourceSelector.window.set_default_size(400, 800)
+                       self._sourceSelector.show()
+                       self._load_settings()
+               except:
+                       self._index.stop()
+                       self._store.stop()
+                       raise
+
+       def _save_settings(self):
+               config = ConfigParser.SafeConfigParser()
+
+               self._sourceSelector.save_settings(config, "Windows")
+
+               with open(constants._user_settings_, "wb") as configFile:
+                       config.write(configFile)
+
+       def _load_settings(self):
+               config = ConfigParser.SafeConfigParser()
+               config.read(constants._user_settings_)
+
+               self._sourceSelector.load_settings(config, "Windows")
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_device_state_change(self, shutdown, save_unsaved_data, memory_low, system_inactivity, message, userData):
+               """
+               For system_inactivity, we have no background tasks to pause
+
+               @note Hildon specific
+               """
+               if memory_low:
+                       gc.collect()
+
+               if save_unsaved_data or shutdown:
+                       self._save_settings()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_destroy(self, widget = None, data = None):
+               try:
+                       self.quit()
+               finally:
+                       gtk.main_quit()
+
+       def quit(self):
+               self._save_settings()
+
+               self._player.stop()
+               self._index.stop()
+               self._store.stop()
+
+               try:
+                       self._deviceState.close()
+               except AttributeError:
+                       pass # Either None or close was removed (in Fremantle)
+               try:
+                       self._osso_c.close()
+               except AttributeError:
+                       pass # Either None or close was removed (in Fremantle)
+
+
+def run():
+       gobject.threads_init()
+       gtk.gdk.threads_init()
+       l = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
+
+       # HACK Playback while silent on Maemo 5
+       hildonize.set_application_name("FMRadio")
+
+       app = MormonChannelProgram()
+       if not PROFILE_STARTUP:
+               try:
+                       gtk.main()
+               except KeyboardInterrupt:
+                       app.quit()
+                       raise
+       else:
+               app.quit()
+
+
+if __name__ == "__main__":
+       logging.basicConfig(level=logging.DEBUG)
+       run()
diff --git a/src/player.py b/src/player.py
new file mode 100644 (file)
index 0000000..1b1494e
--- /dev/null
@@ -0,0 +1,173 @@
+import logging
+
+import gobject
+
+import util.misc as misc_utils
+import stream
+import stream_index
+import call_monitor
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class Player(gobject.GObject):
+
+       __gsignals__ = {
+               'state_change' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_PYOBJECT, ),
+               ),
+               'title_change' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_PYOBJECT, ),
+               ),
+               'error' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT),
+               ),
+       }
+
+       STATE_PLAY = stream.GSTStream.STATE_PLAY
+       STATE_PAUSE = stream.GSTStream.STATE_PAUSE
+       STATE_STOP = stream.GSTStream.STATE_STOP
+
+       def __init__(self, index):
+               gobject.GObject.__init__(self)
+               self._index = index
+               self._node = None
+               self._nextSearch = None
+
+               self._calls = call_monitor.CallMonitor()
+               self._calls.connect("call_start", self._on_call_start)
+
+               self._stream = stream.GSTStream()
+               self._stream.connect("state-change", self._on_stream_state)
+               self._stream.connect("eof", self._on_stream_eof)
+               self._stream.connect("error", self._on_stream_error)
+
+       def set_piece_by_node(self, node):
+               self._set_piece_by_node(node)
+
+       @property
+       def node(self):
+               return self._node
+
+       @property
+       def title(self):
+               if self._node is None:
+                       return ""
+               return self._node.title
+
+       @property
+       def subtitle(self):
+               if self._node is None:
+                       return ""
+               return self._node.subtitle
+
+       @property
+       def can_navigate(self):
+               if self._node is None:
+                       return False
+               return self.node.can_navigate
+
+       @property
+       def state(self):
+               return self._stream.state
+
+       def play(self):
+               _moduleLogger.info("play")
+               self._stream.play()
+
+               self._calls.start()
+
+       def pause(self):
+               _moduleLogger.info("pause")
+               self._stream.pause()
+
+       def stop(self):
+               _moduleLogger.info("stop")
+               self._stream.stop()
+               self.set_piece_by_node(None)
+
+               self._calls.stop()
+
+       def back(self, forcePlay = False):
+               _moduleLogger.info("back")
+               assert self._nextSearch is None
+               self._nextSearch = stream_index.AsyncWalker(stream_index.get_previous)
+               self._nextSearch.start(
+                       self.node,
+                       lambda node: self._on_next_node(node, forcePlay),
+                       self._on_node_search_error
+               )
+
+       def next(self, forcePlay = False):
+               _moduleLogger.info("next")
+               assert self._nextSearch is None
+               self._nextSearch = stream_index.AsyncWalker(stream_index.get_next)
+               self._nextSearch.start(
+                       self.node,
+                       lambda node: self._on_next_node(node, forcePlay),
+                       self._on_node_search_error
+               )
+
+       def seek(self, percent):
+               target = percent * self._stream.duration
+               self._stream.seek_time(target)
+
+       @property
+       def percent_elapsed(self):
+               percent = float(self._stream.elapsed) / float(self._stream.duration)
+               return percent
+
+       def _set_piece_by_node(self, node):
+               assert node is None or node.is_leaf(), node
+               if self._node is node:
+                       _moduleLogger.info("Already set to %r" % node)
+                       return
+               self._node = node
+               if self._node is not None:
+                       self._stream.set_file(self._node.uri)
+               _moduleLogger.info("New node %r" % self._node)
+               self.emit("title_change", self._node)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_next_node(self, node, forcePlay):
+               self._nextSearch = None
+
+               restart = self.state == self.STATE_PLAY
+               self._set_piece_by_node(node)
+               if restart or forcePlay:
+                       self.play()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_node_search_error(self, e):
+               self._nextSearch = None
+               self.emit("error", e, "")
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_stream_state(self, s, state):
+               _moduleLogger.info("State change %r" % state)
+               self.emit("state_change", state)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_stream_eof(self, s, uri):
+               _moduleLogger.info("EOF %s" % uri)
+               self.next(forcePlay = True)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_stream_error(self, s, error, debug):
+               _moduleLogger.info("Error %s %s" % (error, debug))
+               self.emit("error", error, debug)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_call_start(self, monitor):
+               _moduleLogger.info("Call in progress, pausing")
+               self.pause()
+
+
+gobject.type_register(Player)
diff --git a/src/presenter.py b/src/presenter.py
new file mode 100644 (file)
index 0000000..e549c66
--- /dev/null
@@ -0,0 +1,402 @@
+import logging
+
+import gobject
+import pango
+import gtk
+
+import util.go_utils as go_utils
+import util.misc as misc_utils
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class NavigationBox(gobject.GObject):
+
+       __gsignals__ = {
+               'action' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_STRING, ),
+               ),
+               'navigating' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_STRING, ),
+               ),
+       }
+
+       MINIMUM_MOVEMENT = 32
+
+       _NO_POSITION = -1, -1
+
+       def __init__(self):
+               gobject.GObject.__init__(self)
+               self._eventBox = gtk.EventBox()
+               self._eventBox.connect("button_press_event", self._on_button_press)
+               self._eventBox.connect("button_release_event", self._on_button_release)
+               self._eventBox.connect("motion_notify_event", self._on_motion_notify)
+
+               self._isPortrait = True
+               self._clickPosition = self._NO_POSITION
+
+       @property
+       def toplevel(self):
+               return self._eventBox
+
+       def set_orientation(self, orientation):
+               if orientation == gtk.ORIENTATION_VERTICAL:
+                       self._isPortrait = True
+               elif orientation == gtk.ORIENTATION_HORIZONTAL:
+                       self._isPortrait = False
+               else:
+                       raise NotImplementedError(orientation)
+
+       def is_active(self):
+               return self._clickPosition != self._NO_POSITION
+
+       def get_state(self, newCoord):
+               if self._clickPosition == self._NO_POSITION:
+                       return ""
+
+               delta = (
+                       newCoord[0] - self._clickPosition[0],
+                       - (newCoord[1] - self._clickPosition[1])
+               )
+               absDelta = (abs(delta[0]), abs(delta[1]))
+               if max(*absDelta) < self.MINIMUM_MOVEMENT:
+                       return "clicking"
+
+               if absDelta[0] < absDelta[1]:
+                       if 0 < delta[1]:
+                               return "up"
+                       else:
+                               return "down"
+               else:
+                       if 0 < delta[0]:
+                               return "right"
+                       else:
+                               return "left"
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_button_press(self, widget, event):
+               if self._clickPosition != self._NO_POSITION:
+                       _moduleLogger.debug("Ignoring double click")
+               self._clickPosition = event.get_coords()
+
+               self.emit("navigating", "clicking")
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_button_release(self, widget, event):
+               assert self._clickPosition != self._NO_POSITION
+               try:
+                       mousePosition = event.get_coords()
+                       state = self.get_state(mousePosition)
+                       assert state
+               finally:
+                       self._clickPosition = self._NO_POSITION
+               self.emit("action", state)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_motion_notify(self, widget, event):
+               if self._clickPosition == self._NO_POSITION:
+                       return
+
+               mousePosition = event.get_coords()
+               newState = self.get_state(mousePosition)
+               self.emit("navigating", newState)
+
+
+gobject.type_register(NavigationBox)
+
+
+class StreamPresenter(object):
+
+       def __init__(self, store):
+               self._store = store
+
+               self._image = gtk.DrawingArea()
+               self._image.connect("expose_event", self._on_expose)
+
+               self._isPortrait = True
+
+               self._backgroundImage = None
+               self._title = ""
+               self._subtitle = ""
+               self._buttonImage = None
+               self._imageName = ""
+               self._dims = 0, 0
+
+       @property
+       def toplevel(self):
+               return self._image
+
+       def set_orientation(self, orientation):
+               if orientation == gtk.ORIENTATION_VERTICAL:
+                       self._isPortrait = True
+               elif orientation == gtk.ORIENTATION_HORIZONTAL:
+                       self._isPortrait = False
+               else:
+                       raise NotImplementedError(orientation)
+
+               self._image.queue_draw()
+
+       def set_state(self, stateImage):
+               if stateImage == self._imageName:
+                       return
+               self._imageName = stateImage
+               self._buttonImage = self._store.get_surface_from_store(stateImage)
+
+               self._image.queue_draw()
+
+       def set_context(self, backgroundImage, title, subtitle):
+               self._backgroundImage = self._store.get_surface_from_store(backgroundImage)
+               self._title = title
+               self._subtitle = subtitle
+
+               backWidth = self._backgroundImage.get_width()
+               backHeight = self._backgroundImage.get_height()
+               self._image.set_size_request(backWidth, backHeight)
+
+               self._image.queue_draw()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_expose(self, widget, event):
+               cairoContext = self._image.window.cairo_create()
+               self._draw_presenter(cairoContext)
+
+       def _draw_presenter(self, cairoContext):
+               rect = self._image.get_allocation()
+               self._dims = rect.width, rect.height
+
+               # Blank things
+               cairoContext.rectangle(
+                       0,
+                       0,
+                       rect.width,
+                       rect.height,
+               )
+               cairoContext.set_source_rgb(0, 0, 0)
+               cairoContext.fill()
+
+               # Draw Background
+               if self._backgroundImage is not None:
+                       cairoContext.set_source_surface(
+                               self._backgroundImage,
+                               0,
+                               0,
+                       )
+                       cairoContext.paint()
+
+               pangoContext = self._image.create_pango_context()
+
+               titleLayout = pango.Layout(pangoContext)
+               titleLayout.set_markup("<i>%s</i>" % self._subtitle)
+               textWidth, textHeight = titleLayout.get_pixel_size()
+               subtitleTextX = self._dims[0] / 2 - textWidth / 2
+               subtitleTextY = self._dims[1] - textHeight - self._buttonImage.get_height() + 10
+
+               subtitleLayout = pango.Layout(pangoContext)
+               subtitleLayout.set_markup("<b>%s</b>" % self._title)
+               textWidth, textHeight = subtitleLayout.get_pixel_size()
+               textX = self._dims[0] / 2 - textWidth / 2
+               textY = subtitleTextY - textHeight
+
+               xPadding = min((self._dims[0] - textWidth) / 2 - 5, 5)
+               yPadding = 5
+               startContent = xPadding, textY - yPadding
+               endContent = self._dims[0] - xPadding,  self._dims[1] - yPadding
+
+               # Control background
+               cairoContext.rectangle(
+                       startContent[0],
+                       startContent[1],
+                       endContent[0] - startContent[0],
+                       endContent[1] - startContent[1],
+               )
+               cairoContext.set_source_rgba(0.9, 0.9, 0.9, 0.75)
+               cairoContext.fill()
+
+               # title
+               if self._title or self._subtitle:
+                       cairoContext.move_to(subtitleTextX, subtitleTextY)
+                       cairoContext.set_source_rgb(0, 0, 0)
+                       cairoContext.show_layout(titleLayout)
+
+                       cairoContext.move_to(textX, textY)
+                       cairoContext.set_source_rgb(0, 0, 0)
+                       cairoContext.show_layout(subtitleLayout)
+
+               self._draw_state(cairoContext)
+
+       def _draw_state(self, cairoContext):
+               if self._backgroundImage is None or self._buttonImage is None:
+                       return
+               cairoContext.set_source_surface(
+                       self._buttonImage,
+                       self._dims[0] / 2 - self._buttonImage.get_width() / 2,
+                       self._dims[1] - self._buttonImage.get_height() + 5,
+               )
+               cairoContext.paint()
+
+
+class StreamMiniPresenter(object):
+
+       def __init__(self, store):
+               self._store = store
+
+               self._button = gtk.Image()
+
+       @property
+       def toplevel(self):
+               return self._button
+
+       def set_orientation(self, orientation):
+               pass
+
+       def set_state(self, stateImage):
+               self._store.set_image_from_store(self._button, stateImage)
+
+       def set_context(self, backgroundImage, title, subtitle):
+               pass
+
+
+class NavControl(gobject.GObject, go_utils.AutoSignal):
+
+       __gsignals__ = {
+               'home' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (),
+               ),
+               'jump-to' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_PYOBJECT, ),
+               ),
+       }
+
+       def __init__(self, player, store):
+               gobject.GObject.__init__(self)
+               self._layout = gtk.HBox()
+               go_utils.AutoSignal.__init__(self, self.toplevel)
+
+               self._store = store
+
+               self._controlButton = store.get_image_from_store(store.STORE_LOOKUP["play"])
+
+               self._controlBox = NavigationBox()
+               self._controlBox.toplevel.add(self._controlButton)
+               self.connect_auto(self._controlBox, "action", self._on_nav_action)
+               self.connect_auto(self._controlBox, "navigating", self._on_navigating)
+
+               self._titleButton = gtk.Label()
+
+               self._displayBox = NavigationBox()
+               self._displayBox.toplevel.add(self._titleButton)
+               self.connect_auto(self._displayBox, "action", self._on_nav_action)
+               self.connect_auto(self._displayBox, "navigating", self._on_navigating)
+
+               self._layout.pack_start(self._controlBox.toplevel, False, False)
+               self._layout.pack_start(self._displayBox.toplevel, True, True)
+               self._player = player
+               self.connect_auto(self._player, "state-change", self._on_player_state_change)
+               self.connect_auto(self._player, "title-change", self._on_player_title_change)
+               self._titleButton.set_label(self._player.title)
+
+       def refresh(self):
+               self._titleButton.set_label(self._player.title)
+               self._set_context(self._player.state)
+
+       def _set_context(self, state):
+               if state == self._player.STATE_PLAY:
+                       stateImage = self._store.STORE_LOOKUP["pause"]
+                       self._store.set_image_from_store(self._controlButton, stateImage)
+                       self.toplevel.show()
+               elif state == self._player.STATE_PAUSE:
+                       stateImage = self._store.STORE_LOOKUP["play"]
+                       self._store.set_image_from_store(self._controlButton, stateImage)
+                       self.toplevel.show()
+               elif state == self._player.STATE_STOP:
+                       self._titleButton.set_label("")
+                       self.toplevel.hide()
+               else:
+                       _moduleLogger.info("Unhandled player state %s" % state)
+                       stateImage = self._store.STORE_LOOKUP["pause"]
+                       self._store.set_image_from_store(self._controlButton, stateImage)
+
+       @property
+       def toplevel(self):
+               return self._layout
+
+       def set_orientation(self, orientation):
+               pass
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_state_change(self, player, newState):
+               if self._controlBox.is_active() or self._displayBox.is_active():
+                       return
+
+               self._set_context(newState)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_title_change(self, player, node):
+               _moduleLogger.info("Title change: %s" % self._player.title)
+               self._titleButton.set_label(self._player.title)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_navigating(self, widget, navState):
+               if navState == "down":
+                       imageName = "home"
+               elif navState == "clicking":
+                       if widget is self._controlBox:
+                               if self._player.state == self._player.STATE_PLAY:
+                                       imageName = "pause_pressed"
+                               else:
+                                       imageName = "play_pressed"
+                       else:
+                               if self._player.state == self._player.STATE_PLAY:
+                                       imageName = "pause"
+                               else:
+                                       imageName = "play"
+               elif self._player.can_navigate:
+                       if navState == "up":
+                               imageName = "play"
+                       elif navState == "left":
+                               imageName = "next"
+                       elif navState == "right":
+                               imageName = "prev"
+               else:
+                       if self._player.state == self._player.STATE_PLAY:
+                               imageName = "pause"
+                       else:
+                               imageName = "play"
+
+               imagePath = self._store.STORE_LOOKUP[imageName]
+               self._store.set_image_from_store(self._controlButton, imagePath)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_nav_action(self, widget, navState):
+               self._set_context(self._player.state)
+
+               if navState == "clicking":
+                       if widget is self._controlBox:
+                               if self._player.state == self._player.STATE_PLAY:
+                                       self._player.pause()
+                               else:
+                                       self._player.play()
+                       elif widget is self._displayBox:
+                               self.emit("jump-to", self._player.node)
+                       else:
+                               raise NotImplementedError()
+               elif navState == "down":
+                       self.emit("home")
+               elif navState == "up":
+                       pass
+               elif navState == "left":
+                       self._player.next()
+               elif navState == "right":
+                       self._player.back()
+
+
+gobject.type_register(NavControl)
diff --git a/src/stream.py b/src/stream.py
new file mode 100644 (file)
index 0000000..d584b65
--- /dev/null
@@ -0,0 +1,145 @@
+import logging
+
+import gobject
+import gst
+
+import util.misc as misc_utils
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class GSTStream(gobject.GObject):
+
+       STATE_PLAY = "play"
+       STATE_PAUSE = "pause"
+       STATE_STOP = "stop"
+
+       __gsignals__ = {
+               'state-change' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_STRING, ),
+               ),
+               'eof' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_STRING, ),
+               ),
+               'error' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_PYOBJECT, gobject.TYPE_PYOBJECT),
+               ),
+       }
+
+
+       def __init__(self):
+               gobject.GObject.__init__(self)
+               #Fields
+               self._state = self.STATE_STOP
+               self._uri = ""
+               self._elapsed = 0
+               self._duration = 0
+
+               #Set up GStreamer
+               self._player = gst.element_factory_make("playbin2", "player")
+               bus = self._player.get_bus()
+               bus.add_signal_watch()
+               bus.connect("message", self._on_message)
+
+               #Constants
+               self._timeFormat = gst.Format(gst.FORMAT_TIME)
+               self._seekFlag = gst.SEEK_FLAG_FLUSH
+
+       @property
+       def playing(self):
+               return self.state == self.STATE_PLAY
+
+       @property
+       def has_file(self):
+               return 0 < len(self._uri)
+
+       @property
+       def state(self):
+               state = self._player.get_state()[1]
+               return self._translate_state(state)
+
+       def set_file(self, uri):
+               if self._uri != file:
+                       self._invalidate_cache()
+               if self.state != self.STATE_STOP:
+                       self.stop()
+
+               self._uri = uri
+               self._player.set_property("uri", uri)
+
+       def play(self):
+               if self.state == self.STATE_PLAY:
+                       _moduleLogger.info("Already play")
+                       return
+               _moduleLogger.info("Play")
+               self._player.set_state(gst.STATE_PLAYING)
+               self.emit("state-change", self.STATE_PLAY)
+
+       def pause(self):
+               if self.state == self.STATE_PAUSE:
+                       _moduleLogger.info("Already pause")
+                       return
+               _moduleLogger.info("Pause")
+               self._player.set_state(gst.STATE_PAUSED)
+               self.emit("state-change", self.STATE_PAUSE)
+
+       def stop(self):
+               if self.state == self.STATE_STOP:
+                       _moduleLogger.info("Already stop")
+                       return
+               self._player.set_state(gst.STATE_NULL)
+               _moduleLogger.info("Stopped")
+               self.emit("state-change", self.STATE_STOP)
+
+       @property
+       def elapsed(self):
+               try:
+                       self._elapsed = self._player.query_position(self._timeFormat, None)[0]
+               except:
+                       pass
+               return self._elapsed
+
+       @property
+       def duration(self):
+               try:
+                       self._duration = self._player.query_duration(self._timeFormat, None)[0]
+               except:
+                       _moduleLogger.exception("Query failed")
+               return self._duration
+
+       def seek_time(self, ns):
+               self._elapsed = ns
+               self._player.seek_simple(self._timeFormat, self._seekFlag, ns)
+
+       def _invalidate_cache(self):
+               self._elapsed = 0
+               self._duration = 0
+
+       def _translate_state(self, gstState):
+               return {
+                       gst.STATE_NULL: self.STATE_STOP,
+                       gst.STATE_PAUSED: self.STATE_PAUSE,
+                       gst.STATE_PLAYING: self.STATE_PLAY,
+               }.get(gstState, self.STATE_STOP)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_message(self, bus, message):
+               t = message.type
+               if t == gst.MESSAGE_EOS:
+                       self._player.set_state(gst.STATE_NULL)
+                       self.emit("eof", self._uri)
+               elif t == gst.MESSAGE_ERROR:
+                       self._player.set_state(gst.STATE_NULL)
+                       err, debug = message.parse_error()
+                       _moduleLogger.error("Error: %s, (%s)" % (err, debug))
+                       self.emit("error", err, debug)
+
+
+gobject.type_register(GSTStream)
diff --git a/src/stream_index.py b/src/stream_index.py
new file mode 100644 (file)
index 0000000..dc4d654
--- /dev/null
@@ -0,0 +1,649 @@
+import weakref
+import logging
+
+import util.misc as misc_utils
+from util import go_utils
+import backend
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+SOURCE_RADIO = "radio"
+SOURCE_CONFERENCES = "conferences"
+SOURCE_MAGAZINES = "magazines"
+SOURCE_SCRIPTURES = "scriptures"
+
+
+class Connection(object):
+
+       def __init__(self):
+               self._backend = backend.Backend()
+               self._indexing = go_utils.AsyncPool()
+
+       def start(self):
+               self._indexing.start()
+
+       def stop(self):
+               self._indexing.stop()
+
+       def download(self, func, on_success, on_error, args = None, kwds = None):
+               if args is None:
+                       args = ()
+               if kwds is None:
+                       kwds = {}
+
+               self._indexing.add_task(
+                       getattr(self._backend, func),
+                       args,
+                       kwds,
+                       on_success,
+                       on_error,
+               )
+
+
+class AudioIndex(object):
+
+       def __init__(self):
+               self._connection = Connection()
+               self._languages = None
+               self._languagesRequest = None
+               self._sources = {}
+
+       def start(self):
+               self._connection.start()
+
+       def stop(self):
+               self._connection.stop()
+
+       def get_languages(self, on_success, on_error):
+               if self._languages is None:
+                       assert self._languagesRequest is None
+                       self._languagesRequest = on_success, on_error
+                       self._connection.download(
+                               "get_languages",
+                               self._on_get_languages,
+                               self._on_languages_error
+                       )
+               else:
+                       on_success(self._languages)
+
+       def get_source(self, source, langId = None):
+               key = (source, langId)
+               if key in self._sources:
+                       node = self._sources[key]
+               else:
+                       if source == SOURCE_RADIO:
+                               node = RadioNode(self._connection)
+                       elif source == SOURCE_CONFERENCES:
+                               assert langId is not None
+                               node = ConferencesNode(self._connection, langId)
+                       elif source == SOURCE_MAGAZINES:
+                               assert langId is not None
+                               node = MagazinesNode(self._connection, langId)
+                       elif source == SOURCE_SCRIPTURES:
+                               assert langId is not None
+                               node = ScripturesNode(self._connection, langId)
+                       else:
+                               raise NotImplementedError(source)
+                       self._sources[key] = node
+
+               return node
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_get_languages(self, languages):
+               assert self._languages is None
+               assert self._languagesRequest is not None
+               r = self._languagesRequest
+               self._languagesRequest = None
+               self._languages = languages
+               r[0](self._languages)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_languages_error(self, e):
+               assert self._languages is None
+               assert self._languagesRequest is not None
+               r = self._languagesRequest
+               self._languagesRequest = None
+               r[1](self._languages)
+
+
+class Node(object):
+
+       def __init__(self, connection, parent, data, id):
+               self._connection = connection
+               self._parent = weakref.ref(parent) if parent is not None else None
+               self._data = data
+               self._children = None
+               self._id = id
+
+       def get_children(self, on_success, on_error):
+               if self._children is None:
+                       self._get_children(on_success, on_error)
+               else:
+                       on_success(self._children)
+
+       def get_parent(self):
+               if self._parent is None:
+                       raise RuntimeError("")
+               parent = self._parent()
+               return parent
+
+       def get_properties(self):
+               return self._data
+
+       @property
+       def title(self):
+               raise NotImplementedError("On %s" % type(self))
+
+       @property
+       def id(self):
+               return self._id
+
+       def is_leaf(self):
+               raise NotImplementedError("")
+
+       def _get_children(self, on_success, on_error):
+               raise NotImplementedError("")
+
+
+class ParentNode(Node):
+
+       def __init__(self, connection, parent, data, id):
+               Node.__init__(self, connection, parent, data, id)
+
+       def is_leaf(self):
+               return False
+
+       def _get_children(self, on_success, on_error):
+               assert self._children is None
+
+               func, args, kwds = self._get_func()
+
+               self._connection.download(
+                       func,
+                       lambda data: self._on_success(data, on_success, on_error),
+                       on_error,
+                       args,
+                       kwds,
+               )
+
+       def _get_func(self):
+               raise NotImplementedError()
+
+       def _create_child(self, data, id):
+               raise NotImplementedError()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_success(self, data, on_success, on_error):
+               try:
+                       self._children = [
+                               self._create_child(child, i)
+                               for i, child in enumerate(data)
+                       ]
+               except Exception, e:
+                       _moduleLogger.exception("Translating error")
+                       self._children = None
+                       on_error(e)
+               else:
+                       on_success(self._children)
+
+
+class LeafNode(Node):
+
+       def __init__(self, connection, parent, data, id):
+               Node.__init__(self, connection, parent, data, id)
+
+       def is_leaf(self):
+               return True
+
+       @property
+       def can_navigate(self):
+               raise NotImplementedError("On %s" % type(self))
+
+       @property
+       def subtitle(self):
+               raise NotImplementedError("On %s" % type(self))
+
+       @property
+       def uri(self):
+               raise NotImplementedError("On %s" % type(self))
+
+       def _get_children(self, on_success, on_error):
+               raise RuntimeError("Not is a leaf")
+
+
+class RadioNode(ParentNode):
+
+       def __init__(self, connection):
+               ParentNode.__init__(self, connection, None, {}, SOURCE_RADIO)
+
+       @property
+       def title(self):
+               return "Radio"
+
+       def _get_func(self):
+               return "get_radio_channels", (), {}
+
+       def _create_child(self, data, id):
+               return RadioChannelNode(self._connection, self, data, id)
+
+
+class RadioChannelNode(LeafNode):
+
+       def __init__(self, connection, parent, data, id):
+               LeafNode.__init__(self, connection, parent, data, id)
+               self._extendedData = {}
+               self._request = None
+
+       @property
+       def can_navigate(self):
+               return False
+
+       @property
+       def title(self):
+               return "Radio"
+
+       @property
+       def subtitle(self):
+               return ""
+
+       @property
+       def uri(self):
+               return self._data["url"]
+
+       def get_programming(self, date, on_success, on_error):
+               date = date.strftime("%Y-%m-%d")
+               try:
+                       programming = self._extendedData[date]
+               except KeyError:
+                       self._get_programming(date, on_success, on_error)
+               else:
+                       on_success(programming)
+
+       def _get_programming(self, date, on_success, on_error):
+               assert self._request is None
+               assert date not in self._extendedData
+               self._request = on_success, on_error, date
+
+               self._connection.download(
+                       "get_radio_channel_programming",
+                       self._on_success,
+                       self._on_error,
+                       (self._data["id"], date),
+                       {},
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_success(self, data):
+               r = self._request
+               date = r[2]
+               self._request = None
+               try:
+                       self._extendedData[date] = [
+                               child
+                               for child in data
+                       ]
+               except Exception, e:
+                       _moduleLogger.exception("Translating error")
+                       del self._extendedData[date]
+                       r[1](e)
+               else:
+                       r[0](self._extendedData[date])
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, error):
+               r = self._request
+               self._request = None
+               r[1](error)
+
+
+class ConferencesNode(ParentNode):
+
+       def __init__(self, connection, langId):
+               ParentNode.__init__(self, connection, None, {}, SOURCE_CONFERENCES)
+               self._langId = langId
+
+       @property
+       def title(self):
+               return "Conferences"
+
+       def _get_func(self):
+               return "get_conferences", (self._langId, ), {}
+
+       def _create_child(self, data, id):
+               return ConferenceNode(self._connection, self, data, id)
+
+
+class ConferenceNode(ParentNode):
+
+       def __init__(self, connection, parent, data, id):
+               ParentNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       def _get_func(self):
+               return "get_conference_sessions", (self._data["id"], ), {}
+
+       def _create_child(self, data, id):
+               return SessionNode(self._connection, self, data, id)
+
+
+class SessionNode(ParentNode):
+
+       def __init__(self, connection, parent, data, id):
+               ParentNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       def _get_func(self):
+               return "get_conference_talks", (self._data["id"], ), {}
+
+       def _create_child(self, data, id):
+               return TalkNode(self._connection, self, data, id)
+
+
+class TalkNode(LeafNode):
+
+       def __init__(self, connection, parent, data, id):
+               LeafNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def can_navigate(self):
+               return True
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       @property
+       def subtitle(self):
+               speaker = self._data["speaker"]
+               if speaker is not None:
+                       return speaker
+               else:
+                       return ""
+
+       @property
+       def uri(self):
+               return self._data["url"]
+
+
+class MagazinesNode(ParentNode):
+
+       def __init__(self, connection, langId):
+               ParentNode.__init__(self, connection, None, {}, SOURCE_MAGAZINES)
+               self._langId = langId
+
+       @property
+       def title(self):
+               return "Magazines"
+
+       def _get_func(self):
+               return "get_magazines", (self._langId, ), {}
+
+       def _create_child(self, data, id):
+               return MagazineNode(self._connection, self, data, id)
+
+
+class MagazineNode(ParentNode):
+
+       def __init__(self, connection, parent, data, id):
+               ParentNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       def _get_func(self):
+               return "get_magazine_issues", (self._data["id"], ), {}
+
+       def _create_child(self, data, id):
+               return IssueNode(self._connection, self, data, id)
+
+
+class IssueNode(ParentNode):
+
+       def __init__(self, connection, parent, data, id):
+               ParentNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       def _get_func(self):
+               return "get_magazine_articles", (self._data["id"], ), {}
+
+       def _create_child(self, data, id):
+               return ArticleNode(self._connection, self, data, id)
+
+
+class ArticleNode(LeafNode):
+
+       def __init__(self, connection, parent, data, id):
+               LeafNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def can_navigate(self):
+               return True
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       @property
+       def subtitle(self):
+               speaker = self._data["author"]
+               if speaker is not None:
+                       return speaker
+               else:
+                       return ""
+
+       @property
+       def uri(self):
+               return self._data["url"]
+
+
+class ScripturesNode(ParentNode):
+
+       def __init__(self, connection, langId):
+               ParentNode.__init__(self, connection, None, {}, SOURCE_SCRIPTURES)
+               self._langId = langId
+
+       @property
+       def title(self):
+               return "Scriptures"
+
+       def _get_func(self):
+               return "get_scriptures", (self._langId, ), {}
+
+       def _create_child(self, data, id):
+               return ScriptureNode(self._connection, self, data, id)
+
+
+class ScriptureNode(ParentNode):
+
+       def __init__(self, connection, parent, data, id):
+               ParentNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       def _get_func(self):
+               return "get_scripture_books", (self._data["id"], ), {}
+
+       def _create_child(self, data, id):
+               return BookNode(self._connection, self, data, id)
+
+
+class BookNode(ParentNode):
+
+       def __init__(self, connection, parent, data, id):
+               ParentNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       def _get_func(self):
+               return "get_scripture_chapters", (self._data["id"], ), {}
+
+       def _create_child(self, data, id):
+               return ChapterNode(self._connection, self, data, id)
+
+
+class ChapterNode(LeafNode):
+
+       def __init__(self, connection, parent, data, id):
+               LeafNode.__init__(self, connection, parent, data, id)
+
+       @property
+       def can_navigate(self):
+               return True
+
+       @property
+       def title(self):
+               return self._data["title"]
+
+       @property
+       def subtitle(self):
+               return ""
+
+       @property
+       def uri(self):
+               return self._data["url"]
+
+
+def walk_ancestors(node):
+       while True:
+               yield node
+               try:
+                       node = node.get_parent()
+               except RuntimeError:
+                       return
+
+
+def common_paths(targetNode, currentNode):
+       targetNodePath = list(walk_ancestors(targetNode))
+       targetNodePath.reverse()
+       currentNodePath = list(walk_ancestors(currentNode))
+       currentNodePath.reverse()
+
+       ancestors = []
+       descendants = []
+
+       for i, (t, c) in enumerate(zip(targetNodePath, currentNodePath)):
+               if t is not c:
+                       return ancestors, None, descendants
+               ancestors.append(t)
+
+       descendants.extend(
+               child
+               for child in targetNodePath[i+1:]
+       )
+
+       return ancestors, currentNode, descendants
+
+
+class AsyncWalker(object):
+
+       def __init__(self, func):
+               self._func = func
+               self._run = None
+
+       def start(self, *args, **kwds):
+               assert self._run is None
+               self._run = self._func(*args, **kwds)
+               node = self._run.send(None) # priming the function
+               node.get_children(self.on_success, self.on_error)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def on_success(self, children):
+               _moduleLogger.debug("Processing success for: %r", self._func)
+               try:
+                       node = self._run.send(children)
+               except StopIteration, e:
+                       pass
+               else:
+                       node.get_children(self.on_success, self.on_error)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def on_error(self, error):
+               _moduleLogger.debug("Processing error for: %r", self._func)
+               try:
+                       node = self._run.throw(error)
+               except StopIteration, e:
+                       pass
+               else:
+                       node.get_children(self.on_success, self.on_error)
+
+
+def get_next(node, on_success, on_error):
+       try:
+               assert node.is_leaf(), node
+
+               # Find next branch
+               childNode = node
+               while True:
+                       parent = childNode.get_parent()
+                       siblings = yield parent
+                       for i, sibling in enumerate(siblings):
+                               if sibling is childNode:
+                                       break
+                       i += 1
+                       if i < len(siblings):
+                               sibling = siblings[i]
+                               break
+                       else:
+                               childNode = parent
+
+               # dig into that branch to find the first leaf
+               nodes = [sibling]
+               while nodes:
+                       child = nodes.pop(0)
+                       if child.is_leaf():
+                               on_success(child)
+                               return
+                       children = yield child
+                       nodes[0:0] = children
+               raise RuntimeError("Ran out of nodes when hunting for first leaf of %s" % node)
+       except Exception, e:
+               on_error(e)
+
+
+def get_previous(node, on_success, on_error):
+       try:
+               assert node.is_leaf(), node
+
+               # Find next branch
+               childNode = node
+               while True:
+                       parent = childNode.get_parent()
+                       siblings = yield parent
+                       for i, sibling in enumerate(siblings):
+                               if sibling is childNode:
+                                       break
+                       i -= 1
+                       if 0 <= i:
+                               sibling = siblings[i]
+                               break
+                       else:
+                               childNode = parent
+
+               # dig into that branch to find the first leaf
+               nodes = [sibling]
+               while nodes:
+                       child = nodes.pop(-1)
+                       if child.is_leaf():
+                               on_success(child)
+                               return
+                       children = yield child
+                       nodes[0:0] = children
+               raise RuntimeError("Ran out of nodes when hunting for first leaf of %s" % node)
+       except Exception, e:
+               on_error(e)
diff --git a/src/util/__init__.py b/src/util/__init__.py
new file mode 100644 (file)
index 0000000..4265cc3
--- /dev/null
@@ -0,0 +1 @@
+#!/usr/bin/env python
diff --git a/src/util/algorithms.py b/src/util/algorithms.py
new file mode 100644 (file)
index 0000000..7052b98
--- /dev/null
@@ -0,0 +1,584 @@
+#!/usr/bin/env python
+
+"""
+@note Source http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66448
+"""
+
+import itertools
+import functools
+import datetime
+import types
+
+
+def ordered_itr(collection):
+       """
+       >>> [v for v in ordered_itr({"a": 1, "b": 2})]
+       [('a', 1), ('b', 2)]
+       >>> [v for v in ordered_itr([3, 1, 10, -20])]
+       [-20, 1, 3, 10]
+       """
+       if isinstance(collection, types.DictType):
+               keys = list(collection.iterkeys())
+               keys.sort()
+               for key in keys:
+                       yield key, collection[key]
+       else:
+               values = list(collection)
+               values.sort()
+               for value in values:
+                       yield value
+
+
+def itercat(*iterators):
+       """
+       Concatenate several iterators into one.
+
+       >>> [v for v in itercat([1, 2, 3], [4, 1, 3])]
+       [1, 2, 3, 4, 1, 3]
+       """
+       for i in iterators:
+               for x in i:
+                       yield x
+
+
+def iterwhile(func, iterator):
+       """
+       Iterate for as long as func(value) returns true.
+       >>> through = lambda b: b
+       >>> [v for v in iterwhile(through, [True, True, False])]
+       [True, True]
+       """
+       iterator = iter(iterator)
+       while 1:
+               next = iterator.next()
+               if not func(next):
+                       raise StopIteration
+               yield next
+
+
+def iterfirst(iterator, count=1):
+       """
+       Iterate through 'count' first values.
+
+       >>> [v for v in iterfirst([1, 2, 3, 4, 5], 3)]
+       [1, 2, 3]
+       """
+       iterator = iter(iterator)
+       for i in xrange(count):
+               yield iterator.next()
+
+
+def iterstep(iterator, n):
+       """
+       Iterate every nth value.
+
+       >>> [v for v in iterstep([1, 2, 3, 4, 5], 1)]
+       [1, 2, 3, 4, 5]
+       >>> [v for v in iterstep([1, 2, 3, 4, 5], 2)]
+       [1, 3, 5]
+       >>> [v for v in iterstep([1, 2, 3, 4, 5], 3)]
+       [1, 4]
+       """
+       iterator = iter(iterator)
+       while True:
+               yield iterator.next()
+               # skip n-1 values
+               for dummy in xrange(n-1):
+                       iterator.next()
+
+
+def itergroup(iterator, count, padValue = None):
+       """
+       Iterate in groups of 'count' values. If there
+       aren't enough values, the last result is padded with
+       None.
+
+       >>> for val in itergroup([1, 2, 3, 4, 5, 6], 3):
+       ...     print tuple(val)
+       (1, 2, 3)
+       (4, 5, 6)
+       >>> for val in itergroup([1, 2, 3, 4, 5, 6], 3):
+       ...     print list(val)
+       [1, 2, 3]
+       [4, 5, 6]
+       >>> for val in itergroup([1, 2, 3, 4, 5, 6, 7], 3):
+       ...     print tuple(val)
+       (1, 2, 3)
+       (4, 5, 6)
+       (7, None, None)
+       >>> for val in itergroup("123456", 3):
+       ...     print tuple(val)
+       ('1', '2', '3')
+       ('4', '5', '6')
+       >>> for val in itergroup("123456", 3):
+       ...     print repr("".join(val))
+       '123'
+       '456'
+       """
+       paddedIterator = itertools.chain(iterator, itertools.repeat(padValue, count-1))
+       nIterators = (paddedIterator, ) * count
+       return itertools.izip(*nIterators)
+
+
+def xzip(*iterators):
+       """Iterative version of builtin 'zip'."""
+       iterators = itertools.imap(iter, iterators)
+       while 1:
+               yield tuple([x.next() for x in iterators])
+
+
+def xmap(func, *iterators):
+       """Iterative version of builtin 'map'."""
+       iterators = itertools.imap(iter, iterators)
+       values_left = [1]
+
+       def values():
+               # Emulate map behaviour, i.e. shorter
+               # sequences are padded with None when
+               # they run out of values.
+               values_left[0] = 0
+               for i in range(len(iterators)):
+                       iterator = iterators[i]
+                       if iterator is None:
+                               yield None
+                       else:
+                               try:
+                                       yield iterator.next()
+                                       values_left[0] = 1
+                               except StopIteration:
+                                       iterators[i] = None
+                                       yield None
+       while 1:
+               args = tuple(values())
+               if not values_left[0]:
+                       raise StopIteration
+               yield func(*args)
+
+
+def xfilter(func, iterator):
+       """Iterative version of builtin 'filter'."""
+       iterator = iter(iterator)
+       while 1:
+               next = iterator.next()
+               if func(next):
+                       yield next
+
+
+def xreduce(func, iterator, default=None):
+       """Iterative version of builtin 'reduce'."""
+       iterator = iter(iterator)
+       try:
+               prev = iterator.next()
+       except StopIteration:
+               return default
+       single = 1
+       for next in iterator:
+               single = 0
+               prev = func(prev, next)
+       if single:
+               return func(prev, default)
+       return prev
+
+
+def daterange(begin, end, delta = datetime.timedelta(1)):
+       """
+       Form a range of dates and iterate over them.
+
+       Arguments:
+       begin -- a date (or datetime) object; the beginning of the range.
+       end   -- a date (or datetime) object; the end of the range.
+       delta -- (optional) a datetime.timedelta object; how much to step each iteration.
+                       Default step is 1 day.
+
+       Usage:
+       """
+       if not isinstance(delta, datetime.timedelta):
+               delta = datetime.timedelta(delta)
+
+       ZERO = datetime.timedelta(0)
+
+       if begin < end:
+               if delta <= ZERO:
+                       raise StopIteration
+               test = end.__gt__
+       else:
+               if delta >= ZERO:
+                       raise StopIteration
+               test = end.__lt__
+
+       while test(begin):
+               yield begin
+               begin += delta
+
+
+class LazyList(object):
+       """
+       A Sequence whose values are computed lazily by an iterator.
+
+       Module for the creation and use of iterator-based lazy lists.
+       this module defines a class LazyList which can be used to represent sequences
+       of values generated lazily. One can also create recursively defined lazy lists
+       that generate their values based on ones previously generated.
+
+       Backport to python 2.5 by Michael Pust
+       """
+
+       __author__ = 'Dan Spitz'
+
+       def __init__(self, iterable):
+               self._exhausted = False
+               self._iterator = iter(iterable)
+               self._data = []
+
+       def __len__(self):
+               """Get the length of a LazyList's computed data."""
+               return len(self._data)
+
+       def __getitem__(self, i):
+               """Get an item from a LazyList.
+               i should be a positive integer or a slice object."""
+               if isinstance(i, int):
+                       #index has not yet been yielded by iterator (or iterator exhausted
+                       #before reaching that index)
+                       if i >= len(self):
+                               self.exhaust(i)
+                       elif i < 0:
+                               raise ValueError('cannot index LazyList with negative number')
+                       return self._data[i]
+
+               #LazyList slices are iterators over a portion of the list.
+               elif isinstance(i, slice):
+                       start, stop, step = i.start, i.stop, i.step
+                       if any(x is not None and x < 0 for x in (start, stop, step)):
+                               raise ValueError('cannot index or step through a LazyList with'
+                                                               'a negative number')
+                       #set start and step to their integer defaults if they are None.
+                       if start is None:
+                               start = 0
+                       if step is None:
+                               step = 1
+
+                       def LazyListIterator():
+                               count = start
+                               predicate = (
+                                       (lambda: True)
+                                       if stop is None
+                                       else (lambda: count < stop)
+                               )
+                               while predicate():
+                                       try:
+                                               yield self[count]
+                                       #slices can go out of actual index range without raising an
+                                       #error
+                                       except IndexError:
+                                               break
+                                       count += step
+                       return LazyListIterator()
+
+               raise TypeError('i must be an integer or slice')
+
+       def __iter__(self):
+               """return an iterator over each value in the sequence,
+               whether it has been computed yet or not."""
+               return self[:]
+
+       def computed(self):
+               """Return an iterator over the values in a LazyList that have
+               already been computed."""
+               return self[:len(self)]
+
+       def exhaust(self, index = None):
+               """Exhaust the iterator generating this LazyList's values.
+               if index is None, this will exhaust the iterator completely.
+               Otherwise, it will iterate over the iterator until either the list
+               has a value for index or the iterator is exhausted.
+               """
+               if self._exhausted:
+                       return
+               if index is None:
+                       ind_range = itertools.count(len(self))
+               else:
+                       ind_range = range(len(self), index + 1)
+
+               for ind in ind_range:
+                       try:
+                               self._data.append(self._iterator.next())
+                       except StopIteration: #iterator is fully exhausted
+                               self._exhausted = True
+                               break
+
+
+class RecursiveLazyList(LazyList):
+
+       def __init__(self, prod, *args, **kwds):
+               super(RecursiveLazyList, self).__init__(prod(self, *args, **kwds))
+
+
+class RecursiveLazyListFactory:
+
+       def __init__(self, producer):
+               self._gen = producer
+
+       def __call__(self, *a, **kw):
+               return RecursiveLazyList(self._gen, *a, **kw)
+
+
+def lazylist(gen):
+       """
+       Decorator for creating a RecursiveLazyList subclass.
+       This should decorate a generator function taking the LazyList object as its
+       first argument which yields the contents of the list in order.
+
+       >>> #fibonnacci sequence in a lazy list.
+       >>> @lazylist
+       ... def fibgen(lst):
+       ...     yield 0
+       ...     yield 1
+       ...     for a, b in itertools.izip(lst, lst[1:]):
+       ...             yield a + b
+       ...
+       >>> #now fibs can be indexed or iterated over as if it were an infinitely long list containing the fibonnaci sequence
+       >>> fibs = fibgen()
+       >>>
+       >>> #prime numbers in a lazy list.
+       >>> @lazylist
+       ... def primegen(lst):
+       ...     yield 2
+       ...     for candidate in itertools.count(3): #start at next number after 2
+       ...             #if candidate is not divisible by any smaller prime numbers,
+       ...             #it is a prime.
+       ...             if all(candidate % p for p in lst.computed()):
+       ...                     yield candidate
+       ...
+       >>> #same for primes- treat it like an infinitely long list containing all prime numbers.
+       >>> primes = primegen()
+       >>> print fibs[0], fibs[1], fibs[2], primes[0], primes[1], primes[2]
+       0 1 1 2 3 5
+       >>> print list(fibs[:10]), list(primes[:10])
+       [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
+       """
+       return RecursiveLazyListFactory(gen)
+
+
+def map_func(f):
+       """
+       >>> import misc
+       >>> misc.validate_decorator(map_func)
+       """
+
+       @functools.wraps(f)
+       def wrapper(*args):
+               result = itertools.imap(f, args)
+               return result
+       return wrapper
+
+
+def reduce_func(function):
+       """
+       >>> import misc
+       >>> misc.validate_decorator(reduce_func(lambda x: x))
+       """
+
+       def decorator(f):
+
+               @functools.wraps(f)
+               def wrapper(*args):
+                       result = reduce(function, f(args))
+                       return result
+               return wrapper
+       return decorator
+
+
+def any_(iterable):
+       """
+       @note Python Version <2.5
+
+       >>> any_([True, True])
+       True
+       >>> any_([True, False])
+       True
+       >>> any_([False, False])
+       False
+       """
+
+       for element in iterable:
+               if element:
+                       return True
+       return False
+
+
+def all_(iterable):
+       """
+       @note Python Version <2.5
+
+       >>> all_([True, True])
+       True
+       >>> all_([True, False])
+       False
+       >>> all_([False, False])
+       False
+       """
+
+       for element in iterable:
+               if not element:
+                       return False
+       return True
+
+
+def for_every(pred, seq):
+       """
+       for_every takes a one argument predicate function and a sequence.
+       @param pred The predicate function should return true or false.
+       @returns true if every element in seq returns true for predicate, else returns false.
+
+       >>> for_every (lambda c: c > 5,(6,7,8,9))
+       True
+
+       @author Source:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52907
+       """
+
+       for i in seq:
+               if not pred(i):
+                       return False
+       return True
+
+
+def there_exists(pred, seq):
+       """
+       there_exists takes a one argument predicate     function and a sequence.
+       @param pred The predicate function should return true or false.
+       @returns true if any element in seq returns true for predicate, else returns false.
+
+       >>> there_exists (lambda c: c > 5,(6,7,8,9))
+       True
+
+       @author Source:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52907
+       """
+
+       for i in seq:
+               if pred(i):
+                       return True
+       return False
+
+
+def func_repeat(quantity, func, *args, **kwd):
+       """
+       Meant to be in connection with "reduce"
+       """
+       for i in xrange(quantity):
+               yield func(*args, **kwd)
+
+
+def function_map(preds, item):
+       """
+       Meant to be in connection with "reduce"
+       """
+       results = (pred(item) for pred in preds)
+
+       return results
+
+
+def functional_if(combiner, preds, item):
+       """
+       Combines the result of a list of predicates applied to item according to combiner
+
+       @see any, every for example combiners
+       """
+       pass_bool = lambda b: b
+
+       bool_results = function_map(preds, item)
+       return combiner(pass_bool, bool_results)
+
+
+def pushback_itr(itr):
+       """
+       >>> list(pushback_itr(xrange(5)))
+       [0, 1, 2, 3, 4]
+       >>>
+       >>> first = True
+       >>> itr = pushback_itr(xrange(5))
+       >>> for i in itr:
+       ...     print i
+       ...     if first and i == 2:
+       ...             first = False
+       ...             print itr.send(i)
+       0
+       1
+       2
+       None
+       2
+       3
+       4
+       >>>
+       >>> first = True
+       >>> itr = pushback_itr(xrange(5))
+       >>> for i in itr:
+       ...     print i
+       ...     if first and i == 2:
+       ...             first = False
+       ...             print itr.send(i)
+       ...             print itr.send(i)
+       0
+       1
+       2
+       None
+       None
+       2
+       2
+       3
+       4
+       >>>
+       >>> itr = pushback_itr(xrange(5))
+       >>> print itr.next()
+       0
+       >>> print itr.next()
+       1
+       >>> print itr.send(10)
+       None
+       >>> print itr.next()
+       10
+       >>> print itr.next()
+       2
+       >>> print itr.send(20)
+       None
+       >>> print itr.send(30)
+       None
+       >>> print itr.send(40)
+       None
+       >>> print itr.next()
+       40
+       >>> print itr.next()
+       30
+       >>> print itr.send(50)
+       None
+       >>> print itr.next()
+       50
+       >>> print itr.next()
+       20
+       >>> print itr.next()
+       3
+       >>> print itr.next()
+       4
+       """
+       for item in itr:
+               maybePushedBack = yield item
+               queue = []
+               while queue or maybePushedBack is not None:
+                       if maybePushedBack is not None:
+                               queue.append(maybePushedBack)
+                               maybePushedBack = yield None
+                       else:
+                               item = queue.pop()
+                               maybePushedBack = yield item
+
+
+def itr_available(queue, initiallyBlock = False):
+       if initiallyBlock:
+               yield queue.get()
+       while not queue.empty():
+               yield queue.get_nowait()
+
+
+if __name__ == "__main__":
+       import doctest
+       print doctest.testmod()
diff --git a/src/util/concurrent.py b/src/util/concurrent.py
new file mode 100644 (file)
index 0000000..503a1b4
--- /dev/null
@@ -0,0 +1,77 @@
+#!/usr/bin/env python
+
+from __future__ import with_statement
+
+import os
+import errno
+import time
+import functools
+import contextlib
+
+
+def synchronized(lock):
+       """
+       Synchronization decorator.
+
+       >>> import misc
+       >>> misc.validate_decorator(synchronized(object()))
+       """
+
+       def wrap(f):
+
+               @functools.wraps(f)
+               def newFunction(*args, **kw):
+                       lock.acquire()
+                       try:
+                               return f(*args, **kw)
+                       finally:
+                               lock.release()
+               return newFunction
+       return wrap
+
+
+@contextlib.contextmanager
+def qlock(queue, gblock = True, gtimeout = None, pblock = True, ptimeout = None):
+       """
+       Locking with a queue, good for when you want to lock an item passed around
+
+       >>> import Queue
+       >>> item = 5
+       >>> lock = Queue.Queue()
+       >>> lock.put(item)
+       >>> with qlock(lock) as i:
+       ...     print i
+       5
+       """
+       item = queue.get(gblock, gtimeout)
+       try:
+               yield item
+       finally:
+               queue.put(item, pblock, ptimeout)
+
+
+@contextlib.contextmanager
+def flock(path, timeout=-1):
+       WAIT_FOREVER = -1
+       DELAY = 0.1
+       timeSpent = 0
+
+       acquired = False
+
+       while timeSpent <= timeout or timeout == WAIT_FOREVER:
+               try:
+                       fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR)
+                       acquired = True
+                       break
+               except OSError, e:
+                       if e.errno != errno.EEXIST:
+                               raise
+               time.sleep(DELAY)
+               timeSpent += DELAY
+
+       assert acquired, "Failed to grab file-lock %s within timeout %d" % (path, timeout)
+
+       try:
+               yield fd
+       finally:
+               os.unlink(path)
diff --git a/src/util/coroutines.py b/src/util/coroutines.py
new file mode 100755 (executable)
index 0000000..b1e539e
--- /dev/null
@@ -0,0 +1,623 @@
+#!/usr/bin/env python\r
+\r
+"""\r
+Uses for generators\r
+* Pull pipelining (iterators)\r
+* Push pipelining (coroutines)\r
+* State machines (coroutines)\r
+* "Cooperative multitasking" (coroutines)\r
+* Algorithm -> Object transform for cohesiveness (for example context managers) (coroutines)\r
+\r
+Design considerations\r
+* When should a stage pass on exceptions or have it thrown within it?\r
+* When should a stage pass on GeneratorExits?\r
+* Is there a way to either turn a push generator into a iterator or to use\r
+       comprehensions syntax for push generators (I doubt it)\r
+* When should the stage try and send data in both directions\r
+* Since pull generators (generators), push generators (coroutines), subroutines, and coroutines are all coroutines, maybe we should rename the push generators to not confuse them, like signals/slots? and then refer to two-way generators as coroutines\r
+** If so, make s* and co* implementation of functions\r
+"""\r
+\r
+import threading\r
+import Queue\r
+import pickle\r
+import functools\r
+import itertools\r
+import xml.sax\r
+import xml.parsers.expat\r
+\r
+\r
+def autostart(func):\r
+       """\r
+       >>> @autostart\r
+       ... def grep_sink(pattern):\r
+       ...     print "Looking for %s" % pattern\r
+       ...     while True:\r
+       ...             line = yield\r
+       ...             if pattern in line:\r
+       ...                     print line,\r
+       >>> g = grep_sink("python")\r
+       Looking for python\r
+       >>> g.send("Yeah but no but yeah but no")\r
+       >>> g.send("A series of tubes")\r
+       >>> g.send("python generators rock!")\r
+       python generators rock!\r
+       >>> g.close()\r
+       """\r
+\r
+       @functools.wraps(func)\r
+       def start(*args, **kwargs):\r
+               cr = func(*args, **kwargs)\r
+               cr.next()\r
+               return cr\r
+\r
+       return start\r
+\r
+\r
+@autostart\r
+def printer_sink(format = "%s"):\r
+       """\r
+       >>> pr = printer_sink("%r")\r
+       >>> pr.send("Hello")\r
+       'Hello'\r
+       >>> pr.send("5")\r
+       '5'\r
+       >>> pr.send(5)\r
+       5\r
+       >>> p = printer_sink()\r
+       >>> p.send("Hello")\r
+       Hello\r
+       >>> p.send("World")\r
+       World\r
+       >>> # p.throw(RuntimeError, "Goodbye")\r
+       >>> # p.send("Meh")\r
+       >>> # p.close()\r
+       """\r
+       while True:\r
+               item = yield\r
+               print format % (item, )\r
+\r
+\r
+@autostart\r
+def null_sink():\r
+       """\r
+       Good for uses like with cochain to pick up any slack\r
+       """\r
+       while True:\r
+               item = yield\r
+\r
+\r
+def itr_source(itr, target):\r
+       """\r
+       >>> itr_source(xrange(2), printer_sink())\r
+       0\r
+       1\r
+       """\r
+       for item in itr:\r
+               target.send(item)\r
+\r
+\r
+@autostart\r
+def cofilter(predicate, target):\r
+       """\r
+       >>> p = printer_sink()\r
+       >>> cf = cofilter(None, p)\r
+       >>> cf.send("")\r
+       >>> cf.send("Hello")\r
+       Hello\r
+       >>> cf.send([])\r
+       >>> cf.send([1, 2])\r
+       [1, 2]\r
+       >>> cf.send(False)\r
+       >>> cf.send(True)\r
+       True\r
+       >>> cf.send(0)\r
+       >>> cf.send(1)\r
+       1\r
+       >>> # cf.throw(RuntimeError, "Goodbye")\r
+       >>> # cf.send(False)\r
+       >>> # cf.send(True)\r
+       >>> # cf.close()\r
+       """\r
+       if predicate is None:\r
+               predicate = bool\r
+\r
+       while True:\r
+               try:\r
+                       item = yield\r
+                       if predicate(item):\r
+                               target.send(item)\r
+               except StandardError, e:\r
+                       target.throw(e.__class__, e.message)\r
+\r
+\r
+@autostart\r
+def comap(function, target):\r
+       """\r
+       >>> p = printer_sink()\r
+       >>> cm = comap(lambda x: x+1, p)\r
+       >>> cm.send(0)\r
+       1\r
+       >>> cm.send(1.0)\r
+       2.0\r
+       >>> cm.send(-2)\r
+       -1\r
+       >>> # cm.throw(RuntimeError, "Goodbye")\r
+       >>> # cm.send(0)\r
+       >>> # cm.send(1.0)\r
+       >>> # cm.close()\r
+       """\r
+       while True:\r
+               try:\r
+                       item = yield\r
+                       mappedItem = function(item)\r
+                       target.send(mappedItem)\r
+               except StandardError, e:\r
+                       target.throw(e.__class__, e.message)\r
+\r
+\r
+def func_sink(function):\r
+       return comap(function, null_sink())\r
+\r
+\r
+def expand_positional(function):\r
+\r
+       @functools.wraps(function)\r
+       def expander(item):\r
+               return function(*item)\r
+\r
+       return expander\r
+\r
+\r
+@autostart\r
+def append_sink(l):\r
+       """\r
+       >>> l = []\r
+       >>> apps = append_sink(l)\r
+       >>> apps.send(1)\r
+       >>> apps.send(2)\r
+       >>> apps.send(3)\r
+       >>> print l\r
+       [1, 2, 3]\r
+       """\r
+       while True:\r
+               item = yield\r
+               l.append(item)\r
+\r
+\r
+@autostart\r
+def last_n_sink(l, n = 1):\r
+       """\r
+       >>> l = []\r
+       >>> lns = last_n_sink(l)\r
+       >>> lns.send(1)\r
+       >>> lns.send(2)\r
+       >>> lns.send(3)\r
+       >>> print l\r
+       [3]\r
+       """\r
+       del l[:]\r
+       while True:\r
+               item = yield\r
+               extraCount = len(l) - n + 1\r
+               if 0 < extraCount:\r
+                       del l[0:extraCount]\r
+               l.append(item)\r
+\r
+\r
+@autostart\r
+def coreduce(target, function, initializer = None):\r
+       """\r
+       >>> reduceResult = []\r
+       >>> lns = last_n_sink(reduceResult)\r
+       >>> cr = coreduce(lns, lambda x, y: x + y, 0)\r
+       >>> cr.send(1)\r
+       >>> cr.send(2)\r
+       >>> cr.send(3)\r
+       >>> print reduceResult\r
+       [6]\r
+       >>> cr = coreduce(lns, lambda x, y: x + y)\r
+       >>> cr.send(1)\r
+       >>> cr.send(2)\r
+       >>> cr.send(3)\r
+       >>> print reduceResult\r
+       [6]\r
+       """\r
+       isFirst = True\r
+       cumulativeRef = initializer\r
+       while True:\r
+               item = yield\r
+               if isFirst and initializer is None:\r
+                       cumulativeRef = item\r
+               else:\r
+                       cumulativeRef = function(cumulativeRef, item)\r
+               target.send(cumulativeRef)\r
+               isFirst = False\r
+\r
+\r
+@autostart\r
+def cotee(targets):\r
+       """\r
+       Takes a sequence of coroutines and sends the received items to all of them\r
+\r
+       >>> ct = cotee((printer_sink("1 %s"), printer_sink("2 %s")))\r
+       >>> ct.send("Hello")\r
+       1 Hello\r
+       2 Hello\r
+       >>> ct.send("World")\r
+       1 World\r
+       2 World\r
+       >>> # ct.throw(RuntimeError, "Goodbye")\r
+       >>> # ct.send("Meh")\r
+       >>> # ct.close()\r
+       """\r
+       while True:\r
+               try:\r
+                       item = yield\r
+                       for target in targets:\r
+                               target.send(item)\r
+               except StandardError, e:\r
+                       for target in targets:\r
+                               target.throw(e.__class__, e.message)\r
+\r
+\r
+class CoTee(object):\r
+       """\r
+       >>> ct = CoTee()\r
+       >>> ct.register_sink(printer_sink("1 %s"))\r
+       >>> ct.register_sink(printer_sink("2 %s"))\r
+       >>> ct.stage.send("Hello")\r
+       1 Hello\r
+       2 Hello\r
+       >>> ct.stage.send("World")\r
+       1 World\r
+       2 World\r
+       >>> ct.register_sink(printer_sink("3 %s"))\r
+       >>> ct.stage.send("Foo")\r
+       1 Foo\r
+       2 Foo\r
+       3 Foo\r
+       >>> # ct.stage.throw(RuntimeError, "Goodbye")\r
+       >>> # ct.stage.send("Meh")\r
+       >>> # ct.stage.close()\r
+       """\r
+\r
+       def __init__(self):\r
+               self.stage = self._stage()\r
+               self._targets = []\r
+\r
+       def register_sink(self, sink):\r
+               self._targets.append(sink)\r
+\r
+       def unregister_sink(self, sink):\r
+               self._targets.remove(sink)\r
+\r
+       def restart(self):\r
+               self.stage = self._stage()\r
+\r
+       @autostart\r
+       def _stage(self):\r
+               while True:\r
+                       try:\r
+                               item = yield\r
+                               for target in self._targets:\r
+                                       target.send(item)\r
+                       except StandardError, e:\r
+                               for target in self._targets:\r
+                                       target.throw(e.__class__, e.message)\r
+\r
+\r
+def _flush_queue(queue):\r
+       while not queue.empty():\r
+               yield queue.get()\r
+\r
+\r
+@autostart\r
+def cocount(target, start = 0):\r
+       """\r
+       >>> cc = cocount(printer_sink("%s"))\r
+       >>> cc.send("a")\r
+       0\r
+       >>> cc.send(None)\r
+       1\r
+       >>> cc.send([])\r
+       2\r
+       >>> cc.send(0)\r
+       3\r
+       """\r
+       for i in itertools.count(start):\r
+               item = yield\r
+               target.send(i)\r
+\r
+\r
+@autostart\r
+def coenumerate(target, start = 0):\r
+       """\r
+       >>> ce = coenumerate(printer_sink("%r"))\r
+       >>> ce.send("a")\r
+       (0, 'a')\r
+       >>> ce.send(None)\r
+       (1, None)\r
+       >>> ce.send([])\r
+       (2, [])\r
+       >>> ce.send(0)\r
+       (3, 0)\r
+       """\r
+       for i in itertools.count(start):\r
+               item = yield\r
+               decoratedItem = i, item\r
+               target.send(decoratedItem)\r
+\r
+\r
+@autostart\r
+def corepeat(target, elem):\r
+       """\r
+       >>> cr = corepeat(printer_sink("%s"), "Hello World")\r
+       >>> cr.send("a")\r
+       Hello World\r
+       >>> cr.send(None)\r
+       Hello World\r
+       >>> cr.send([])\r
+       Hello World\r
+       >>> cr.send(0)\r
+       Hello World\r
+       """\r
+       while True:\r
+               item = yield\r
+               target.send(elem)\r
+\r
+\r
+@autostart\r
+def cointercept(target, elems):\r
+       """\r
+       >>> cr = cointercept(printer_sink("%s"), [1, 2, 3, 4])\r
+       >>> cr.send("a")\r
+       1\r
+       >>> cr.send(None)\r
+       2\r
+       >>> cr.send([])\r
+       3\r
+       >>> cr.send(0)\r
+       4\r
+       >>> cr.send("Bye")\r
+       Traceback (most recent call last):\r
+         File "/usr/lib/python2.5/doctest.py", line 1228, in __run\r
+           compileflags, 1) in test.globs\r
+         File "<doctest __main__.cointercept[5]>", line 1, in <module>\r
+           cr.send("Bye")\r
+       StopIteration\r
+       """\r
+       item = yield\r
+       for elem in elems:\r
+               target.send(elem)\r
+               item = yield\r
+\r
+\r
+@autostart\r
+def codropwhile(target, pred):\r
+       """\r
+       >>> cdw = codropwhile(printer_sink("%s"), lambda x: x)\r
+       >>> cdw.send([0, 1, 2])\r
+       >>> cdw.send(1)\r
+       >>> cdw.send(True)\r
+       >>> cdw.send(False)\r
+       >>> cdw.send([0, 1, 2])\r
+       [0, 1, 2]\r
+       >>> cdw.send(1)\r
+       1\r
+       >>> cdw.send(True)\r
+       True\r
+       """\r
+       while True:\r
+               item = yield\r
+               if not pred(item):\r
+                       break\r
+\r
+       while True:\r
+               item = yield\r
+               target.send(item)\r
+\r
+\r
+@autostart\r
+def cotakewhile(target, pred):\r
+       """\r
+       >>> ctw = cotakewhile(printer_sink("%s"), lambda x: x)\r
+       >>> ctw.send([0, 1, 2])\r
+       [0, 1, 2]\r
+       >>> ctw.send(1)\r
+       1\r
+       >>> ctw.send(True)\r
+       True\r
+       >>> ctw.send(False)\r
+       >>> ctw.send([0, 1, 2])\r
+       >>> ctw.send(1)\r
+       >>> ctw.send(True)\r
+       """\r
+       while True:\r
+               item = yield\r
+               if not pred(item):\r
+                       break\r
+               target.send(item)\r
+\r
+       while True:\r
+               item = yield\r
+\r
+\r
+@autostart\r
+def coslice(target, lower, upper):\r
+       """\r
+       >>> cs = coslice(printer_sink("%r"), 3, 5)\r
+       >>> cs.send("0")\r
+       >>> cs.send("1")\r
+       >>> cs.send("2")\r
+       >>> cs.send("3")\r
+       '3'\r
+       >>> cs.send("4")\r
+       '4'\r
+       >>> cs.send("5")\r
+       >>> cs.send("6")\r
+       """\r
+       for i in xrange(lower):\r
+               item = yield\r
+       for i in xrange(upper - lower):\r
+               item = yield\r
+               target.send(item)\r
+       while True:\r
+               item = yield\r
+\r
+\r
+@autostart\r
+def cochain(targets):\r
+       """\r
+       >>> cr = cointercept(printer_sink("good %s"), [1, 2, 3, 4])\r
+       >>> cc = cochain([cr, printer_sink("end %s")])\r
+       >>> cc.send("a")\r
+       good 1\r
+       >>> cc.send(None)\r
+       good 2\r
+       >>> cc.send([])\r
+       good 3\r
+       >>> cc.send(0)\r
+       good 4\r
+       >>> cc.send("Bye")\r
+       end Bye\r
+       """\r
+       behind = []\r
+       for target in targets:\r
+               try:\r
+                       while behind:\r
+                               item = behind.pop()\r
+                               target.send(item)\r
+                       while True:\r
+                               item = yield\r
+                               target.send(item)\r
+               except StopIteration:\r
+                       behind.append(item)\r
+\r
+\r
+@autostart\r
+def queue_sink(queue):\r
+       """\r
+       >>> q = Queue.Queue()\r
+       >>> qs = queue_sink(q)\r
+       >>> qs.send("Hello")\r
+       >>> qs.send("World")\r
+       >>> qs.throw(RuntimeError, "Goodbye")\r
+       >>> qs.send("Meh")\r
+       >>> qs.close()\r
+       >>> print [i for i in _flush_queue(q)]\r
+       [(None, 'Hello'), (None, 'World'), (<type 'exceptions.RuntimeError'>, 'Goodbye'), (None, 'Meh'), (<type 'exceptions.GeneratorExit'>, None)]\r
+       """\r
+       while True:\r
+               try:\r
+                       item = yield\r
+                       queue.put((None, item))\r
+               except StandardError, e:\r
+                       queue.put((e.__class__, e.message))\r
+               except GeneratorExit:\r
+                       queue.put((GeneratorExit, None))\r
+                       raise\r
+\r
+\r
+def decode_item(item, target):\r
+       if item[0] is None:\r
+               target.send(item[1])\r
+               return False\r
+       elif item[0] is GeneratorExit:\r
+               target.close()\r
+               return True\r
+       else:\r
+               target.throw(item[0], item[1])\r
+               return False\r
+\r
+\r
+def queue_source(queue, target):\r
+       """\r
+       >>> q = Queue.Queue()\r
+       >>> for i in [\r
+       ...     (None, 'Hello'),\r
+       ...     (None, 'World'),\r
+       ...     (GeneratorExit, None),\r
+       ...     ]:\r
+       ...     q.put(i)\r
+       >>> qs = queue_source(q, printer_sink())\r
+       Hello\r
+       World\r
+       """\r
+       isDone = False\r
+       while not isDone:\r
+               item = queue.get()\r
+               isDone = decode_item(item, target)\r
+\r
+\r
+def threaded_stage(target, thread_factory = threading.Thread):\r
+       messages = Queue.Queue()\r
+\r
+       run_source = functools.partial(queue_source, messages, target)\r
+       thread_factory(target=run_source).start()\r
+\r
+       # Sink running in current thread\r
+       return functools.partial(queue_sink, messages)\r
+\r
+\r
+@autostart\r
+def pickle_sink(f):\r
+       while True:\r
+               try:\r
+                       item = yield\r
+                       pickle.dump((None, item), f)\r
+               except StandardError, e:\r
+                       pickle.dump((e.__class__, e.message), f)\r
+               except GeneratorExit:\r
+                       pickle.dump((GeneratorExit, ), f)\r
+                       raise\r
+               except StopIteration:\r
+                       f.close()\r
+                       return\r
+\r
+\r
+def pickle_source(f, target):\r
+       try:\r
+               isDone = False\r
+               while not isDone:\r
+                       item = pickle.load(f)\r
+                       isDone = decode_item(item, target)\r
+       except EOFError:\r
+               target.close()\r
+\r
+\r
+class EventHandler(object, xml.sax.ContentHandler):\r
+\r
+       START = "start"\r
+       TEXT = "text"\r
+       END = "end"\r
+\r
+       def __init__(self, target):\r
+               object.__init__(self)\r
+               xml.sax.ContentHandler.__init__(self)\r
+               self._target = target\r
+\r
+       def startElement(self, name, attrs):\r
+               self._target.send((self.START, (name, attrs._attrs)))\r
+\r
+       def characters(self, text):\r
+               self._target.send((self.TEXT, text))\r
+\r
+       def endElement(self, name):\r
+               self._target.send((self.END, name))\r
+\r
+\r
+def expat_parse(f, target):\r
+       parser = xml.parsers.expat.ParserCreate()\r
+       parser.buffer_size = 65536\r
+       parser.buffer_text = True\r
+       parser.returns_unicode = False\r
+       parser.StartElementHandler = lambda name, attrs: target.send(('start', (name, attrs)))\r
+       parser.EndElementHandler = lambda name: target.send(('end', name))\r
+       parser.CharacterDataHandler = lambda data: target.send(('text', data))\r
+       parser.ParseFile(f)\r
+\r
+\r
+if __name__ == "__main__":\r
+       import doctest\r
+       doctest.testmod()\r
diff --git a/src/util/go_utils.py b/src/util/go_utils.py
new file mode 100644 (file)
index 0000000..d066542
--- /dev/null
@@ -0,0 +1,326 @@
+#!/usr/bin/env python
+
+from __future__ import with_statement
+
+import time
+import functools
+import threading
+import Queue
+import logging
+
+import gobject
+
+import algorithms
+import misc
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+def make_idler(func):
+       """
+       Decorator that makes a generator-function into a function that will continue execution on next call
+       """
+       a = []
+
+       @functools.wraps(func)
+       def decorated_func(*args, **kwds):
+               if not a:
+                       a.append(func(*args, **kwds))
+               try:
+                       a[0].next()
+                       return True
+               except StopIteration:
+                       del a[:]
+                       return False
+
+       return decorated_func
+
+
+def async(func):
+       """
+       Make a function mainloop friendly. the function will be called at the
+       next mainloop idle state.
+
+       >>> import misc
+       >>> misc.validate_decorator(async)
+       """
+
+       @functools.wraps(func)
+       def new_function(*args, **kwargs):
+
+               def async_function():
+                       func(*args, **kwargs)
+                       return False
+
+               gobject.idle_add(async_function)
+
+       return new_function
+
+
+class Async(object):
+
+       def __init__(self, func, once = True):
+               self.__func = func
+               self.__idleId = None
+               self.__once = once
+
+       def start(self):
+               assert self.__idleId is None
+               if self.__once:
+                       self.__idleId = gobject.idle_add(self._on_once)
+               else:
+                       self.__idleId = gobject.idle_add(self.__func)
+
+       def is_running(self):
+               return self.__idleId is not None
+
+       def cancel(self):
+               if self.__idleId is not None:
+                       gobject.source_remove(self.__idleId)
+                       self.__idleId = None
+
+       def __call__(self):
+               return self.start()
+
+       @misc.log_exception(_moduleLogger)
+       def _on_once(self):
+               self.cancel()
+               try:
+                       self.__func()
+               except Exception:
+                       pass
+               return False
+
+
+class Timeout(object):
+
+       def __init__(self, func, once = True):
+               self.__func = func
+               self.__timeoutId = None
+               self.__once = once
+
+       def start(self, **kwds):
+               assert self.__timeoutId is None
+
+               callback = self._on_once if self.__once else self.__func
+
+               assert len(kwds) == 1
+               timeoutInSeconds = kwds["seconds"]
+               assert 0 <= timeoutInSeconds
+
+               if timeoutInSeconds == 0:
+                       self.__timeoutId = gobject.idle_add(callback)
+               else:
+                       self.__timeoutId = timeout_add_seconds(timeoutInSeconds, callback)
+
+       def is_running(self):
+               return self.__timeoutId is not None
+
+       def cancel(self):
+               if self.__timeoutId is not None:
+                       gobject.source_remove(self.__timeoutId)
+                       self.__timeoutId = None
+
+       def __call__(self, **kwds):
+               return self.start(**kwds)
+
+       @misc.log_exception(_moduleLogger)
+       def _on_once(self):
+               self.cancel()
+               try:
+                       self.__func()
+               except Exception:
+                       pass
+               return False
+
+
+_QUEUE_EMPTY = object()
+
+
+class AsyncPool(object):
+
+       def __init__(self):
+               self.__workQueue = Queue.Queue()
+               self.__thread = threading.Thread(
+                       name = type(self).__name__,
+                       target = self.__consume_queue,
+               )
+               self.__isRunning = True
+
+       def start(self):
+               self.__thread.start()
+
+       def stop(self):
+               self.__isRunning = False
+               for _ in algorithms.itr_available(self.__workQueue):
+                       pass # eat up queue to cut down dumb work
+               self.__workQueue.put(_QUEUE_EMPTY)
+
+       def clear_tasks(self):
+               for _ in algorithms.itr_available(self.__workQueue):
+                       pass # eat up queue to cut down dumb work
+
+       def add_task(self, func, args, kwds, on_success, on_error):
+               task = func, args, kwds, on_success, on_error
+               self.__workQueue.put(task)
+
+       @misc.log_exception(_moduleLogger)
+       def __trampoline_callback(self, on_success, on_error, isError, result):
+               if not self.__isRunning:
+                       if isError:
+                               _moduleLogger.error("Masking: %s" % (result, ))
+                       isError = True
+                       result = StopIteration("Cancelling all callbacks")
+               callback = on_success if not isError else on_error
+               try:
+                       callback(result)
+               except Exception:
+                       _moduleLogger.exception("Callback errored")
+               return False
+
+       @misc.log_exception(_moduleLogger)
+       def __consume_queue(self):
+               while True:
+                       task = self.__workQueue.get()
+                       if task is _QUEUE_EMPTY:
+                               break
+                       func, args, kwds, on_success, on_error = task
+
+                       try:
+                               result = func(*args, **kwds)
+                               isError = False
+                       except Exception, e:
+                               _moduleLogger.error("Error, passing it back to the main thread")
+                               result = e
+                               isError = True
+                       self.__workQueue.task_done()
+
+                       gobject.idle_add(self.__trampoline_callback, on_success, on_error, isError, result)
+               _moduleLogger.debug("Shutting down worker thread")
+
+
+class AsyncLinearExecution(object):
+
+       def __init__(self, pool, func):
+               self._pool = pool
+               self._func = func
+               self._run = None
+
+       def start(self, *args, **kwds):
+               assert self._run is None
+               self._run = self._func(*args, **kwds)
+               trampoline, args, kwds = self._run.send(None) # priming the function
+               self._pool.add_task(
+                       trampoline,
+                       args,
+                       kwds,
+                       self.on_success,
+                       self.on_error,
+               )
+
+       @misc.log_exception(_moduleLogger)
+       def on_success(self, result):
+               _moduleLogger.debug("Processing success for: %r", self._func)
+               try:
+                       trampoline, args, kwds = self._run.send(result)
+               except StopIteration, e:
+                       pass
+               else:
+                       self._pool.add_task(
+                               trampoline,
+                               args,
+                               kwds,
+                               self.on_success,
+                               self.on_error,
+                       )
+
+       @misc.log_exception(_moduleLogger)
+       def on_error(self, error):
+               _moduleLogger.debug("Processing error for: %r", self._func)
+               try:
+                       trampoline, args, kwds = self._run.throw(error)
+               except StopIteration, e:
+                       pass
+               else:
+                       self._pool.add_task(
+                               trampoline,
+                               args,
+                               kwds,
+                               self.on_success,
+                               self.on_error,
+                       )
+
+
+class AutoSignal(object):
+
+       def __init__(self, toplevel):
+               self.__disconnectPool = []
+               toplevel.connect("destroy", self.__on_destroy)
+
+       def connect_auto(self, widget, *args):
+               id = widget.connect(*args)
+               self.__disconnectPool.append((widget, id))
+
+       @misc.log_exception(_moduleLogger)
+       def __on_destroy(self, widget):
+               _moduleLogger.info("Destroy: %r (%s to clean up)" % (self, len(self.__disconnectPool)))
+               for widget, id in self.__disconnectPool:
+                       widget.disconnect(id)
+               del self.__disconnectPool[:]
+
+
+def throttled(minDelay, queue):
+       """
+       Throttle the calls to a function by queueing all the calls that happen
+       before the minimum delay
+
+       >>> import misc
+       >>> import Queue
+       >>> misc.validate_decorator(throttled(0, Queue.Queue()))
+       """
+
+       def actual_decorator(func):
+
+               lastCallTime = [None]
+
+               def process_queue():
+                       if 0 < len(queue):
+                               func, args, kwargs = queue.pop(0)
+                               lastCallTime[0] = time.time() * 1000
+                               func(*args, **kwargs)
+                       return False
+
+               @functools.wraps(func)
+               def new_function(*args, **kwargs):
+                       now = time.time() * 1000
+                       if (
+                               lastCallTime[0] is None or
+                               (now - lastCallTime >= minDelay)
+                       ):
+                               lastCallTime[0] = now
+                               func(*args, **kwargs)
+                       else:
+                               queue.append((func, args, kwargs))
+                               lastCallDelta = now - lastCallTime[0]
+                               processQueueTimeout = int(minDelay * len(queue) - lastCallDelta)
+                               gobject.timeout_add(processQueueTimeout, process_queue)
+
+               return new_function
+
+       return actual_decorator
+
+
+def _old_timeout_add_seconds(timeout, callback):
+       return gobject.timeout_add(timeout * 1000, callback)
+
+
+def _timeout_add_seconds(timeout, callback):
+       return gobject.timeout_add_seconds(timeout, callback)
+
+
+try:
+       gobject.timeout_add_seconds
+       timeout_add_seconds = _timeout_add_seconds
+except AttributeError:
+       timeout_add_seconds = _old_timeout_add_seconds
diff --git a/src/util/io.py b/src/util/io.py
new file mode 100644 (file)
index 0000000..aece2dd
--- /dev/null
@@ -0,0 +1,129 @@
+#!/usr/bin/env python
+
+
+from __future__ import with_statement
+
+import os
+import pickle
+import contextlib
+import itertools
+import functools
+
+
+@contextlib.contextmanager
+def change_directory(directory):
+       previousDirectory = os.getcwd()
+       os.chdir(directory)
+       currentDirectory = os.getcwd()
+
+       try:
+               yield previousDirectory, currentDirectory
+       finally:
+               os.chdir(previousDirectory)
+
+
+@contextlib.contextmanager
+def pickled(filename):
+       """
+       Here is an example usage:
+       with pickled("foo.db") as p:
+               p("users", list).append(["srid", "passwd", 23])
+       """
+
+       if os.path.isfile(filename):
+               data = pickle.load(open(filename))
+       else:
+               data = {}
+
+       def getter(item, factory):
+               if item in data:
+                       return data[item]
+               else:
+                       data[item] = factory()
+                       return data[item]
+
+       yield getter
+
+       pickle.dump(data, open(filename, "w"))
+
+
+@contextlib.contextmanager
+def redirect(object_, attr, value):
+       """
+       >>> import sys
+       ... with redirect(sys, 'stdout', open('stdout', 'w')):
+       ...     print "hello"
+       ...
+       >>> print "we're back"
+       we're back
+       """
+       orig = getattr(object_, attr)
+       setattr(object_, attr, value)
+       try:
+               yield
+       finally:
+               setattr(object_, attr, orig)
+
+
+def pathsplit(path):
+       """
+       >>> pathsplit("/a/b/c")
+       ['', 'a', 'b', 'c']
+       >>> pathsplit("./plugins/builtins.ini")
+       ['.', 'plugins', 'builtins.ini']
+       """
+       pathParts = path.split(os.path.sep)
+       return pathParts
+
+
+def commonpath(l1, l2, common=None):
+       """
+       >>> commonpath(pathsplit('/a/b/c/d'), pathsplit('/a/b/c1/d1'))
+       (['', 'a', 'b'], ['c', 'd'], ['c1', 'd1'])
+       >>> commonpath(pathsplit("./plugins/"), pathsplit("./plugins/builtins.ini"))
+       (['.', 'plugins'], [''], ['builtins.ini'])
+       >>> commonpath(pathsplit("./plugins/builtins"), pathsplit("./plugins"))
+       (['.', 'plugins'], ['builtins'], [])
+       """
+       if common is None:
+               common = []
+
+       if l1 == l2:
+               return l1, [], []
+
+       for i, (leftDir, rightDir) in enumerate(zip(l1, l2)):
+               if leftDir != rightDir:
+                       return l1[0:i], l1[i:], l2[i:]
+       else:
+               if leftDir == rightDir:
+                       i += 1
+               return l1[0:i], l1[i:], l2[i:]
+
+
+def relpath(p1, p2):
+       """
+       >>> relpath('/', '/')
+       './'
+       >>> relpath('/a/b/c/d', '/')
+       '../../../../'
+       >>> relpath('/a/b/c/d', '/a/b/c1/d1')
+       '../../c1/d1'
+       >>> relpath('/a/b/c/d', '/a/b/c1/d1/')
+       '../../c1/d1'
+       >>> relpath("./plugins/builtins", "./plugins")
+       '../'
+       >>> relpath("./plugins/", "./plugins/builtins.ini")
+       'builtins.ini'
+       """
+       sourcePath = os.path.normpath(p1)
+       destPath = os.path.normpath(p2)
+
+       (common, sourceOnly, destOnly) = commonpath(pathsplit(sourcePath), pathsplit(destPath))
+       if len(sourceOnly) or len(destOnly):
+               relParts = itertools.chain(
+                       (('..' + os.sep) * len(sourceOnly), ),
+                       destOnly,
+               )
+               return os.path.join(*relParts)
+       else:
+               return "."+os.sep
diff --git a/src/util/linux.py b/src/util/linux.py
new file mode 100644 (file)
index 0000000..4837f2a
--- /dev/null
@@ -0,0 +1,13 @@
+#!/usr/bin/env python
+
+
+import logging
+
+
+def set_process_name(name):
+       try: # change process name for killall
+               import ctypes
+               libc = ctypes.CDLL('libc.so.6')
+               libc.prctl(15, name, 0, 0, 0)
+       except Exception, e:
+               logging.warning('Unable to set processName: %s" % e')
diff --git a/src/util/misc.py b/src/util/misc.py
new file mode 100644 (file)
index 0000000..cf5c22a
--- /dev/null
@@ -0,0 +1,757 @@
+#!/usr/bin/env python
+
+from __future__ import with_statement
+
+import sys
+import re
+import cPickle
+
+import functools
+import contextlib
+import inspect
+
+import optparse
+import traceback
+import warnings
+import string
+
+
+_indentationLevel = [0]
+
+
+def log_call(logger):
+
+       def log_call_decorator(func):
+
+               @functools.wraps(func)
+               def wrapper(*args, **kwds):
+                       logger.debug("%s> %s" % (" " * _indentationLevel[0], func.__name__, ))
+                       _indentationLevel[0] += 1
+                       try:
+                               return func(*args, **kwds)
+                       finally:
+                               _indentationLevel[0] -= 1
+                               logger.debug("%s< %s" % (" " * _indentationLevel[0], func.__name__, ))
+
+               return wrapper
+
+       return log_call_decorator
+
+
+def log_exception(logger):
+
+       def log_exception_decorator(func):
+
+               @functools.wraps(func)
+               def wrapper(*args, **kwds):
+                       try:
+                               return func(*args, **kwds)
+                       except Exception:
+                               logger.exception(func.__name__)
+                               raise
+
+               return wrapper
+
+       return log_exception_decorator
+
+
+def printfmt(template):
+       """
+       This hides having to create the Template object and call substitute/safe_substitute on it. For example:
+
+       >>> num = 10
+       >>> word = "spam"
+       >>> printfmt("I would like to order $num units of $word, please") #doctest: +SKIP
+       I would like to order 10 units of spam, please
+       """
+       frame = inspect.stack()[-1][0]
+       try:
+               print string.Template(template).safe_substitute(frame.f_locals)
+       finally:
+               del frame
+
+
+def is_special(name):
+       return name.startswith("__") and name.endswith("__")
+
+
+def is_private(name):
+       return name.startswith("_") and not is_special(name)
+
+
+def privatize(clsName, attributeName):
+       """
+       At runtime, make an attributeName private
+
+       Example:
+       >>> class Test(object):
+       ...     pass
+       ...
+       >>> try:
+       ...     dir(Test).index("_Test__me")
+       ...     print dir(Test)
+       ... except:
+       ...     print "Not Found"
+       Not Found
+       >>> setattr(Test, privatize(Test.__name__, "me"), "Hello World")
+       >>> try:
+       ...     dir(Test).index("_Test__me")
+       ...     print "Found"
+       ... except:
+       ...     print dir(Test)
+       0
+       Found
+       >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
+       Hello World
+       >>>
+       >>> is_private(privatize(Test.__name__, "me"))
+       True
+       >>> is_special(privatize(Test.__name__, "me"))
+       False
+       """
+       return "".join(["_", clsName, "__", attributeName])
+
+
+def obfuscate(clsName, attributeName):
+       """
+       At runtime, turn a private name into the obfuscated form
+
+       Example:
+       >>> class Test(object):
+       ...     __me = "Hello World"
+       ...
+       >>> try:
+       ...     dir(Test).index("_Test__me")
+       ...     print "Found"
+       ... except:
+       ...     print dir(Test)
+       0
+       Found
+       >>> print getattr(Test, obfuscate(Test.__name__, "__me"))
+       Hello World
+       >>> is_private(obfuscate(Test.__name__, "__me"))
+       True
+       >>> is_special(obfuscate(Test.__name__, "__me"))
+       False
+       """
+       return "".join(["_", clsName, attributeName])
+
+
+class PAOptionParser(optparse.OptionParser, object):
+       """
+       >>> if __name__ == '__main__':
+       ...     #parser = PAOptionParser("My usage str")
+       ...     parser = PAOptionParser()
+       ...     parser.add_posarg("Foo", help="Foo usage")
+       ...     parser.add_posarg("Bar", dest="bar_dest")
+       ...     parser.add_posarg("Language", dest='tr_type', type="choice", choices=("Python", "Other"))
+       ...     parser.add_option('--stocksym', dest='symbol')
+       ...     values, args = parser.parse_args()
+       ...     print values, args
+       ...
+
+       python mycp.py  -h
+       python mycp.py
+       python mycp.py  foo
+       python mycp.py  foo bar
+
+       python mycp.py foo bar lava
+       Usage: pa.py <Foo> <Bar> <Language> [options]
+
+       Positional Arguments:
+       Foo: Foo usage
+       Bar:
+       Language:
+
+       pa.py: error: option --Language: invalid choice: 'lava' (choose from 'Python', 'Other'
+       """
+
+       def __init__(self, *args, **kw):
+               self.posargs = []
+               super(PAOptionParser, self).__init__(*args, **kw)
+
+       def add_posarg(self, *args, **kw):
+               pa_help = kw.get("help", "")
+               kw["help"] = optparse.SUPPRESS_HELP
+               o = self.add_option("--%s" % args[0], *args[1:], **kw)
+               self.posargs.append((args[0], pa_help))
+
+       def get_usage(self, *args, **kwargs):
+               params = (' '.join(["<%s>" % arg[0] for arg in self.posargs]), '\n '.join(["%s: %s" % (arg) for arg in self.posargs]))
+               self.usage = "%%prog %s [options]\n\nPositional Arguments:\n %s" % params
+               return super(PAOptionParser, self).get_usage(*args, **kwargs)
+
+       def parse_args(self, *args, **kwargs):
+               args = sys.argv[1:]
+               args0 = []
+               for p, v in zip(self.posargs, args):
+                       args0.append("--%s" % p[0])
+                       args0.append(v)
+               args = args0 + args
+               options, args = super(PAOptionParser, self).parse_args(args, **kwargs)
+               if len(args) < len(self.posargs):
+                       msg = 'Missing value(s) for "%s"\n' % ", ".join([arg[0] for arg in self.posargs][len(args):])
+                       self.error(msg)
+               return options, args
+
+
+def explicitly(name, stackadd=0):
+       """
+       This is an alias for adding to '__all__'.  Less error-prone than using
+       __all__ itself, since setting __all__ directly is prone to stomping on
+       things implicitly exported via L{alias}.
+
+       @note Taken from PyExport (which could turn out pretty cool):
+       @li @a http://codebrowse.launchpad.net/~glyph/
+       @li @a http://glyf.livejournal.com/74356.html
+       """
+       packageVars = sys._getframe(1+stackadd).f_locals
+       globalAll = packageVars.setdefault('__all__', [])
+       globalAll.append(name)
+
+
+def public(thunk):
+       """
+       This is a decorator, for convenience.  Rather than typing the name of your
+       function twice, you can decorate a function with this.
+
+       To be real, @public would need to work on methods as well, which gets into
+       supporting types...
+
+       @note Taken from PyExport (which could turn out pretty cool):
+       @li @a http://codebrowse.launchpad.net/~glyph/
+       @li @a http://glyf.livejournal.com/74356.html
+       """
+       explicitly(thunk.__name__, 1)
+       return thunk
+
+
+def _append_docstring(obj, message):
+       if obj.__doc__ is None:
+               obj.__doc__ = message
+       else:
+               obj.__doc__ += message
+
+
+def validate_decorator(decorator):
+
+       def simple(x):
+               return x
+
+       f = simple
+       f.__name__ = "name"
+       f.__doc__ = "doc"
+       f.__dict__["member"] = True
+
+       g = decorator(f)
+
+       if f.__name__ != g.__name__:
+               print f.__name__, "!=", g.__name__
+
+       if g.__doc__ is None:
+               print decorator.__name__, "has no doc string"
+       elif not g.__doc__.startswith(f.__doc__):
+               print g.__doc__, "didn't start with", f.__doc__
+
+       if not ("member" in g.__dict__ and g.__dict__["member"]):
+               print "'member' not in ", g.__dict__
+
+
+def deprecated_api(func):
+       """
+       This is a decorator which can be used to mark functions
+       as deprecated. It will result in a warning being emitted
+       when the function is used.
+
+       >>> validate_decorator(deprecated_api)
+       """
+
+       @functools.wraps(func)
+       def newFunc(*args, **kwargs):
+               warnings.warn("Call to deprecated function %s." % func.__name__, category=DeprecationWarning)
+               return func(*args, **kwargs)
+
+       _append_docstring(newFunc, "\n@deprecated")
+       return newFunc
+
+
+def unstable_api(func):
+       """
+       This is a decorator which can be used to mark functions
+       as deprecated. It will result in a warning being emitted
+       when the function is used.
+
+       >>> validate_decorator(unstable_api)
+       """
+
+       @functools.wraps(func)
+       def newFunc(*args, **kwargs):
+               warnings.warn("Call to unstable API function %s." % func.__name__, category=FutureWarning)
+               return func(*args, **kwargs)
+       _append_docstring(newFunc, "\n@unstable")
+       return newFunc
+
+
+def enabled(func):
+       """
+       This decorator doesn't add any behavior
+
+       >>> validate_decorator(enabled)
+       """
+       return func
+
+
+def disabled(func):
+       """
+       This decorator disables the provided function, and does nothing
+
+       >>> validate_decorator(disabled)
+       """
+
+       @functools.wraps(func)
+       def emptyFunc(*args, **kargs):
+               pass
+       _append_docstring(emptyFunc, "\n@note Temporarily Disabled")
+       return emptyFunc
+
+
+def metadata(document=True, **kwds):
+       """
+       >>> validate_decorator(metadata(author="Ed"))
+       """
+
+       def decorate(func):
+               for k, v in kwds.iteritems():
+                       setattr(func, k, v)
+                       if document:
+                               _append_docstring(func, "\n@"+k+" "+v)
+               return func
+       return decorate
+
+
+def prop(func):
+       """Function decorator for defining property attributes
+
+       The decorated function is expected to return a dictionary
+       containing one or more of the following pairs:
+               fget - function for getting attribute value
+               fset - function for setting attribute value
+               fdel - function for deleting attribute
+       This can be conveniently constructed by the locals() builtin
+       function; see:
+       http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
+       @author http://kbyanc.blogspot.com/2007/06/python-property-attribute-tricks.html
+
+       Example:
+       >>> #Due to transformation from function to property, does not need to be validated
+       >>> #validate_decorator(prop)
+       >>> class MyExampleClass(object):
+       ...     @prop
+       ...     def foo():
+       ...             "The foo property attribute's doc-string"
+       ...             def fget(self):
+       ...                     print "GET"
+       ...                     return self._foo
+       ...             def fset(self, value):
+       ...                     print "SET"
+       ...                     self._foo = value
+       ...             return locals()
+       ...
+       >>> me = MyExampleClass()
+       >>> me.foo = 10
+       SET
+       >>> print me.foo
+       GET
+       10
+       """
+       return property(doc=func.__doc__, **func())
+
+
+def print_handler(e):
+       """
+       @see ExpHandler
+       """
+       print "%s: %s" % (type(e).__name__, e)
+
+
+def print_ignore(e):
+       """
+       @see ExpHandler
+       """
+       print 'Ignoring %s exception: %s' % (type(e).__name__, e)
+
+
+def print_traceback(e):
+       """
+       @see ExpHandler
+       """
+       #print sys.exc_info()
+       traceback.print_exc(file=sys.stdout)
+
+
+def ExpHandler(handler = print_handler, *exceptions):
+       """
+       An exception handling idiom using decorators
+       Examples
+       Specify exceptions in order, first one is handled first
+       last one last.
+
+       >>> validate_decorator(ExpHandler())
+       >>> @ExpHandler(print_ignore, ZeroDivisionError)
+       ... @ExpHandler(None, AttributeError, ValueError)
+       ... def f1():
+       ...     1/0
+       >>> @ExpHandler(print_traceback, ZeroDivisionError)
+       ... def f2():
+       ...     1/0
+       >>> @ExpHandler()
+       ... def f3(*pargs):
+       ...     l = pargs
+       ...     return l[10]
+       >>> @ExpHandler(print_traceback, ZeroDivisionError)
+       ... def f4():
+       ...     return 1
+       >>>
+       >>>
+       >>> f1()
+       Ignoring ZeroDivisionError exception: integer division or modulo by zero
+       >>> f2() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
+       Traceback (most recent call last):
+       ...
+       ZeroDivisionError: integer division or modulo by zero
+       >>> f3()
+       IndexError: tuple index out of range
+       >>> f4()
+       1
+       """
+
+       def wrapper(f):
+               localExceptions = exceptions
+               if not localExceptions:
+                       localExceptions = [Exception]
+               t = [(ex, handler) for ex in localExceptions]
+               t.reverse()
+
+               def newfunc(t, *args, **kwargs):
+                       ex, handler = t[0]
+                       try:
+                               if len(t) == 1:
+                                       return f(*args, **kwargs)
+                               else:
+                                       #Recurse for embedded try/excepts
+                                       dec_func = functools.partial(newfunc, t[1:])
+                                       dec_func = functools.update_wrapper(dec_func, f)
+                                       return dec_func(*args, **kwargs)
+                       except ex, e:
+                               return handler(e)
+
+               dec_func = functools.partial(newfunc, t)
+               dec_func = functools.update_wrapper(dec_func, f)
+               return dec_func
+       return wrapper
+
+
+def into_debugger(func):
+       """
+       >>> validate_decorator(into_debugger)
+       """
+
+       @functools.wraps(func)
+       def newFunc(*args, **kwargs):
+               try:
+                       return func(*args, **kwargs)
+               except:
+                       import pdb
+                       pdb.post_mortem()
+
+       return newFunc
+
+
+class bindclass(object):
+       """
+       >>> validate_decorator(bindclass)
+       >>> class Foo(BoundObject):
+       ...      @bindclass
+       ...      def foo(this_class, self):
+       ...              return this_class, self
+       ...
+       >>> class Bar(Foo):
+       ...      @bindclass
+       ...      def bar(this_class, self):
+       ...              return this_class, self
+       ...
+       >>> f = Foo()
+       >>> b = Bar()
+       >>>
+       >>> f.foo() # doctest: +ELLIPSIS
+       (<class '...Foo'>, <...Foo object at ...>)
+       >>> b.foo() # doctest: +ELLIPSIS
+       (<class '...Foo'>, <...Bar object at ...>)
+       >>> b.bar() # doctest: +ELLIPSIS
+       (<class '...Bar'>, <...Bar object at ...>)
+       """
+
+       def __init__(self, f):
+               self.f = f
+               self.__name__ = f.__name__
+               self.__doc__ = f.__doc__
+               self.__dict__.update(f.__dict__)
+               self.m = None
+
+       def bind(self, cls, attr):
+
+               def bound_m(*args, **kwargs):
+                       return self.f(cls, *args, **kwargs)
+               bound_m.__name__ = attr
+               self.m = bound_m
+
+       def __get__(self, obj, objtype=None):
+               return self.m.__get__(obj, objtype)
+
+
+class ClassBindingSupport(type):
+       "@see bindclass"
+
+       def __init__(mcs, name, bases, attrs):
+               type.__init__(mcs, name, bases, attrs)
+               for attr, val in attrs.iteritems():
+                       if isinstance(val, bindclass):
+                               val.bind(mcs, attr)
+
+
+class BoundObject(object):
+       "@see bindclass"
+       __metaclass__ = ClassBindingSupport
+
+
+def bindfunction(f):
+       """
+       >>> validate_decorator(bindfunction)
+       >>> @bindfunction
+       ... def factorial(thisfunction, n):
+       ...      # Within this function the name 'thisfunction' refers to the factorial
+       ...      # function(with only one argument), even after 'factorial' is bound
+       ...      # to another object
+       ...      if n > 0:
+       ...              return n * thisfunction(n - 1)
+       ...      else:
+       ...              return 1
+       ...
+       >>> factorial(3)
+       6
+       """
+
+       @functools.wraps(f)
+       def bound_f(*args, **kwargs):
+               return f(bound_f, *args, **kwargs)
+       return bound_f
+
+
+class Memoize(object):
+       """
+       Memoize(fn) - an instance which acts like fn but memoizes its arguments
+       Will only work on functions with non-mutable arguments
+       @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
+
+       >>> validate_decorator(Memoize)
+       """
+
+       def __init__(self, fn):
+               self.fn = fn
+               self.__name__ = fn.__name__
+               self.__doc__ = fn.__doc__
+               self.__dict__.update(fn.__dict__)
+               self.memo = {}
+
+       def __call__(self, *args):
+               if args not in self.memo:
+                       self.memo[args] = self.fn(*args)
+               return self.memo[args]
+
+
+class MemoizeMutable(object):
+       """Memoize(fn) - an instance which acts like fn but memoizes its arguments
+       Will work on functions with mutable arguments(slower than Memoize)
+       @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201
+
+       >>> validate_decorator(MemoizeMutable)
+       """
+
+       def __init__(self, fn):
+               self.fn = fn
+               self.__name__ = fn.__name__
+               self.__doc__ = fn.__doc__
+               self.__dict__.update(fn.__dict__)
+               self.memo = {}
+
+       def __call__(self, *args, **kw):
+               text = cPickle.dumps((args, kw))
+               if text not in self.memo:
+                       self.memo[text] = self.fn(*args, **kw)
+               return self.memo[text]
+
+
+callTraceIndentationLevel = 0
+
+
+def call_trace(f):
+       """
+       Synchronization decorator.
+
+       >>> validate_decorator(call_trace)
+       >>> @call_trace
+       ... def a(a, b, c):
+       ...     pass
+       >>> a(1, 2, c=3)
+       Entering a((1, 2), {'c': 3})
+       Exiting a((1, 2), {'c': 3})
+       """
+
+       @functools.wraps(f)
+       def verboseTrace(*args, **kw):
+               global callTraceIndentationLevel
+
+               print "%sEntering %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
+               callTraceIndentationLevel += 1
+               try:
+                       result = f(*args, **kw)
+               except:
+                       callTraceIndentationLevel -= 1
+                       print "%sException %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
+                       raise
+               callTraceIndentationLevel -= 1
+               print "%sExiting %s(%s, %s)" % ("\t"*callTraceIndentationLevel, f.__name__, args, kw)
+               return result
+
+       @functools.wraps(f)
+       def smallTrace(*args, **kw):
+               global callTraceIndentationLevel
+
+               print "%sEntering %s" % ("\t"*callTraceIndentationLevel, f.__name__)
+               callTraceIndentationLevel += 1
+               try:
+                       result = f(*args, **kw)
+               except:
+                       callTraceIndentationLevel -= 1
+                       print "%sException %s" % ("\t"*callTraceIndentationLevel, f.__name__)
+                       raise
+               callTraceIndentationLevel -= 1
+               print "%sExiting %s" % ("\t"*callTraceIndentationLevel, f.__name__)
+               return result
+
+       #return smallTrace
+       return verboseTrace
+
+
+@contextlib.contextmanager
+def lexical_scope(*args):
+       """
+       @note Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/520586
+       Example:
+       >>> b = 0
+       >>> with lexical_scope(1) as (a):
+       ...     print a
+       ...
+       1
+       >>> with lexical_scope(1,2,3) as (a,b,c):
+       ...     print a,b,c
+       ...
+       1 2 3
+       >>> with lexical_scope():
+       ...     d = 10
+       ...     def foo():
+       ...             pass
+       ...
+       >>> print b
+       2
+       """
+
+       frame = inspect.currentframe().f_back.f_back
+       saved = frame.f_locals.keys()
+       try:
+               if not args:
+                       yield
+               elif len(args) == 1:
+                       yield args[0]
+               else:
+                       yield args
+       finally:
+               f_locals = frame.f_locals
+               for key in (x for x in f_locals.keys() if x not in saved):
+                       del f_locals[key]
+               del frame
+
+
+def normalize_number(prettynumber):
+       """
+       function to take a phone number and strip out all non-numeric
+       characters
+
+       >>> normalize_number("+012-(345)-678-90")
+       '+01234567890'
+       >>> normalize_number("1-(345)-678-9000")
+       '+13456789000'
+       >>> normalize_number("+1-(345)-678-9000")
+       '+13456789000'
+       """
+       uglynumber = re.sub('[^0-9+]', '', prettynumber)
+       if uglynumber.startswith("+"):
+               pass
+       elif uglynumber.startswith("1") and len(uglynumber) == 11:
+               uglynumber = "+"+uglynumber
+       elif len(uglynumber) == 10:
+               uglynumber = "+1"+uglynumber
+       else:
+               pass
+
+       #validateRe = re.compile("^\+?[0-9]{10,}$")
+       #assert validateRe.match(uglynumber) is not None
+
+       return uglynumber
+
+
+_VALIDATE_RE = re.compile("^\+?[0-9]{10,}$")
+
+
+def is_valid_number(number):
+       """
+       @returns If This number be called ( syntax validation only )
+       """
+       return _VALIDATE_RE.match(number) is not None
+
+
+def parse_version(versionText):
+       """
+       >>> parse_version("0.5.2")
+       [0, 5, 2]
+       """
+       return [
+               int(number)
+               for number in versionText.split(".")
+       ]
+
+
+def compare_versions(leftParsedVersion, rightParsedVersion):
+       """
+       >>> compare_versions([0, 1, 2], [0, 1, 2])
+       0
+       >>> compare_versions([0, 1, 2], [0, 1, 3])
+       -1
+       >>> compare_versions([0, 1, 2], [0, 2, 2])
+       -1
+       >>> compare_versions([0, 1, 2], [1, 1, 2])
+       -1
+       >>> compare_versions([0, 1, 3], [0, 1, 2])
+       1
+       >>> compare_versions([0, 2, 2], [0, 1, 2])
+       1
+       >>> compare_versions([1, 1, 2], [0, 1, 2])
+       1
+       """
+       for left, right in zip(leftParsedVersion, rightParsedVersion):
+               if left < right:
+                       return -1
+               elif right < left:
+                       return 1
+       else:
+               return 0
diff --git a/src/util/overloading.py b/src/util/overloading.py
new file mode 100644 (file)
index 0000000..89cb738
--- /dev/null
@@ -0,0 +1,256 @@
+#!/usr/bin/env python
+import new
+
+# Make the environment more like Python 3.0
+__metaclass__ = type
+from itertools import izip as zip
+import textwrap
+import inspect
+
+
+__all__ = [
+       "AnyType",
+       "overloaded"
+]
+
+
+AnyType = object
+
+
+class overloaded:
+       """
+       Dynamically overloaded functions.
+
+       This is an implementation of (dynamically, or run-time) overloaded
+       functions; also known as generic functions or multi-methods.
+
+       The dispatch algorithm uses the types of all argument for dispatch,
+       similar to (compile-time) overloaded functions or methods in C++ and
+       Java.
+
+       Most of the complexity in the algorithm comes from the need to support
+       subclasses in call signatures.  For example, if an function is
+       registered for a signature (T1, T2), then a call with a signature (S1,
+       S2) is acceptable, assuming that S1 is a subclass of T1, S2 a subclass
+       of T2, and there are no other more specific matches (see below).
+
+       If there are multiple matches and one of those doesn't *dominate* all
+       others, the match is deemed ambiguous and an exception is raised.  A
+       subtlety here: if, after removing the dominated matches, there are
+       still multiple matches left, but they all map to the same function,
+       then the match is not deemed ambiguous and that function is used.
+       Read the method find_func() below for details.
+
+       @note Python 2.5 is required due to the use of predicates any() and all().
+       @note only supports positional arguments
+
+       @author http://www.artima.com/weblogs/viewpost.jsp?thread=155514
+
+       >>> import misc
+       >>> misc.validate_decorator (overloaded)
+       >>>
+       >>>
+       >>>
+       >>>
+       >>> #################
+       >>> #Basics, with reusing names and without
+       >>> @overloaded
+       ... def foo(x):
+       ...     "prints x"
+       ...     print x
+       ...
+       >>> @foo.register(int)
+       ... def foo(x):
+       ...     "prints the hex representation of x"
+       ...     print hex(x)
+       ...
+       >>> from types import DictType
+       >>> @foo.register(DictType)
+       ... def foo_dict(x):
+       ...     "prints the keys of x"
+       ...     print [k for k in x.iterkeys()]
+       ...
+       >>> #combines all of the doc strings to help keep track of the specializations
+       >>> foo.__doc__  # doctest: +ELLIPSIS
+       "prints x\\n\\n...overloading.foo (<type 'int'>):\\n\\tprints the hex representation of x\\n\\n...overloading.foo_dict (<type 'dict'>):\\n\\tprints the keys of x"
+       >>> foo ("text")
+       text
+       >>> foo (10) #calling the specialized foo
+       0xa
+       >>> foo ({3:5, 6:7}) #calling the specialization foo_dict
+       [3, 6]
+       >>> foo_dict ({3:5, 6:7}) #with using a unique name, you still have the option of calling the function directly
+       [3, 6]
+       >>>
+       >>>
+       >>>
+       >>>
+       >>> #################
+       >>> #Multiple arguments, accessing the default, and function finding
+       >>> @overloaded
+       ... def two_arg (x, y):
+       ...     print x,y
+       ...
+       >>> @two_arg.register(int, int)
+       ... def two_arg_int_int (x, y):
+       ...     print hex(x), hex(y)
+       ...
+       >>> @two_arg.register(float, int)
+       ... def two_arg_float_int (x, y):
+       ...     print x, hex(y)
+       ...
+       >>> @two_arg.register(int, float)
+       ... def two_arg_int_float (x, y):
+       ...     print hex(x), y
+       ...
+       >>> two_arg.__doc__ # doctest: +ELLIPSIS
+       "...overloading.two_arg_int_int (<type 'int'>, <type 'int'>):\\n\\n...overloading.two_arg_float_int (<type 'float'>, <type 'int'>):\\n\\n...overloading.two_arg_int_float (<type 'int'>, <type 'float'>):"
+       >>> two_arg(9, 10)
+       0x9 0xa
+       >>> two_arg(9.0, 10)
+       9.0 0xa
+       >>> two_arg(15, 16.0)
+       0xf 16.0
+       >>> two_arg.default_func(9, 10)
+       9 10
+       >>> two_arg.find_func ((int, float)) == two_arg_int_float
+       True
+       >>> (int, float) in two_arg
+       True
+       >>> (str, int) in two_arg
+       False
+       >>>
+       >>>
+       >>>
+       >>> #################
+       >>> #wildcard
+       >>> @two_arg.register(AnyType, str)
+       ... def two_arg_any_str (x, y):
+       ...     print x, y.lower()
+       ...
+       >>> two_arg("Hello", "World")
+       Hello world
+       >>> two_arg(500, "World")
+       500 world
+       """
+
+       def __init__(self, default_func):
+               # Decorator to declare new overloaded function.
+               self.registry = {}
+               self.cache = {}
+               self.default_func = default_func
+               self.__name__ = self.default_func.__name__
+               self.__doc__ = self.default_func.__doc__
+               self.__dict__.update (self.default_func.__dict__)
+
+       def __get__(self, obj, type=None):
+               if obj is None:
+                       return self
+               return new.instancemethod(self, obj)
+
+       def register(self, *types):
+               """
+               Decorator to register an implementation for a specific set of types.
+
+               .register(t1, t2)(f) is equivalent to .register_func((t1, t2), f).
+               """
+
+               def helper(func):
+                       self.register_func(types, func)
+
+                       originalDoc = self.__doc__ if self.__doc__ is not None else ""
+                       typeNames = ", ".join ([str(type) for type in types])
+                       typeNames = "".join ([func.__module__+".", func.__name__, " (", typeNames, "):"])
+                       overloadedDoc = ""
+                       if func.__doc__ is not None:
+                               overloadedDoc = textwrap.fill (func.__doc__, width=60, initial_indent="\t", subsequent_indent="\t")
+                       self.__doc__ = "\n".join ([originalDoc, "", typeNames, overloadedDoc]).strip()
+
+                       new_func = func
+
+                       #Masking the function, so we want to take on its traits
+                       if func.__name__ == self.__name__:
+                               self.__dict__.update (func.__dict__)
+                               new_func = self
+                       return new_func
+
+               return helper
+
+       def register_func(self, types, func):
+               """Helper to register an implementation."""
+               self.registry[tuple(types)] = func
+               self.cache = {} # Clear the cache (later we can optimize this).
+
+       def __call__(self, *args):
+               """Call the overloaded function."""
+               types = tuple(map(type, args))
+               func = self.cache.get(types)
+               if func is None:
+                       self.cache[types] = func = self.find_func(types)
+               return func(*args)
+
+       def __contains__ (self, types):
+               return self.find_func(types) is not self.default_func
+
+       def find_func(self, types):
+               """Find the appropriate overloaded function; don't call it.
+
+               @note This won't work for old-style classes or classes without __mro__
+               """
+               func = self.registry.get(types)
+               if func is not None:
+                       # Easy case -- direct hit in registry.
+                       return func
+
+               # Phillip Eby suggests to use issubclass() instead of __mro__.
+               # There are advantages and disadvantages.
+
+               # I can't help myself -- this is going to be intense functional code.
+               # Find all possible candidate signatures.
+               mros = tuple(inspect.getmro(t) for t in types)
+               n = len(mros)
+               candidates = [sig for sig in self.registry
+                               if len(sig) == n and
+                                       all(t in mro for t, mro in zip(sig, mros))]
+
+               if not candidates:
+                       # No match at all -- use the default function.
+                       return self.default_func
+               elif len(candidates) == 1:
+                       # Unique match -- that's an easy case.
+                       return self.registry[candidates[0]]
+
+               # More than one match -- weed out the subordinate ones.
+
+               def dominates(dom, sub,
+                               orders=tuple(dict((t, i) for i, t in enumerate(mro))
+                                                       for mro in mros)):
+                       # Predicate to decide whether dom strictly dominates sub.
+                       # Strict domination is defined as domination without equality.
+                       # The arguments dom and sub are type tuples of equal length.
+                       # The orders argument is a precomputed auxiliary data structure
+                       # giving dicts of ordering information corresponding to the
+                       # positions in the type tuples.
+                       # A type d dominates a type s iff order[d] <= order[s].
+                       # A type tuple (d1, d2, ...) dominates a type tuple of equal length
+                       # (s1, s2, ...) iff d1 dominates s1, d2 dominates s2, etc.
+                       if dom is sub:
+                               return False
+                       return all(order[d] <= order[s] for d, s, order in zip(dom, sub, orders))
+
+               # I suppose I could inline dominates() but it wouldn't get any clearer.
+               candidates = [cand
+                               for cand in candidates
+                                       if not any(dominates(dom, cand) for dom in candidates)]
+               if len(candidates) == 1:
+                       # There's exactly one candidate left.
+                       return self.registry[candidates[0]]
+
+               # Perhaps these multiple candidates all have the same implementation?
+               funcs = set(self.registry[cand] for cand in candidates)
+               if len(funcs) == 1:
+                       return funcs.pop()
+
+               # No, the situation is irreducibly ambiguous.
+               raise TypeError("ambigous call; types=%r; candidates=%r" %
+                                               (types, candidates))
diff --git a/src/util/time_utils.py b/src/util/time_utils.py
new file mode 100644 (file)
index 0000000..90ec84d
--- /dev/null
@@ -0,0 +1,94 @@
+from datetime import tzinfo, timedelta, datetime
+
+ZERO = timedelta(0)
+HOUR = timedelta(hours=1)
+
+
+def first_sunday_on_or_after(dt):
+       days_to_go = 6 - dt.weekday()
+       if days_to_go:
+               dt += timedelta(days_to_go)
+       return dt
+
+
+# US DST Rules
+#
+# This is a simplified (i.e., wrong for a few cases) set of rules for US
+# DST start and end times. For a complete and up-to-date set of DST rules
+# and timezone definitions, visit the Olson Database (or try pytz):
+# http://www.twinsun.com/tz/tz-link.htm
+# http://sourceforge.net/projects/pytz/ (might not be up-to-date)
+#
+# In the US, since 2007, DST starts at 2am (standard time) on the second
+# Sunday in March, which is the first Sunday on or after Mar 8.
+DSTSTART_2007 = datetime(1, 3, 8, 2)
+# and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov.
+DSTEND_2007 = datetime(1, 11, 1, 1)
+# From 1987 to 2006, DST used to start at 2am (standard time) on the first
+# Sunday in April and to end at 2am (DST time; 1am standard time) on the last
+# Sunday of October, which is the first Sunday on or after Oct 25.
+DSTSTART_1987_2006 = datetime(1, 4, 1, 2)
+DSTEND_1987_2006 = datetime(1, 10, 25, 1)
+# From 1967 to 1986, DST used to start at 2am (standard time) on the last
+# Sunday in April (the one on or after April 24) and to end at 2am (DST time;
+# 1am standard time) on the last Sunday of October, which is the first Sunday
+# on or after Oct 25.
+DSTSTART_1967_1986 = datetime(1, 4, 24, 2)
+DSTEND_1967_1986 = DSTEND_1987_2006
+
+
+class USTimeZone(tzinfo):
+
+       def __init__(self, hours, reprname, stdname, dstname):
+               self.stdoffset = timedelta(hours=hours)
+               self.reprname = reprname
+               self.stdname = stdname
+               self.dstname = dstname
+
+       def __repr__(self):
+               return self.reprname
+
+       def tzname(self, dt):
+               if self.dst(dt):
+                       return self.dstname
+               else:
+                       return self.stdname
+
+       def utcoffset(self, dt):
+               return self.stdoffset + self.dst(dt)
+
+       def dst(self, dt):
+               if dt is None or dt.tzinfo is None:
+                       # An exception may be sensible here, in one or both cases.
+                       # It depends on how you want to treat them.  The default
+                       # fromutc() implementation (called by the default astimezone()
+                       # implementation) passes a datetime with dt.tzinfo is self.
+                       return ZERO
+               assert dt.tzinfo is self
+
+               # Find start and end times for US DST. For years before 1967, return
+               # ZERO for no DST.
+               if 2006 < dt.year:
+                       dststart, dstend = DSTSTART_2007, DSTEND_2007
+               elif 1986 < dt.year < 2007:
+                       dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006
+               elif 1966 < dt.year < 1987:
+                       dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986
+               else:
+                       return ZERO
+
+               start = first_sunday_on_or_after(dststart.replace(year=dt.year))
+               end = first_sunday_on_or_after(dstend.replace(year=dt.year))
+
+               # Can't compare naive to aware objects, so strip the timezone from
+               # dt first.
+               if start <= dt.replace(tzinfo=None) < end:
+                       return HOUR
+               else:
+                       return ZERO
+
+
+Eastern  = USTimeZone(-5, "Eastern",  "EST", "EDT")
+Central  = USTimeZone(-6, "Central",  "CST", "CDT")
+Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
+Pacific  = USTimeZone(-8, "Pacific",  "PST", "PDT")
diff --git a/src/util/tp_utils.py b/src/util/tp_utils.py
new file mode 100644 (file)
index 0000000..1c6cbc8
--- /dev/null
@@ -0,0 +1,220 @@
+#!/usr/bin/env python
+
+import logging
+
+import dbus
+import telepathy
+
+import util.go_utils as gobject_utils
+import misc
+
+
+_moduleLogger = logging.getLogger(__name__)
+DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties'
+
+
+class WasMissedCall(object):
+
+       def __init__(self, bus, conn, chan, on_success, on_error):
+               self.__on_success = on_success
+               self.__on_error = on_error
+
+               self._requested = None
+               self._didMembersChange = False
+               self._didClose = False
+               self._didReport = False
+
+               self._onTimeout = gobject_utils.Timeout(self._on_timeout)
+               self._onTimeout.start(seconds=10)
+
+               chan[telepathy.interfaces.CHANNEL_INTERFACE_GROUP].connect_to_signal(
+                       "MembersChanged",
+                       self._on_members_changed,
+               )
+
+               chan[telepathy.interfaces.CHANNEL].connect_to_signal(
+                       "Closed",
+                       self._on_closed,
+               )
+
+               chan[DBUS_PROPERTIES].GetAll(
+                       telepathy.interfaces.CHANNEL_INTERFACE,
+                       reply_handler = self._on_got_all,
+                       error_handler = self._on_error,
+               )
+
+       def cancel(self):
+               self._report_error("by request")
+
+       def _report_missed_if_ready(self):
+               if self._didReport:
+                       pass
+               elif self._requested is not None and (self._didMembersChange or self._didClose):
+                       if self._requested:
+                               self._report_error("wrong direction")
+                       elif self._didClose:
+                               self._report_success()
+                       else:
+                               self._report_error("members added")
+               else:
+                       if self._didClose:
+                               self._report_error("closed too early")
+
+       def _report_success(self):
+               assert not self._didReport
+               self._didReport = True
+               self._onTimeout.cancel()
+               self.__on_success(self)
+
+       def _report_error(self, reason):
+               assert not self._didReport
+               self._didReport = True
+               self._onTimeout.cancel()
+               self.__on_error(self, reason)
+
+       @misc.log_exception(_moduleLogger)
+       def _on_got_all(self, properties):
+               self._requested = properties["Requested"]
+               self._report_missed_if_ready()
+
+       @misc.log_exception(_moduleLogger)
+       def _on_members_changed(self, message, added, removed, lp, rp, actor, reason):
+               if added:
+                       self._didMembersChange = True
+                       self._report_missed_if_ready()
+
+       @misc.log_exception(_moduleLogger)
+       def _on_closed(self):
+               self._didClose = True
+               self._report_missed_if_ready()
+
+       @misc.log_exception(_moduleLogger)
+       def _on_error(self, *args):
+               self._report_error(args)
+
+       @misc.log_exception(_moduleLogger)
+       def _on_timeout(self):
+               self._report_error("timeout")
+               return False
+
+
+class NewChannelSignaller(object):
+
+       def __init__(self, on_new_channel):
+               self._sessionBus = dbus.SessionBus()
+               self._on_user_new_channel = on_new_channel
+
+       def start(self):
+               self._sessionBus.add_signal_receiver(
+                       self._on_new_channel,
+                       "NewChannel",
+                       "org.freedesktop.Telepathy.Connection",
+                       None,
+                       None
+               )
+
+       def stop(self):
+               self._sessionBus.remove_signal_receiver(
+                       self._on_new_channel,
+                       "NewChannel",
+                       "org.freedesktop.Telepathy.Connection",
+                       None,
+                       None
+               )
+
+       @misc.log_exception(_moduleLogger)
+       def _on_new_channel(
+               self, channelObjectPath, channelType, handleType, handle, supressHandler
+       ):
+               connObjectPath = channel_path_to_conn_path(channelObjectPath)
+               serviceName = path_to_service_name(channelObjectPath)
+               try:
+                       self._on_user_new_channel(
+                               self._sessionBus, serviceName, connObjectPath, channelObjectPath, channelType
+                       )
+               except Exception:
+                       _moduleLogger.exception("Blocking exception from being passed up")
+
+
+class EnableSystemContactIntegration(object):
+
+       ACCOUNT_MGR_NAME = "org.freedesktop.Telepathy.AccountManager"
+       ACCOUNT_MGR_PATH = "/org/freedesktop/Telepathy/AccountManager"
+       ACCOUNT_MGR_IFACE_QUERY = "com.nokia.AccountManager.Interface.Query"
+       ACCOUNT_IFACE_COMPAT = "com.nokia.Account.Interface.Compat"
+       ACCOUNT_IFACE_COMPAT_PROFILE = "com.nokia.Account.Interface.Compat.Profile"
+       DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties'
+
+       def __init__(self, profileName):
+               self._bus = dbus.SessionBus()
+               self._profileName = profileName
+
+       def start(self):
+               self._accountManager = self._bus.get_object(
+                       self.ACCOUNT_MGR_NAME,
+                       self.ACCOUNT_MGR_PATH,
+               )
+               self._accountManagerQuery = dbus.Interface(
+                       self._accountManager,
+                       dbus_interface=self.ACCOUNT_MGR_IFACE_QUERY,
+               )
+
+               self._accountManagerQuery.FindAccounts(
+                       {
+                               self.ACCOUNT_IFACE_COMPAT_PROFILE: self._profileName,
+                       },
+                       reply_handler = self._on_found_accounts_reply,
+                       error_handler = self._on_error,
+               )
+
+       @misc.log_exception(_moduleLogger)
+       def _on_found_accounts_reply(self, accountObjectPaths):
+               for accountObjectPath in accountObjectPaths:
+                       print accountObjectPath
+                       account = self._bus.get_object(
+                               self.ACCOUNT_MGR_NAME,
+                               accountObjectPath,
+                       )
+                       accountProperties = dbus.Interface(
+                               account,
+                               self.DBUS_PROPERTIES,
+                       )
+                       accountProperties.Set(
+                               self.ACCOUNT_IFACE_COMPAT,
+                               "SecondaryVCardFields",
+                               ["TEL"],
+                               reply_handler = self._on_field_set,
+                               error_handler = self._on_error,
+                       )
+
+       @misc.log_exception(_moduleLogger)
+       def _on_field_set(self):
+               _moduleLogger.info("SecondaryVCardFields Set")
+
+       @misc.log_exception(_moduleLogger)
+       def _on_error(self, error):
+               _moduleLogger.error("%r" % (error, ))
+
+
+def channel_path_to_conn_path(channelObjectPath):
+       """
+       >>> channel_path_to_conn_path("/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME/Channel1")
+       '/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME'
+       """
+       return channelObjectPath.rsplit("/", 1)[0]
+
+
+def path_to_service_name(path):
+       """
+       >>> path_to_service_name("/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME/Channel1")
+       'org.freedesktop.Telepathy.ConnectionManager.theonering.gv.USERNAME'
+       """
+       return ".".join(path[1:].split("/")[0:7])
+
+
+def cm_from_path(path):
+       """
+       >>> cm_from_path("/org/freedesktop/Telepathy/ConnectionManager/theonering/gv/USERNAME/Channel1")
+       'theonering'
+       """
+       return path[1:].split("/")[4]
diff --git a/src/windows/__init__.py b/src/windows/__init__.py
new file mode 100644 (file)
index 0000000..4acbe57
--- /dev/null
@@ -0,0 +1,6 @@
+import _base
+import source
+import radio
+import conferences
+import magazines
+import scriptures
diff --git a/src/windows/_base.py b/src/windows/_base.py
new file mode 100644 (file)
index 0000000..1e7a79f
--- /dev/null
@@ -0,0 +1,579 @@
+from __future__ import with_statement
+
+import ConfigParser
+import logging
+
+import gobject
+import gtk
+
+import constants
+import hildonize
+import util.misc as misc_utils
+import util.go_utils as go_utils
+
+import stream_index
+import banners
+import presenter
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class BasicWindow(gobject.GObject, go_utils.AutoSignal):
+
+       __gsignals__ = {
+               'quit' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (),
+               ),
+               'home' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (),
+               ),
+               'jump-to' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_PYOBJECT, ),
+               ),
+               'rotate' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_BOOLEAN, ),
+               ),
+               'fullscreen' : (
+                       gobject.SIGNAL_RUN_LAST,
+                       gobject.TYPE_NONE,
+                       (gobject.TYPE_BOOLEAN, ),
+               ),
+       }
+
+       def __init__(self, app, player, store):
+               gobject.GObject.__init__(self)
+               self._isDestroyed = False
+
+               self._app = app
+               self._player = player
+               self._store = store
+
+               self._clipboard = gtk.clipboard_get()
+               self._windowInFullscreen = False
+
+               self._errorBanner = banners.StackingBanner()
+
+               self._layout = gtk.VBox()
+
+               self._window = gtk.Window()
+               self._window.add(self._layout)
+               self._window = hildonize.hildonize_window(self._app, self._window)
+               go_utils.AutoSignal.__init__(self, self.window)
+
+               self._window.set_icon(self._store.get_pixbuf_from_store(self._store.STORE_LOOKUP["icon"]))
+               self._window.connect("key-press-event", self._on_key_press)
+               self._window.connect("window-state-event", self._on_window_state_change)
+               self._window.connect("destroy", self._on_destroy)
+
+               if hildonize.GTK_MENU_USED:
+                       aboutMenuItem = gtk.MenuItem("About")
+                       aboutMenuItem.connect("activate", self._on_about)
+
+                       helpMenu = gtk.Menu()
+                       helpMenu.append(aboutMenuItem)
+
+                       helpMenuItem = gtk.MenuItem("Help")
+                       helpMenuItem.set_submenu(helpMenu)
+
+                       menuBar = gtk.MenuBar()
+                       menuBar.append(helpMenuItem)
+
+                       self._layout.pack_start(menuBar, False, False)
+               else:
+                       aboutMenuItem = gtk.Button("About")
+                       aboutMenuItem.connect("clicked", self._on_about)
+
+                       appMenu = hildonize.hildon.AppMenu()
+                       appMenu.append(aboutMenuItem)
+                       appMenu.show_all()
+                       self._window.set_app_menu(appMenu)
+
+               self._layout.pack_start(self._errorBanner.toplevel, False, True)
+
+       @property
+       def window(self):
+               return self._window
+
+       def show(self):
+               hildonize.window_to_portrait(self._window)
+               self._window.show_all()
+
+       def save_settings(self, config, sectionName):
+               config.add_section(sectionName)
+               config.set(sectionName, "fullscreen", str(self._windowInFullscreen))
+
+       def load_settings(self, config, sectionName):
+               try:
+                       windowInFullscreen = config.getboolean(sectionName, "fullscreen")
+               except ConfigParser.NoSectionError, e:
+                       _moduleLogger.info(
+                               "Settings file %s is missing section %s" % (
+                                       constants._user_settings_,
+                                       e.section,
+                               )
+                       )
+                       windowInFullscreen = self._windowInFullscreen
+
+               if windowInFullscreen:
+                       self._window.fullscreen()
+               else:
+                       self._window.unfullscreen()
+
+       def jump_to(self, node):
+               raise NotImplementedError("On %s" % self)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_about(self, *args):
+               show_about()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_destroy(self, *args):
+               self._isDestroyed = True
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_window_state_change(self, widget, event, *args):
+               oldIsFull = self._windowInFullscreen
+               if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
+                       self._windowInFullscreen = True
+               else:
+                       self._windowInFullscreen = False
+               if oldIsFull != self._windowInFullscreen:
+                       _moduleLogger.info("%r Emit fullscreen %s" % (self, self._windowInFullscreen))
+                       self.emit("fullscreen", self._windowInFullscreen)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_key_press(self, widget, event, *args):
+               RETURN_TYPES = (gtk.keysyms.Return, gtk.keysyms.ISO_Enter, gtk.keysyms.KP_Enter)
+               isCtrl = bool(event.get_state() & gtk.gdk.CONTROL_MASK)
+               if (
+                       event.keyval == gtk.keysyms.F6 or
+                       event.keyval in RETURN_TYPES and isCtrl
+               ):
+                       # The "Full screen" hardware key has been pressed
+                       if self._windowInFullscreen:
+                               self._window.unfullscreen ()
+                       else:
+                               self._window.fullscreen ()
+                       return True
+               elif (
+                       event.keyval in (gtk.keysyms.w, ) and
+                       event.get_state() & gtk.gdk.CONTROL_MASK
+               ):
+                       self._window.destroy()
+               elif (
+                       event.keyval in (gtk.keysyms.q, ) and
+                       event.get_state() & gtk.gdk.CONTROL_MASK
+               ):
+                       self.emit("quit")
+                       self._window.destroy()
+               elif event.keyval == gtk.keysyms.l and event.get_state() & gtk.gdk.CONTROL_MASK:
+                       with open(constants._user_logpath_, "r") as f:
+                               logLines = f.xreadlines()
+                               log = "".join(logLines)
+                               self._clipboard.set_text(str(log))
+                       return True
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_home(self, *args):
+               self.emit("home")
+               self._window.destroy()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_child_fullscreen(self, source, isFull):
+               if isFull:
+                       _moduleLogger.info("Full screen %r to mirror child %r" % (self, source))
+                       self._window.fullscreen()
+               else:
+                       _moduleLogger.info("Unfull screen %r to mirror child %r" % (self, source))
+                       self._window.unfullscreen()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_jump(self, source, node):
+               raise NotImplementedError("On %s" % self)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_quit(self, *args):
+               self.emit("quit")
+               self._window.destroy()
+
+
+class ListWindow(BasicWindow):
+
+       def __init__(self, app, player, store, node):
+               BasicWindow.__init__(self, app, player, store)
+               self._node = node
+
+               self.connect_auto(self._player, "title-change", self._on_player_title_change)
+
+               self._loadingBanner = banners.GenericBanner()
+
+               modelTypes, columns = zip(*self._get_columns())
+
+               self._model = gtk.ListStore(*modelTypes)
+
+               self._treeView = gtk.TreeView()
+               self._treeView.connect("row-activated", self._on_row_activated)
+               self._treeView.set_property("fixed-height-mode", True)
+               self._treeView.set_headers_visible(False)
+               self._treeView.set_model(self._model)
+               for column in columns:
+                       if column is not None:
+                               self._treeView.append_column(column)
+
+               self._viewport = gtk.Viewport()
+               self._viewport.add(self._treeView)
+
+               self._treeScroller = gtk.ScrolledWindow()
+               self._treeScroller.add(self._viewport)
+               self._treeScroller.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
+               self._treeScroller = hildonize.hildonize_scrollwindow(self._treeScroller)
+
+               self._separator = gtk.HSeparator()
+               self._presenter = presenter.NavControl(self._player, self._store)
+               self.connect_auto(self._presenter, "home", self._on_home)
+               self.connect_auto(self._presenter, "jump-to", self._on_jump)
+
+               self._contentLayout = gtk.VBox(False)
+               self._contentLayout.pack_start(self._treeScroller, True, True)
+               self._contentLayout.pack_start(self._separator, False, True)
+               self._contentLayout.pack_start(self._presenter.toplevel, False, True)
+
+               self._layout.pack_start(self._loadingBanner.toplevel, False, False)
+               self._layout.pack_start(self._contentLayout, True, True)
+
+       def show(self):
+               BasicWindow.show(self)
+
+               self._errorBanner.toplevel.hide()
+               self._loadingBanner.toplevel.hide()
+
+               self._refresh()
+               self._presenter.refresh()
+
+       @classmethod
+       def _get_columns(cls):
+               raise NotImplementedError("")
+
+       def _get_current_row(self):
+               if self._player.node is None:
+                       return -1
+               ancestors, current, descendants = stream_index.common_paths(self._player.node, self._node)
+               if not descendants:
+                       return -1
+               activeChild = descendants[0]
+               for i, row in enumerate(self._model):
+                       if activeChild is row[0]:
+                               return i
+               else:
+                       return -1
+
+       def jump_to(self, node):
+               ancestors, current, descendants = stream_index.common_paths(node, self._node)
+               if current is None:
+                       raise RuntimeError("Cannot jump to node %s" % node)
+               if not descendants:
+                       _moduleLogger.info("Current node is the target")
+                       return
+               child = descendants[0]
+               window = self._window_from_node(child)
+               window.jump_to(node)
+
+       def _window_from_node(self, node):
+               raise NotImplementedError("")
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_row_activated(self, view, path, column):
+               itr = self._model.get_iter(path)
+               node = self._model.get_value(itr, 0)
+               self._window_from_node(node)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_title_change(self, player, node):
+               assert not self._isDestroyed
+               self._select_row()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_jump(self, source, node):
+               ancestors, current, descendants = stream_index.common_paths(node, self._node)
+               if current is None:
+                       _moduleLogger.info("%s is not the target, moving up" % self._node)
+                       self.emit("jump-to", node)
+                       self._window.destroy()
+                       return
+               if not descendants:
+                       _moduleLogger.info("Current node is the target")
+                       return
+               child = descendants[0]
+               window = self._window_from_node(child)
+               window.jump_to(node)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_delay_scroll(self, *args):
+               self._scroll_to_row()
+
+       def _show_loading(self):
+               animationPath = self._store.STORE_LOOKUP["loading"]
+               animation = self._store.get_pixbuf_animation_from_store(animationPath)
+               self._loadingBanner.show(animation, "Loading...")
+
+       def _hide_loading(self):
+               self._loadingBanner.hide()
+
+       def _refresh(self):
+               self._show_loading()
+               self._model.clear()
+
+       def _select_row(self):
+               rowIndex = self._get_current_row()
+               if rowIndex < 0:
+                       return
+               path = (rowIndex, )
+               self._treeView.get_selection().select_path(path)
+
+       def _scroll_to_row(self):
+               rowIndex = self._get_current_row()
+               if rowIndex < 0:
+                       return
+
+               path = (rowIndex, )
+               self._treeView.scroll_to_cell(path)
+
+               treeViewHeight = self._treeView.get_allocation().height
+               viewportHeight = self._viewport.get_allocation().height
+
+               viewsPerPort = treeViewHeight / float(viewportHeight)
+               maxRows = len(self._model)
+               percentThrough = rowIndex / float(maxRows)
+               dxByIndex = int(viewsPerPort * percentThrough * viewportHeight)
+
+               dxMax = max(treeViewHeight - viewportHeight, 0)
+
+               dx = min(dxByIndex, dxMax)
+               adjustment = self._treeScroller.get_vadjustment()
+               adjustment.value = dx
+
+
+class PresenterWindow(BasicWindow):
+
+       def __init__(self, app, player, store, node):
+               BasicWindow.__init__(self, app, player, store)
+               self._node = node
+               self._playerNode = self._player.node
+               self._nextSearch = None
+               self._updateSeek = None
+
+               self.connect_auto(self._player, "state-change", self._on_player_state_change)
+               self.connect_auto(self._player, "title-change", self._on_player_title_change)
+               self.connect_auto(self._player, "error", self._on_player_error)
+
+               self._loadingBanner = banners.GenericBanner()
+
+               self._presenter = presenter.StreamPresenter(self._store)
+               self._presenter.set_context(
+                       self._get_background(),
+                       self._node.title,
+                       self._node.subtitle,
+               )
+               self._presenterNavigation = presenter.NavigationBox()
+               self._presenterNavigation.toplevel.add(self._presenter.toplevel)
+               self.connect_auto(self._presenterNavigation, "action", self._on_nav_action)
+               self.connect_auto(self._presenterNavigation, "navigating", self._on_navigating)
+
+               self._seekbar = hildonize.create_seekbar()
+               self._seekbar.connect("change-value", self._on_user_seek)
+
+               self._layout.pack_start(self._loadingBanner.toplevel, False, False)
+               self._layout.pack_start(self._presenterNavigation.toplevel, True, True)
+               self._layout.pack_start(self._seekbar, False, False)
+
+               self._window.set_title(self._node.get_parent().title)
+
+       def _get_background(self):
+               raise NotImplementedError()
+
+       def show(self):
+               BasicWindow.show(self)
+               self._window.show_all()
+               self._errorBanner.toplevel.hide()
+               self._loadingBanner.toplevel.hide()
+               self._set_context(self._player.state)
+               self._seekbar.hide()
+
+       def jump_to(self, node):
+               assert self._node is node
+
+       @property
+       def _active(self):
+               return self._playerNode is self._node
+
+       def _show_loading(self):
+               animationPath = self._store.STORE_LOOKUP["loading"]
+               animation = self._store.get_pixbuf_animation_from_store(animationPath)
+               self._loadingBanner.show(animation, "Loading...")
+
+       def _hide_loading(self):
+               self._loadingBanner.hide()
+
+       def _set_context(self, state):
+               if state == self._player.STATE_PLAY:
+                       if self._active:
+                               self._presenter.set_state(self._store.STORE_LOOKUP["pause"])
+                       else:
+                               self._presenter.set_state(self._store.STORE_LOOKUP["play"])
+               elif state == self._player.STATE_PAUSE:
+                       self._presenter.set_state(self._store.STORE_LOOKUP["play"])
+               elif state == self._player.STATE_STOP:
+                       self._presenter.set_state(self._store.STORE_LOOKUP["play"])
+               else:
+                       _moduleLogger.info("Unhandled player state %s" % state)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_user_seek(self, widget, scroll, value):
+               self._player.seek(value / 100.0)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_update_seek(self):
+               if self._isDestroyed:
+                       return False
+               self._seekbar.set_value(self._player.percent_elapsed * 100)
+               return True
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_state_change(self, player, newState):
+               assert not self._isDestroyed
+               if self._active and self._player.state == self._player.STATE_PLAY:
+                       self._seekbar.show()
+                       assert self._updateSeek is None
+                       self._updateSeek = go_utils.Timeout(self._on_player_update_seek, once=False)
+                       self._updateSeek.start(seconds=1)
+               else:
+                       self._seekbar.hide()
+                       if self._updateSeek is not None:
+                               self._updateSeek.cancel()
+                               self._updateSeek = None
+
+               if not self._presenterNavigation.is_active():
+                       self._set_context(newState)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_title_change(self, player, node):
+               assert not self._isDestroyed
+               if not self._active or node in [None, self._node]:
+                       self._playerNode = node
+                       return
+               self._playerNode = node
+               self.emit("jump-to", node)
+               self._window.destroy()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_error(self, player, err, debug):
+               assert not self._isDestroyed
+               _moduleLogger.error("%r - %r" % (err, debug))
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_navigating(self, widget, navState):
+               if navState == "clicking":
+                       if self._player.state == self._player.STATE_PLAY:
+                               if self._active:
+                                       imageName = "pause_pressed"
+                               else:
+                                       imageName = "play_pressed"
+                       elif self._player.state == self._player.STATE_PAUSE:
+                               imageName = "play_pressed"
+                       elif self._player.state == self._player.STATE_STOP:
+                               imageName = "play_pressed"
+                       else:
+                               _moduleLogger.info("Unhandled player state %s" % self._player.state)
+               elif navState == "down":
+                       imageName = "home"
+               elif navState == "up":
+                       if self._player.state == self._player.STATE_PLAY:
+                               if self._active:
+                                       imageName = "pause"
+                               else:
+                                       imageName = "play"
+                       elif self._player.state == self._player.STATE_PAUSE:
+                               imageName = "play"
+                       elif self._player.state == self._player.STATE_STOP:
+                               imageName = "play"
+                       else:
+                               _moduleLogger.info("Unhandled player state %s" % self._player.state)
+               elif navState == "left":
+                       imageName = "next"
+               elif navState == "right":
+                       imageName = "prev"
+
+               self._presenter.set_state(self._store.STORE_LOOKUP[imageName])
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_nav_action(self, widget, navState):
+               self._set_context(self._player.state)
+
+               if navState == "clicking":
+                       if self._player.state == self._player.STATE_PLAY:
+                               if self._active:
+                                       self._player.pause()
+                               else:
+                                       self._player.set_piece_by_node(self._node)
+                                       self._player.play()
+                       elif self._player.state == self._player.STATE_PAUSE:
+                               self._player.play()
+                       elif self._player.state == self._player.STATE_STOP:
+                               self._player.set_piece_by_node(self._node)
+                               self._player.play()
+                       else:
+                               _moduleLogger.info("Unhandled player state %s" % self._player.state)
+               elif navState == "down":
+                       self.emit("home")
+                       self._window.destroy()
+               elif navState == "up":
+                       pass
+               elif navState == "left":
+                       if self._active:
+                               self._player.next()
+                       else:
+                               assert self._nextSearch is None
+                               self._nextSearch = stream_index.AsyncWalker(stream_index.get_next)
+                               self._nextSearch.start(self._node, self._on_next_node, self._on_node_search_error)
+               elif navState == "right":
+                       if self._active:
+                               self._player.back()
+                       else:
+                               assert self._nextSearch is None
+                               self._nextSearch = stream_index.AsyncWalker(stream_index.get_previous)
+                               self._nextSearch.start(self._node, self._on_next_node, self._on_node_search_error)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_next_node(self, node):
+               self._nextSearch = None
+               self.emit("jump-to", node)
+               self._window.destroy()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_node_search_error(self, e):
+               self._nextSearch = None
+               self._errorBanner.push_message(str(e))
+
+
+def show_about():
+       # @todo Turn this into a full-fledge window to keep it rotated
+       dialog = gtk.AboutDialog()
+       dialog.set_position(gtk.WIN_POS_CENTER)
+       dialog.set_name(constants.__pretty_app_name__)
+       dialog.set_version(constants.__version__)
+       dialog.set_copyright("(c) 2010 Intellectual Reserve, Inc. All rights reserved.")
+       dialog.set_website("http://www.lds.org")
+       comments = "Mormon Radio and Audiobook Player"
+       dialog.set_comments(comments)
+       dialog.set_authors(["The Church of Jesus Christ of Latter-day Saints"])
+       dialog.run()
+       dialog.destroy()
diff --git a/src/windows/conferences.py b/src/windows/conferences.py
new file mode 100644 (file)
index 0000000..1b31755
--- /dev/null
@@ -0,0 +1,228 @@
+import logging
+
+import gobject
+import gtk
+
+import hildonize
+import util.go_utils as go_utils
+import util.misc as misc_utils
+
+import windows
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class ConferencesWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               textrenderer = gtk.CellRendererText()
+               textrenderer.set_property("scale", 0.75)
+               column = gtk.TreeViewColumn("Date")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.set_property("fixed-width", 96)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 1)
+               yield gobject.TYPE_STRING, column
+
+               textrenderer = gtk.CellRendererText()
+               hildonize.set_cell_thumb_selectable(textrenderer)
+               column = gtk.TreeViewColumn("Conference")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 2)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_conferences,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_conferences(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       row = programNode, program["title"], program["full_title"]
+                       self._model.append(row)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               sessionsWindow = ConferenceSessionsWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       sessionsWindow.window.set_modal(True)
+                       sessionsWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       sessionsWindow.window.fullscreen()
+               else:
+                       sessionsWindow.window.unfullscreen()
+               sessionsWindow.connect_auto(sessionsWindow, "quit", self._on_quit)
+               sessionsWindow.connect_auto(sessionsWindow, "home", self._on_home)
+               sessionsWindow.connect_auto(sessionsWindow, "jump-to", self._on_jump)
+               sessionsWindow.connect_auto(sessionsWindow, "fullscreen", self._on_child_fullscreen)
+               sessionsWindow.show()
+               return sessionsWindow
+
+
+gobject.type_register(ConferencesWindow)
+
+
+class ConferenceSessionsWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               textrenderer = gtk.CellRendererText()
+               hildonize.set_cell_thumb_selectable(textrenderer)
+               column = gtk.TreeViewColumn("Session")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 1)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_conference_sessions,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_conference_sessions(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       row = programNode, program["title"]
+                       self._model.append(row)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               sessionsWindow = ConferenceTalksWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       sessionsWindow.window.set_modal(True)
+                       sessionsWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       sessionsWindow.window.fullscreen()
+               else:
+                       sessionsWindow.window.unfullscreen()
+               sessionsWindow.connect_auto(sessionsWindow, "quit", self._on_quit)
+               sessionsWindow.connect_auto(sessionsWindow, "home", self._on_home)
+               sessionsWindow.connect_auto(sessionsWindow, "jump-to", self._on_jump)
+               sessionsWindow.connect_auto(sessionsWindow, "fullscreen", self._on_child_fullscreen)
+               sessionsWindow.show()
+               return sessionsWindow
+
+
+gobject.type_register(ConferenceSessionsWindow)
+
+
+class ConferenceTalksWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               textrenderer = gtk.CellRendererText()
+               column = gtk.TreeViewColumn("Talk")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "markup", 1)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_conference_talks,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_conference_talks(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       row = programNode, "%s\n<small>%s</small>" % (programNode.title, programNode.subtitle)
+                       self._model.append(row)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               sessionsWindow = ConferenceTalkWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       sessionsWindow.window.set_modal(True)
+                       sessionsWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       sessionsWindow.window.fullscreen()
+               else:
+                       sessionsWindow.window.unfullscreen()
+               sessionsWindow.connect_auto(sessionsWindow, "quit", self._on_quit)
+               sessionsWindow.connect_auto(sessionsWindow, "home", self._on_home)
+               sessionsWindow.connect_auto(sessionsWindow, "jump-to", self._on_jump)
+               sessionsWindow.connect_auto(sessionsWindow, "fullscreen", self._on_child_fullscreen)
+               sessionsWindow.show()
+               return sessionsWindow
+
+
+gobject.type_register(ConferenceTalksWindow)
+
+
+class ConferenceTalkWindow(windows._base.PresenterWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.PresenterWindow.__init__(self, app, player, store, node)
+
+       def _get_background(self):
+               return self._store.STORE_LOOKUP["conference_background"]
+
+
+gobject.type_register(ConferenceTalkWindow)
diff --git a/src/windows/magazines.py b/src/windows/magazines.py
new file mode 100644 (file)
index 0000000..7d74ab5
--- /dev/null
@@ -0,0 +1,282 @@
+import logging
+
+import gobject
+import gtk
+
+import hildonize
+import util.go_utils as go_utils
+import util.misc as misc_utils
+
+import windows
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class MagazinesWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               pixrenderer = gtk.CellRendererPixbuf()
+               column = gtk.TreeViewColumn("Covers")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.set_property("fixed-width", 96)
+               column.pack_start(pixrenderer, expand=True)
+               column.add_attribute(pixrenderer, "pixbuf", 1)
+               yield gobject.TYPE_OBJECT, column
+
+               textrenderer = gtk.CellRendererText()
+               hildonize.set_cell_thumb_selectable(textrenderer)
+               column = gtk.TreeViewColumn("Magazine")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 2)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_magazines,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_magazines(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for i, programNode in enumerate(programs):
+                       program = programNode.get_properties()
+                       img = self._store.get_pixbuf_from_store(self._store.STORE_LOOKUP["nomagazineimage"])
+                       row = programNode, img, program["title"]
+                       self._model.append(row)
+
+                       programNode.get_children(self._create_on_issues(i), self._on_error)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       def _create_on_issues(self, row):
+               return lambda issues: self._on_issues(row, issues)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_issues(self, row, issues):
+               for issue in issues:
+                       self._store.get_pixbuf_from_url(
+                               issue.get_properties()["pictureURL"],
+                               lambda pix: self._on_image(row, pix),
+                               self._on_error,
+                       )
+                       break
+               else:
+                       _moduleLogger.info("No issues for magazine %s" % row)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_image(self, row, pix):
+               treeiter = self._model.iter_nth_child(None, row)
+               self._model.set_value(treeiter, 1, pix)
+               treeiter = self._model.iter_nth_child(None, row)
+               self._model.row_changed((row, ), treeiter)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               issuesWindow = MagazineIssuesWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       issuesWindow.window.set_modal(True)
+                       issuesWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       issuesWindow.window.fullscreen()
+               else:
+                       issuesWindow.window.unfullscreen()
+               issuesWindow.connect_auto(issuesWindow, "quit", self._on_quit)
+               issuesWindow.connect_auto(issuesWindow, "home", self._on_home)
+               issuesWindow.connect_auto(issuesWindow, "jump-to", self._on_jump)
+               issuesWindow.connect_auto(issuesWindow, "fullscreen", self._on_child_fullscreen)
+               issuesWindow.show()
+               return issuesWindow
+
+
+gobject.type_register(MagazinesWindow)
+
+
+class MagazineIssuesWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               pixrenderer = gtk.CellRendererPixbuf()
+               column = gtk.TreeViewColumn("Covers")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.set_property("fixed-width", 96)
+               column.pack_start(pixrenderer, expand=True)
+               column.add_attribute(pixrenderer, "pixbuf", 1)
+               yield gobject.TYPE_OBJECT, column
+
+               textrenderer = gtk.CellRendererText()
+               hildonize.set_cell_thumb_selectable(textrenderer)
+               column = gtk.TreeViewColumn("Issue")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 2)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_magazine_issues,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_magazine_issues(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       img = self._store.get_pixbuf_from_store(self._store.STORE_LOOKUP["nomagazineimage"])
+                       row = programNode, img, program["title"]
+                       self._model.append(row)
+
+                       self._store.get_pixbuf_from_url(
+                               program["pictureURL"],
+                               self._create_on_image(programNode),
+                               self._on_error,
+                       )
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _create_on_image(self, programNode):
+               return lambda pix: self._on_image(programNode, pix)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_image(self, childNode, pix):
+               for i, row in enumerate(self._model):
+                       if row[0] is childNode:
+                               break
+               else:
+                       raise RuntimeError("Could not find %r" % childNode)
+               treeiter = self._model.iter_nth_child(None, i)
+               self._model.set_value(treeiter, 1, pix)
+               treeiter = self._model.iter_nth_child(None, i)
+               self._model.row_changed((i, ), treeiter)
+
+       def _window_from_node(self, node):
+               issuesWindow = MagazineArticlesWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       issuesWindow.window.set_modal(True)
+                       issuesWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       issuesWindow.window.fullscreen()
+               else:
+                       issuesWindow.window.unfullscreen()
+               issuesWindow.connect_auto(issuesWindow, "quit", self._on_quit)
+               issuesWindow.connect_auto(issuesWindow, "home", self._on_home)
+               issuesWindow.connect_auto(issuesWindow, "jump-to", self._on_jump)
+               issuesWindow.connect_auto(issuesWindow, "fullscreen", self._on_child_fullscreen)
+               issuesWindow.show()
+               return issuesWindow
+
+
+gobject.type_register(MagazineIssuesWindow)
+
+
+class MagazineArticlesWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               textrenderer = gtk.CellRendererText()
+               column = gtk.TreeViewColumn("Article")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "markup", 1)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_magazine_articles,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_magazine_articles(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       row = programNode, "%s\n<small>%s</small>" % (programNode.title, programNode.subtitle)
+                       self._model.append(row)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               issuesWindow = MagazineArticleWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       issuesWindow.window.set_modal(True)
+                       issuesWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       issuesWindow.window.fullscreen()
+               else:
+                       issuesWindow.window.unfullscreen()
+               issuesWindow.connect_auto(issuesWindow, "quit", self._on_quit)
+               issuesWindow.connect_auto(issuesWindow, "home", self._on_home)
+               issuesWindow.connect_auto(issuesWindow, "jump-to", self._on_jump)
+               issuesWindow.connect_auto(issuesWindow, "fullscreen", self._on_child_fullscreen)
+               issuesWindow.show()
+               return issuesWindow
+
+
+gobject.type_register(MagazineArticlesWindow)
+
+
+class MagazineArticleWindow(windows._base.PresenterWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.PresenterWindow.__init__(self, app, player, store, node)
+
+       def _get_background(self):
+               return self._store.STORE_LOOKUP["magazine_background"]
+
+
+gobject.type_register(MagazineArticleWindow)
diff --git a/src/windows/radio.py b/src/windows/radio.py
new file mode 100644 (file)
index 0000000..981aeee
--- /dev/null
@@ -0,0 +1,329 @@
+import datetime
+import logging
+
+import gobject
+import gtk
+
+import hildonize
+import util.misc as misc_utils
+import util.time_utils as time_utils
+import util.go_utils as go_utils
+import banners
+import presenter
+
+import windows
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class RadioWindow(windows._base.BasicWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.BasicWindow.__init__(self, app, player, store)
+               self._node = node
+               self._childNode = None
+
+               self.connect_auto(self._player, "state-change", self._on_player_state_change)
+               self.connect_auto(self._player, "title-change", self._on_player_title_change)
+
+               self._loadingBanner = banners.GenericBanner()
+
+               headerPath = self._store.STORE_LOOKUP["radio_header"]
+               self._header = self._store.get_image_from_store(headerPath)
+               self._headerNavigation = presenter.NavigationBox()
+               self._headerNavigation.toplevel.add(self._header)
+               self.connect_auto(self._headerNavigation, "action", self._on_nav_action)
+               self.connect_auto(self._headerNavigation, "navigating", self._on_navigating)
+
+               self._programmingModel = gtk.ListStore(
+                       gobject.TYPE_STRING,
+                       gobject.TYPE_STRING,
+               )
+
+               textrenderer = gtk.CellRendererText()
+               timeColumn = gtk.TreeViewColumn("Time")
+               textrenderer.set_property("scale", 0.75)
+               timeColumn.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               timeColumn.set_property("fixed-width", 80)
+               timeColumn.pack_start(textrenderer, expand=True)
+               timeColumn.add_attribute(textrenderer, "text", 0)
+
+               textrenderer = gtk.CellRendererText()
+               titleColumn = gtk.TreeViewColumn("Program")
+               titleColumn.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               titleColumn.pack_start(textrenderer, expand=True)
+               titleColumn.add_attribute(textrenderer, "text", 1)
+
+               self._treeView = gtk.TreeView()
+               self._treeView.set_property("fixed-height-mode", True)
+               self._treeView.set_headers_visible(False)
+               self._treeView.set_model(self._programmingModel)
+               self._treeView.append_column(timeColumn)
+               self._treeView.append_column(titleColumn)
+               self._treeView.get_selection().connect("changed", self._on_row_changed)
+
+               self._viewport = gtk.Viewport()
+               self._viewport.add(self._treeView)
+
+               self._treeScroller = gtk.ScrolledWindow()
+               self._treeScroller.add(self._viewport)
+               self._treeScroller.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
+               self._treeScroller = hildonize.hildonize_scrollwindow(self._treeScroller)
+
+               self._presenter = presenter.StreamMiniPresenter(self._store)
+               self._presenterNavigation = presenter.NavigationBox()
+               self._presenterNavigation.toplevel.add(self._presenter.toplevel)
+               self.connect_auto(self._presenterNavigation, "action", self._on_nav_action)
+               self.connect_auto(self._presenterNavigation, "navigating", self._on_navigating)
+
+               self._radioLayout = gtk.VBox(False)
+               self._radioLayout.pack_start(self._headerNavigation.toplevel, False, False)
+               self._radioLayout.pack_start(self._treeScroller, True, True)
+               self._radioLayout.pack_start(self._presenterNavigation.toplevel, False, True)
+
+               self._layout.pack_start(self._loadingBanner.toplevel, False, False)
+               self._layout.pack_start(self._radioLayout, True, True)
+
+               self._dateShown = datetime.datetime.now(tz=time_utils.Mountain)
+               self._currentTime = self._dateShown
+               self._update_title()
+
+               self._continualUpdate = go_utils.Timeout(self._on_continual_update, once = False)
+               self._continualUpdate.start(seconds=60)
+
+       def show(self):
+               windows._base.BasicWindow.show(self)
+
+               self._errorBanner.toplevel.hide()
+               self._loadingBanner.toplevel.hide()
+
+               self._refresh()
+
+       def jump_to(self, node):
+               _moduleLogger.info("Only 1 channel, nothing to jump to")
+
+       def _update_time(self, newTime):
+               oldTime = self._dateShown
+               self._dateShown = newTime
+               if newTime.date() == oldTime.date():
+                       self._select_row()
+               else:
+                       self._update_title()
+                       self._refresh()
+
+       def _update_title(self):
+               self._window.set_title("%s - %s" % (self._node.title, self._dateShown.strftime("%m/%d")))
+
+       @property
+       def _active(self):
+               return self._player.node is self._childNode
+
+       def _set_context(self, state):
+               if state == self._player.STATE_PLAY:
+                       if self._active:
+                               self._presenter.set_state(self._store.STORE_LOOKUP["pause"])
+                       else:
+                               self._presenter.set_state(self._store.STORE_LOOKUP["play"])
+               elif state == self._player.STATE_PAUSE:
+                       self._presenter.set_state(self._store.STORE_LOOKUP["play"])
+               elif state == self._player.STATE_STOP:
+                       self._presenter.set_state(self._store.STORE_LOOKUP["play"])
+               else:
+                       _moduleLogger.info("Unhandled player state %s" % state)
+                       self._presenter.set_state(self._store.STORE_LOOKUP["play"])
+
+       def _show_loading(self):
+               animationPath = self._store.STORE_LOOKUP["loading"]
+               animation = self._store.get_pixbuf_animation_from_store(animationPath)
+               self._loadingBanner.show(animation, "Loading...")
+
+       def _hide_loading(self):
+               self._loadingBanner.hide()
+
+       def _refresh(self):
+               self._show_loading()
+               self._programmingModel.clear()
+               self._node.get_children(
+                       self._on_channels,
+                       self._on_load_error,
+               )
+               self._set_context(self._player.state)
+
+       def _get_current_row(self):
+               nowTime = self._dateShown.strftime("%H:%M:%S")
+               i = 0
+               for i, row in enumerate(self._programmingModel):
+                       if nowTime < row[0]:
+                               if i == 0:
+                                       return 0
+                               else:
+                                       return i - 1
+               else:
+                       return i
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_continual_update(self, *args):
+               if self._isDestroyed:
+                       return False
+               newTime = datetime.datetime.now(tz=time_utils.Mountain)
+               oldTime = self._currentTime
+               shownTime = self._dateShown
+
+               self._currentTime = newTime
+               if shownTime.date() == oldTime.date():
+                       _moduleLogger.info("Today selected, updating selection")
+                       self._update_time(newTime)
+               return True
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_state_change(self, player, newState):
+               if self._headerNavigation.is_active() or self._presenterNavigation.is_active():
+                       return
+
+               self._set_context(newState)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_player_title_change(self, player, node):
+               if node is not self._childNode or node is None:
+                       _moduleLogger.info("Player title magically changed to %s" % player.title)
+                       return
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_navigating(self, widget, navState):
+               if navState == "clicking":
+                       if self._player.state == self._player.STATE_PLAY:
+                               if self._active:
+                                       imageName = "pause_pressed"
+                               else:
+                                       imageName = "play_pressed"
+                       elif self._player.state == self._player.STATE_PAUSE:
+                               imageName = "play_pressed"
+                       elif self._player.state == self._player.STATE_STOP:
+                               imageName = "play_pressed"
+                       else:
+                               imageName = "play_pressed"
+                               _moduleLogger.info("Unhandled player state %s" % self._player.state)
+               elif navState == "down":
+                       imageName = "home"
+               else:
+                       if self._player.state == self._player.STATE_PLAY:
+                               imageName = "pause"
+                       else:
+                               imageName = "play"
+
+               self._presenter.set_state(self._store.STORE_LOOKUP[imageName])
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_nav_action(self, widget, navState):
+               self._set_context(self._player.state)
+
+               if navState == "clicking":
+                       if self._player.state == self._player.STATE_PLAY:
+                               if self._active:
+                                       self._player.pause()
+                               else:
+                                       self._player.set_piece_by_node(self._childNode)
+                                       self._player.play()
+                       elif self._player.state == self._player.STATE_PAUSE:
+                               self._player.play()
+                       elif self._player.state == self._player.STATE_STOP:
+                               self._player.set_piece_by_node(self._childNode)
+                               self._player.play()
+                       else:
+                               _moduleLogger.info("Unhandled player state %s" % self._player.state)
+               elif navState == "down":
+                       self.window.destroy()
+               elif navState == "up":
+                       pass
+               elif navState == "left":
+                       self._update_time(self._dateShown + datetime.timedelta(days=1))
+               elif navState == "right":
+                       self._update_time(self._dateShown - datetime.timedelta(days=1))
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_channels(self, channels):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               channels = channels
+               if 1 < len(channels):
+                       _moduleLogger.warning("More channels now available!")
+               self._childNode = channels[0]
+               self._childNode.get_programming(
+                       self._dateShown,
+                       self._on_channel,
+                       self._on_load_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_channel(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for program in programs:
+                       row = program["time"], program["title"]
+                       self._programmingModel.append(row)
+
+               currentDate = self._currentTime
+               if currentDate.date() != self._dateShown.date():
+                       self._treeView.get_selection().set_mode(gtk.SELECTION_NONE)
+               else:
+                       self._treeView.get_selection().set_mode(gtk.SELECTION_SINGLE)
+                       self._select_row()
+                       go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_delay_scroll(self, *args):
+               self._scroll_to_row()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_load_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_row_changed(self, selection):
+               if len(self._programmingModel) == 0:
+                       return
+
+               # Undo the user's changing of the selection
+               self._select_row()
+
+       def _select_row(self):
+               rowIndex = self._get_current_row()
+               if rowIndex < 0:
+                       return
+               path = (rowIndex, )
+               if not self._treeView.get_selection().path_is_selected(path):
+                       self._treeView.get_selection().select_path(path)
+
+       def _scroll_to_row(self):
+               if self._isDestroyed:
+                       return
+               rowIndex = self._get_current_row()
+               if rowIndex < 0:
+                       return
+
+               path = (rowIndex, )
+               self._treeView.scroll_to_cell(path)
+
+               treeViewHeight = self._treeView.get_allocation().height
+               viewportHeight = self._viewport.get_allocation().height
+
+               viewsPerPort = treeViewHeight / float(viewportHeight)
+               maxRows = len(self._programmingModel)
+               percentThrough = rowIndex / float(maxRows)
+               dxByIndex = int(viewsPerPort * percentThrough * viewportHeight)
+
+               dxMax = max(treeViewHeight - viewportHeight, 0)
+
+               dx = min(dxByIndex, dxMax)
+               adjustment = self._treeScroller.get_vadjustment()
+               adjustment.value = dx
+
+
+gobject.type_register(RadioWindow)
diff --git a/src/windows/scriptures.py b/src/windows/scriptures.py
new file mode 100644 (file)
index 0000000..9ef47a1
--- /dev/null
@@ -0,0 +1,220 @@
+import logging
+
+import gobject
+import gtk
+
+import hildonize
+import util.go_utils as go_utils
+import util.misc as misc_utils
+
+import windows
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class ScripturesWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               textrenderer = gtk.CellRendererText()
+               hildonize.set_cell_thumb_selectable(textrenderer)
+               column = gtk.TreeViewColumn("Scripture")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 1)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_scriptures,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_scriptures(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       row = programNode, program["title"]
+                       self._model.append(row)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               booksWindow = ScriptureBooksWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       booksWindow.window.set_modal(True)
+                       booksWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       booksWindow.window.fullscreen()
+               else:
+                       booksWindow.window.unfullscreen()
+               booksWindow.connect_auto(booksWindow, "quit", self._on_quit)
+               booksWindow.connect_auto(booksWindow, "home", self._on_home)
+               booksWindow.connect_auto(booksWindow, "jump-to", self._on_jump)
+               booksWindow.connect_auto(booksWindow, "fullscreen", self._on_child_fullscreen)
+               booksWindow.show()
+               return booksWindow
+
+
+gobject.type_register(ScripturesWindow)
+
+
+class ScriptureBooksWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               textrenderer = gtk.CellRendererText()
+               hildonize.set_cell_thumb_selectable(textrenderer)
+               column = gtk.TreeViewColumn("Book")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 1)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_scripture_books,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_scripture_books(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       row = programNode, program["title"]
+                       self._model.append(row)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               booksWindow = ScriptureChaptersWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       booksWindow.window.set_modal(True)
+                       booksWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       booksWindow.window.fullscreen()
+               else:
+                       booksWindow.window.unfullscreen()
+               booksWindow.connect_auto(booksWindow, "quit", self._on_quit)
+               booksWindow.connect_auto(booksWindow, "home", self._on_home)
+               booksWindow.connect_auto(booksWindow, "jump-to", self._on_jump)
+               booksWindow.connect_auto(booksWindow, "fullscreen", self._on_child_fullscreen)
+               booksWindow.show()
+               return booksWindow
+
+
+gobject.type_register(ScriptureBooksWindow)
+
+
+class ScriptureChaptersWindow(windows._base.ListWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.ListWindow.__init__(self, app, player, store, node)
+               self._window.set_title(self._node.title)
+
+       @classmethod
+       def _get_columns(cls):
+               yield gobject.TYPE_PYOBJECT, None
+
+               textrenderer = gtk.CellRendererText()
+               hildonize.set_cell_thumb_selectable(textrenderer)
+               column = gtk.TreeViewColumn("Chapter")
+               column.set_property("sizing", gtk.TREE_VIEW_COLUMN_FIXED)
+               column.pack_start(textrenderer, expand=True)
+               column.add_attribute(textrenderer, "text", 1)
+               yield gobject.TYPE_STRING, column
+
+       def _refresh(self):
+               windows._base.ListWindow._refresh(self)
+               self._node.get_children(
+                       self._on_scripture_chapters,
+                       self._on_error,
+               )
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_scripture_chapters(self, programs):
+               if self._isDestroyed:
+                       _moduleLogger.info("Download complete but window destroyed")
+                       return
+
+               self._hide_loading()
+               for programNode in programs:
+                       program = programNode.get_properties()
+                       row = programNode, program["title"]
+                       self._model.append(row)
+
+               self._select_row()
+               go_utils.Async(self._on_delay_scroll).start()
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               booksWindow = ScriptureChapterWindow(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       booksWindow.window.set_modal(True)
+                       booksWindow.window.set_transient_for(self._window)
+               if self._windowInFullscreen:
+                       booksWindow.window.fullscreen()
+               else:
+                       booksWindow.window.unfullscreen()
+               booksWindow.connect_auto(booksWindow, "quit", self._on_quit)
+               booksWindow.connect_auto(booksWindow, "home", self._on_home)
+               booksWindow.connect_auto(booksWindow, "jump-to", self._on_jump)
+               booksWindow.connect_auto(booksWindow, "fullscreen", self._on_child_fullscreen)
+               booksWindow.show()
+               return booksWindow
+
+
+gobject.type_register(ScriptureChaptersWindow)
+
+
+class ScriptureChapterWindow(windows._base.PresenterWindow):
+
+       def __init__(self, app, player, store, node):
+               windows._base.PresenterWindow.__init__(self, app, player, store, node)
+
+       def _get_background(self):
+               return self._store.STORE_LOOKUP["scripture_background"]
+
+
+gobject.type_register(ScriptureChapterWindow)
diff --git a/src/windows/source.py b/src/windows/source.py
new file mode 100644 (file)
index 0000000..fee997c
--- /dev/null
@@ -0,0 +1,143 @@
+import logging
+
+import gobject
+import gtk
+
+import constants
+import util.misc as misc_utils
+import hildonize
+import banners
+import presenter
+import stream_index
+
+import windows
+
+
+_moduleLogger = logging.getLogger(__name__)
+
+
+class SourceSelector(windows._base.BasicWindow):
+
+       def __init__(self, app, player, store, index):
+               windows._base.BasicWindow.__init__(self, app, player, store)
+               self._languages = []
+               self._index = index
+
+               self._loadingBanner = banners.GenericBanner()
+
+               self._radioButton = self._create_button("radio", "Radio")
+               self._radioButton.connect("clicked", self._on_source_selected, stream_index.SOURCE_RADIO)
+
+               self._conferenceButton = self._create_button("conferences", "Conferences")
+               self._conferenceButton.connect("clicked", self._on_source_selected, stream_index.SOURCE_CONFERENCES)
+
+               self._magazineButton = self._create_button("magazines", "Magazines")
+               self._magazineButton.connect("clicked", self._on_source_selected, stream_index.SOURCE_MAGAZINES)
+
+               self._scriptureButton = self._create_button("scriptures", "Scriptures")
+               self._scriptureButton.connect("clicked", self._on_source_selected, stream_index.SOURCE_SCRIPTURES)
+
+               self._buttonLayout = gtk.VButtonBox()
+               self._buttonLayout.set_layout(gtk.BUTTONBOX_SPREAD)
+               self._buttonLayout.pack_start(self._radioButton, True, True)
+               self._buttonLayout.pack_start(self._conferenceButton, True, True)
+               self._buttonLayout.pack_start(self._magazineButton, True, True)
+               self._buttonLayout.pack_start(self._scriptureButton, True, True)
+
+               self._separator = gtk.HSeparator()
+               self._presenter = presenter.NavControl(player, store)
+               self._presenter.connect("jump-to", self._on_jump)
+
+               self._layout.pack_start(self._loadingBanner.toplevel, False, False)
+               self._layout.pack_start(self._buttonLayout, True, True)
+               self._layout.pack_start(self._separator, False, True)
+               self._layout.pack_start(self._presenter.toplevel, False, True)
+
+               self._window.set_title(constants.__pretty_app_name__)
+
+       def show(self):
+               windows._base.BasicWindow.show(self)
+
+               self._errorBanner.toplevel.hide()
+               self._presenter.toplevel.hide()
+
+               self._refresh()
+
+       def _show_loading(self):
+               animationPath = self._store.STORE_LOOKUP["loading"]
+               animation = self._store.get_pixbuf_animation_from_store(animationPath)
+               self._loadingBanner.show(animation, "Loading...")
+               self._buttonLayout.set_sensitive(False)
+
+       def _hide_loading(self):
+               self._loadingBanner.hide()
+               self._buttonLayout.set_sensitive(True)
+
+       def _refresh(self):
+               self._show_loading()
+               self._index.get_languages(self._on_languages, self._on_error)
+
+       def _create_button(self, icon, message):
+               image = self._store.get_image_from_store(self._store.STORE_LOOKUP[icon])
+
+               label = gtk.Label()
+               label.set_use_markup(True)
+               label.set_markup("<big>%s</big>" % message)
+
+               buttonLayout = gtk.HBox(False, 5)
+               buttonLayout.pack_start(image, False, False)
+               buttonLayout.pack_start(label, False, True)
+               button = gtk.Button()
+               button.add(buttonLayout)
+
+               return button
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_languages(self, languages):
+               self._hide_loading()
+               self._languages = list(languages)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_error(self, exception):
+               self._hide_loading()
+               self._errorBanner.push_message(str(exception))
+
+       def _window_from_node(self, node):
+               if node.id == stream_index.SOURCE_RADIO:
+                       Source = windows.radio.RadioWindow
+               elif node.id == stream_index.SOURCE_CONFERENCES:
+                       Source = windows.conferences.ConferencesWindow
+               elif node.id == stream_index.SOURCE_MAGAZINES:
+                       Source = windows.magazines.MagazinesWindow
+               elif node.id == stream_index.SOURCE_SCRIPTURES:
+                       Source = windows.scriptures.ScripturesWindow
+               sourceWindow = Source(self._app, self._player, self._store, node)
+               if not hildonize.IS_FREMANTLE_SUPPORTED:
+                       sourceWindow.window.set_modal(True)
+                       sourceWindow.window.set_transient_for(self._window)
+               sourceWindow.window.set_default_size(*self._window.get_size())
+               if self._windowInFullscreen:
+                       sourceWindow.window.fullscreen()
+               else:
+                       sourceWindow.window.unfullscreen()
+               sourceWindow.connect("quit", self._on_quit)
+               sourceWindow.connect("jump-to", self._on_jump)
+               sourceWindow.connect("fullscreen", self._on_child_fullscreen)
+               sourceWindow.show()
+               return sourceWindow
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_jump(self, source, node):
+               targetNodePath = list(reversed(list(stream_index.walk_ancestors(node))))
+               ancestor = targetNodePath[0]
+               window = self._window_from_node(ancestor)
+               window.jump_to(node)
+
+       @misc_utils.log_exception(_moduleLogger)
+       def _on_source_selected(self, widget, nodeName):
+               node = self._index.get_source(nodeName, self._languages[0]["id"])
+               self._window_from_node(node)
+
+
+gobject.type_register(SourceSelector)
+
diff --git a/support/builddeb.py b/support/builddeb.py
new file mode 100755 (executable)
index 0000000..4a460f6
--- /dev/null
@@ -0,0 +1,154 @@
+#!/usr/bin/python2.5
+
+import os
+import sys
+
+try:
+       import py2deb
+except ImportError:
+       import fake_py2deb as py2deb
+
+import constants
+
+
+__appname__ = constants.__app_name__
+__description__ = """Player for inspirational streaming radio and audiobooks including the KJV Bible
+Supports streaming:
+* "Mormon Channel" inspirational radio station
+* Conference precedings and magazines from The Church of Jesus Christ of Latter-day Saints
+* Scriptures, including King James Version of the Bible and the Book of Mormon
+.
+Homepage: http://www.lds.org
+"""
+__author__ = "The Church of Jesus Christ of Latter-day Saints"
+__email__ = ""
+__version__ = constants.__version__
+__build__ = constants.__build__
+__changelog__ = """
+"""
+
+
+__postinstall__ = """#!/bin/sh -e
+
+gtk-update-icon-cache -f /usr/share/icons/hicolor
+"""
+
+
+def find_files(path):
+       for root, dirs, files in os.walk(path):
+               for file in files:
+                       if file.startswith("src-"):
+                               fileParts = file.split("-")
+                               unused, relPathParts, newName = fileParts[0], fileParts[1:-1], fileParts[-1]
+                               assert unused == "src"
+                               relPath = os.sep.join(relPathParts)
+                               yield relPath, file, newName
+
+
+def unflatten_files(files):
+       d = {}
+       for relPath, oldName, newName in files:
+               if relPath not in d:
+                       d[relPath] = []
+               d[relPath].append((oldName, newName))
+       return d
+
+
+def build_package(distribution):
+       try:
+               os.chdir(os.path.dirname(sys.argv[0]))
+       except:
+               pass
+
+       py2deb.Py2deb.SECTIONS = py2deb.SECTIONS_BY_POLICY[distribution]
+       p = py2deb.Py2deb(__appname__)
+       p.prettyName = constants.__pretty_app_name__
+       p.description = __description__
+       p.bugTracker = ""
+       p.upgradeDescription = __changelog__.split("\n\n", 1)[0]
+       p.author = __author__
+       p.mail = __email__
+       p.license = "lgpl"
+       p.depends = ", ".join([
+               "python2.6 | python2.5",
+               "python-gtk2 | python2.5-gtk2",
+               "python-xml | python2.5-xml",
+               "python-dbus | python2.5-dbus",
+               "python-gst0.10 | python2.5-gst0.10",
+       ])
+       maemoSpecificDepends = ", python-osso | python2.5-osso, python-hildon | python2.5-hildon"
+       p.depends += {
+               "debian": ", python-glade2",
+               "diablo": maemoSpecificDepends + "",
+               "fremantle": maemoSpecificDepends + ", python-glade2",
+       }[distribution]
+       p.recommends = ", ".join([
+       ])
+       p.section = {
+               "debian": "",
+               "diablo": "",
+               "fremantle": "",
+       }[distribution]
+       p.arch = "all"
+       p.urgency = "low"
+       p.distribution = "diablo fremantle debian"
+       p.repository = "extras"
+       p.changelog = __changelog__
+       p.postinstall = __postinstall__
+       p.icon = {
+               "debian": "",
+               "diablo": "",
+               "fremantle": "", # Fremantle natively uses 48x48
+       }[distribution]
+       p["/usr/bin"] = [ "" ]
+       for relPath, files in unflatten_files(find_files(".")).iteritems():
+               fullPath = ""
+               if relPath:
+                       fullPath += os.sep+relPath
+               p[fullPath] = list(
+                       "|".join((oldName, newName))
+                       for (oldName, newName) in files
+               )
+       p["/usr/share/applications/hildon"] = [""]
+       p["/usr/share/icons/hicolor/26x26/hildon"] = [""]
+       p["/usr/share/icons/hicolor/64x64/hildon"] = [""]
+       p["/usr/share/icons/hicolor/scalable/hildon"] = [""]
+
+       if distribution == "debian":
+               print p
+               print p.generate(
+                       version="%s-%s" % (__version__, __build__),
+                       changelog=__changelog__,
+                       build=True,
+                       tar=False,
+                       changes=False,
+                       dsc=False,
+               )
+               print "Building for %s finished" % distribution
+       else:
+               print p
+               print p.generate(
+                       version="%s-%s" % (__version__, __build__),
+                       changelog=__changelog__,
+                       build=False,
+                       tar=True,
+                       changes=True,
+                       dsc=True,
+               )
+               print "Building for %s finished" % distribution
+
+
+if __name__ == "__main__":
+       if len(sys.argv) > 1:
+               try:
+                       import optparse
+               except ImportError:
+                       optparse = None
+
+               if optparse is not None:
+                       parser = optparse.OptionParser()
+                       (commandOptions, commandArgs) = parser.parse_args()
+       else:
+               commandArgs = None
+               commandArgs = ["diablo"]
+       build_package(commandArgs[0])
diff --git a/support/fake_py2deb.py b/support/fake_py2deb.py
new file mode 100644 (file)
index 0000000..5d6149d
--- /dev/null
@@ -0,0 +1,56 @@
+import pprint
+
+
+class Py2deb(object):
+
+       def __init__(self, appName):
+               self._appName = appName
+               self.description = ""
+               self.author = ""
+               self.mail = ""
+               self.license = ""
+               self.depends = ""
+               self.section = ""
+               self.arch = ""
+               self.ugency = ""
+               self.distribution = ""
+               self.repository = ""
+               self.changelog = ""
+               self.postinstall = ""
+               self.icon = ""
+               self._install = {}
+
+       def generate(self, appVersion, appBuild, changelog, tar, dsc, changes, build, src):
+               return """
+Package: %s
+version: %s-%s
+Changes:
+%s
+
+Build Options:
+       Tar: %s
+       Dsc: %s
+       Changes: %s
+       Build: %s
+       Src: %s
+               """ % (
+                       self._appName, appVersion, appBuild, changelog, tar, dsc, changes, build, src
+               )
+
+       def __str__(self):
+               parts = []
+               parts.append("%s Package Settings:" % (self._appName, ))
+               for settingName in dir(self):
+                       if settingName.startswith("_"):
+                               continue
+                       parts.append("\t%s: %s" % (settingName, getattr(self, settingName)))
+
+               parts.append(pprint.pformat(self._install))
+
+               return "\n".join(parts)
+
+       def __getitem__(self, key):
+               return self._install[key]
+
+       def __setitem__(self, key, item):
+               self._install[key] = item
diff --git a/support/py2deb.py b/support/py2deb.py
new file mode 100644 (file)
index 0000000..4a47513
--- /dev/null
@@ -0,0 +1,991 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+##
+##    Copyright (C) 2009 manatlan manatlan[at]gmail(dot)com
+##
+## This program is free software; you can redistribute it and/or modify
+## it under the terms of the GNU General Public License as published
+## by the Free Software Foundation; version 2 only.
+##
+## This program is distributed in the hope that it will be useful,
+## but WITHOUT ANY WARRANTY; without even the implied warranty of
+## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+## GNU General Public License for more details.
+##
+"""
+Known limitations :
+- don't sign package (-us -uc)
+- no distinctions between author and maintainer(packager)
+
+depends on :
+- dpkg-dev (dpkg-buildpackage)
+- alien
+- python
+- fakeroot
+
+changelog
+ - ??? ?/??/20?? (By epage)
+    - PEP8
+    - added recommends
+    - fixed bug where it couldn't handle the contents of the pre/post scripts being specified
+    - Added customization based on the targeted policy for sections (Maemo support)
+    - Added maemo specific tarball, dsc, changes file generation support (including icon support)
+    - Added armel architecture
+    - Reduced the size of params being passed around by reducing the calls to locals()
+    - Added respository, distribution, priority
+    - Made setting control file a bit more flexible
+ - 0.5 05/09/2009
+    - pre/post install/remove scripts enabled
+    - deb package install py2deb in dist-packages for py2.6
+ - 0.4 14/10/2008
+    - use os.environ USERNAME or USER (debian way)
+    - install on py 2.(4,5,6) (*FIX* do better here)
+
+"""
+
+import os
+import hashlib
+import sys
+import shutil
+import time
+import string
+import StringIO
+import stat
+import commands
+import base64
+import tarfile
+from glob import glob
+from datetime import datetime
+import socket # gethostname()
+from subprocess import Popen, PIPE
+
+#~ __version__ = "0.4"
+__version__ = "0.5"
+__author__ = "manatlan"
+__mail__ = "manatlan@gmail.com"
+
+
+PERMS_URW_GRW_OR = stat.S_IRUSR | stat.S_IWUSR | \
+                   stat.S_IRGRP | stat.S_IWGRP | \
+                   stat.S_IROTH
+
+UID_ROOT = 0
+GID_ROOT = 0
+
+
+def run(cmds):
+    p = Popen(cmds, shell=False, stdout=PIPE, stderr=PIPE)
+    time.sleep(0.01)    # to avoid "IOError: [Errno 4] Interrupted system call"
+    out = string.join(p.stdout.readlines()).strip()
+    outerr = string.join(p.stderr.readlines()).strip()
+    return out
+
+
+def deb2rpm(file):
+    txt=run(['alien', '-r', file])
+    return txt.split(" generated")[0]
+
+
+def py2src(TEMP, name):
+    l=glob("%(TEMP)s/%(name)s*.tar.gz" % locals())
+    if len(l) != 1:
+        raise Py2debException("don't find source package tar.gz")
+
+    tar = os.path.basename(l[0])
+    shutil.move(l[0], tar)
+
+    return tar
+
+
+def md5sum(filename):
+    f = open(filename, "r")
+    try:
+        return hashlib.md5(f.read()).hexdigest()
+    finally:
+        f.close()
+
+
+class Py2changes(object):
+
+    def __init__(self, ChangedBy, description, changes, files, category, repository, **kwargs):
+      self.options = kwargs # TODO: Is order important?
+      self.description = description
+      self.changes=changes
+      self.files=files
+      self.category=category
+      self.repository=repository
+      self.ChangedBy=ChangedBy
+
+    def getContent(self):
+        content = ["%s: %s" % (k, v)
+                   for k,v in self.options.iteritems()]
+
+        if self.description:
+            description=self.description.replace("\n","\n ")
+            content.append('Description: ')
+            content.append(' %s' % description)
+        if self.changes:
+            changes=self.changes.replace("\n","\n ")
+            content.append('Changes: ')
+            content.append(' %s' % changes)
+        if self.ChangedBy:
+            content.append("Changed-By: %s" % self.ChangedBy)
+
+        content.append('Files:')
+
+        for onefile in self.files:
+            md5 = md5sum(onefile)
+            size = os.stat(onefile).st_size.__str__()
+            content.append(' ' + md5 + ' ' + size + ' ' + self.category +' '+self.repository+' '+os.path.basename(onefile))
+
+        return "\n".join(content) + "\n\n"
+
+
+def py2changes(params):
+    changescontent = Py2changes(
+        "%(author)s <%(mail)s>" % params,
+        "%(description)s" % params,
+        "%(changelog)s" % params,
+        (
+            "%(TEMP)s/%(name)s_%(version)s.tar.gz" % params,
+            "%(TEMP)s/%(name)s_%(version)s.dsc" % params,
+        ),
+        "%(section)s" % params,
+        "%(repository)s" % params,
+        Format='1.7',
+        Date=time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()),
+        Source="%(name)s" % params,
+        Architecture="%(arch)s" % params,
+        Version="%(version)s" % params,
+        Distribution="%(distribution)s" % params,
+        Urgency="%(urgency)s" % params,
+        Maintainer="%(author)s <%(mail)s>" % params
+    )
+    f = open("%(TEMP)s/%(name)s_%(version)s.changes" % params,"wb")
+    f.write(changescontent.getContent())
+    f.close()
+
+    fileHandle = open('/tmp/py2deb2.tmp', 'w')
+    fileHandle.write('#!/bin/sh\n')
+    fileHandle.write("cd " +os.getcwd()+ "\n")
+    # TODO Renable signing
+    # fileHandle.write("gpg --local-user %(mail)s --clearsign %(TEMP)s/%(name)s_%(version)s.changes\n" % params)
+    fileHandle.write("mv %(TEMP)s/%(name)s_%(version)s.changes.asc %(TEMP)s/%(name)s_%(version)s.changes\n" % params)
+    fileHandle.write('\nexit')
+    fileHandle.close()
+    commands.getoutput("chmod 777 /tmp/py2deb2.tmp")
+    commands.getoutput("/tmp/py2deb2.tmp")
+
+    ret = []
+
+    l=glob("%(TEMP)s/%(name)s*.tar.gz" % params)
+    if len(l)!=1:
+        raise Py2debException("don't find source package tar.gz")
+    tar = os.path.basename(l[0])
+    shutil.move(l[0],tar)
+    ret.append(tar)
+
+    l=glob("%(TEMP)s/%(name)s*.dsc" % params)
+    if len(l)!=1:
+        raise Py2debException("don't find source package dsc")
+    tar = os.path.basename(l[0])
+    shutil.move(l[0],tar)
+    ret.append(tar)
+
+    l = glob("%(TEMP)s/%(name)s*.changes" % params)
+    if len(l)!=1:
+        raise Py2debException("don't find source package changes")
+    tar = os.path.basename(l[0])
+    shutil.move(l[0],tar)
+    ret.append(tar)
+
+    return ret
+
+
+class Py2dsc(object):
+
+    def __init__(self, StandardsVersion, BuildDepends, files, **kwargs):
+      self.options = kwargs # TODO: Is order important?
+      self.StandardsVersion = StandardsVersion
+      self.BuildDepends=BuildDepends
+      self.files=files
+
+    @property
+    def content(self):
+        content = ["%s: %s" % (k, v)
+                   for k,v in self.options.iteritems()]
+
+        if self.BuildDepends:
+            content.append("Build-Depends: %s" % self.BuildDepends)
+        if self.StandardsVersion:
+            content.append("Standards-Version: %s" % self.StandardsVersion)
+
+        content.append('Files:')
+
+        for onefile in self.files:
+            print onefile
+            md5 = md5sum(onefile)
+            size = os.stat(onefile).st_size.__str__()
+            content.append(' '+md5 + ' ' + size +' '+os.path.basename(onefile))
+
+        return "\n".join(content)+"\n\n"
+
+
+def py2dsc(TEMP, name, version, depends, author, mail, arch):
+    dsccontent = Py2dsc(
+        "%(version)s" % locals(),
+        "%(depends)s" % locals(),
+        ("%(TEMP)s/%(name)s_%(version)s.tar.gz" % locals(),),
+        Format='1.0',
+        Source="%(name)s" % locals(),
+        Version="%(version)s" % locals(),
+        Maintainer="%(author)s <%(mail)s>" % locals(),
+        Architecture="%(arch)s" % locals(),
+    )
+
+    filename = "%(TEMP)s/%(name)s_%(version)s.dsc" % locals()
+
+    f = open(filename, "wb")
+    try:
+        f.write(dsccontent.content)
+    finally:
+        f.close()
+
+    fileHandle = open('/tmp/py2deb.tmp', 'w')
+    try:
+        fileHandle.write('#!/bin/sh\n')
+        fileHandle.write("cd " + os.getcwd() + "\n")
+        # TODO Renable signing
+        # fileHandle.write("gpg --local-user %(mail)s --clearsign %(TEMP)s/%(name)s_%(version)s.dsc\n" % locals())
+        fileHandle.write("mv %(TEMP)s/%(name)s_%(version)s.dsc.asc %(filename)s\n" % locals())
+        fileHandle.write('\nexit')
+        fileHandle.close()
+    finally:
+        f.close()
+
+    commands.getoutput("chmod 777 /tmp/py2deb.tmp")
+    commands.getoutput("/tmp/py2deb.tmp")
+
+    return filename
+
+
+class Py2tar(object):
+
+    def __init__(self, dataDirectoryPath):
+        self._dataDirectoryPath = dataDirectoryPath
+
+    def packed(self):
+        return self._getSourcesFiles()
+
+    def _getSourcesFiles(self):
+        directoryPath = self._dataDirectoryPath
+
+        outputFileObj = StringIO.StringIO() # TODO: Do more transparently?
+
+        tarOutput = tarfile.TarFile.open('sources',
+                                 mode = "w:gz",
+                                 fileobj = outputFileObj)
+
+        # Note: We can't use this because we need to fiddle permissions:
+        #       tarOutput.add(directoryPath, arcname = "")
+
+        for root, dirs, files in os.walk(directoryPath):
+            archiveRoot = root[len(directoryPath):]
+
+            tarinfo = tarOutput.gettarinfo(root, archiveRoot)
+            # TODO: Make configurable?
+            tarinfo.uid = UID_ROOT
+            tarinfo.gid = GID_ROOT
+            tarinfo.uname = ""
+            tarinfo.gname = ""
+            tarOutput.addfile(tarinfo)
+
+            for f in  files:
+                tarinfo = tarOutput.gettarinfo(os.path.join(root, f),
+                                               os.path.join(archiveRoot, f))
+                tarinfo.uid = UID_ROOT
+                tarinfo.gid = GID_ROOT
+                tarinfo.uname = ""
+                tarinfo.gname = ""
+                tarOutput.addfile(tarinfo, file(os.path.join(root, f)))
+
+        tarOutput.close()
+
+        data_tar_gz = outputFileObj.getvalue()
+
+        return data_tar_gz
+
+
+def py2tar(DEST, TEMP, name, version):
+    tarcontent = Py2tar("%(DEST)s" % locals())
+    filename = "%(TEMP)s/%(name)s_%(version)s.tar.gz" % locals()
+    f = open(filename, "wb")
+    try:
+        f.write(tarcontent.packed())
+    finally:
+        f.close()
+    return filename
+
+
+class Py2debException(Exception):
+    pass
+
+
+SECTIONS_BY_POLICY = {
+    # http://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections
+    "debian": "admin, base, comm, contrib, devel, doc, editors, electronics, embedded, games, gnome, graphics, hamradio, interpreters, kde, libs, libdevel, mail, math, misc, net, news, non-free, oldlibs, otherosfs, perl, python, science, shells, sound, tex, text, utils, web, x11",
+    # http://maemo.org/forrest-images/pdf/maemo-policy.pdf
+    "chinook": "accessories, communication, games, multimedia, office, other, programming, support, themes, tools",
+    # http://wiki.maemo.org/Task:Package_categories
+    "diablo": "user/desktop, user/development, user/education, user/games, user/graphics, user/multimedia, user/navigation, user/network, user/office, user/science, user/system, user/utilities",
+    # http://wiki.maemo.org/Task:Fremantle_application_categories
+    "mer": "user/desktop, user/development, user/education, user/games, user/graphics, user/multimedia, user/navigation, user/network, user/office, user/science, user/system, user/utilities",
+    # http://wiki.maemo.org/Task:Fremantle_application_categories
+    "fremantle": "user/desktop, user/development, user/education, user/games, user/graphics, user/multimedia, user/navigation, user/network, user/office, user/science, user/system, user/utilities",
+}
+
+
+LICENSE_AGREEMENT = {
+        "gpl": """
+    This package is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This package is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this package; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+
+On Debian systems, the complete text of the GNU General
+Public License can be found in `/usr/share/common-licenses/GPL'.
+""",
+        "lgpl":"""
+    This package is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This package is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this package; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
+
+On Debian systems, the complete text of the GNU Lesser General
+Public License can be found in `/usr/share/common-licenses/LGPL'.
+""",
+        "bsd": """
+    Redistribution and use in source and binary forms, with or without
+    modification, are permitted under the terms of the BSD License.
+
+    THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
+
+On Debian systems, the complete text of the BSD License can be
+found in `/usr/share/common-licenses/BSD'.
+""",
+        "artistic": """
+    This program is free software; you can redistribute it and/or modify it
+    under the terms of the "Artistic License" which comes with Debian.
+
+    THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
+    WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES
+    OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+
+On Debian systems, the complete text of the Artistic License
+can be found in `/usr/share/common-licenses/Artistic'.
+"""
+}
+
+
+class Py2deb(object):
+    """
+    heavily based on technic described here :
+    http://wiki.showmedo.com/index.php?title=LinuxJensMakingDeb
+    """
+    ## STATICS
+    clear = False  # clear build folder after py2debianization
+
+    SECTIONS = SECTIONS_BY_POLICY["debian"]
+
+    #http://www.debian.org/doc/debian-policy/footnotes.html#f69
+    ARCHS = "all i386 ia64 alpha amd64 armeb arm hppa m32r m68k mips mipsel powerpc ppc64 s390 s390x sh3 sh3eb sh4 sh4eb sparc darwin-i386 darwin-ia64 darwin-alpha darwin-amd64 darwin-armeb darwin-arm darwin-hppa darwin-m32r darwin-m68k darwin-mips darwin-mipsel darwin-powerpc darwin-ppc64 darwin-s390 darwin-s390x darwin-sh3 darwin-sh3eb darwin-sh4 darwin-sh4eb darwin-sparc freebsd-i386 freebsd-ia64 freebsd-alpha freebsd-amd64 freebsd-armeb freebsd-arm freebsd-hppa freebsd-m32r freebsd-m68k freebsd-mips freebsd-mipsel freebsd-powerpc freebsd-ppc64 freebsd-s390 freebsd-s390x freebsd-sh3 freebsd-sh3eb freebsd-sh4 freebsd-sh4eb freebsd-sparc kfreebsd-i386 kfreebsd-ia64 kfreebsd-alpha kfreebsd-amd64 kfreebsd-armeb kfreebsd-arm kfreebsd-hppa kfreebsd-m32r kfreebsd-m68k kfreebsd-mips kfreebsd-mipsel kfreebsd-powerpc kfreebsd-ppc64 kfreebsd-s390 kfreebsd-s390x kfreebsd-sh3 kfreebsd-sh3eb kfreebsd-sh4 kfreebsd-sh4eb kfreebsd-sparc knetbsd-i386 knetbsd-ia64 knetbsd-alpha knetbsd-amd64 knetbsd-armeb knetbsd-arm knetbsd-hppa knetbsd-m32r knetbsd-m68k knetbsd-mips knetbsd-mipsel knetbsd-powerpc knetbsd-ppc64 knetbsd-s390 knetbsd-s390x knetbsd-sh3 knetbsd-sh3eb knetbsd-sh4 knetbsd-sh4eb knetbsd-sparc netbsd-i386 netbsd-ia64 netbsd-alpha netbsd-amd64 netbsd-armeb netbsd-arm netbsd-hppa netbsd-m32r netbsd-m68k netbsd-mips netbsd-mipsel netbsd-powerpc netbsd-ppc64 netbsd-s390 netbsd-s390x netbsd-sh3 netbsd-sh3eb netbsd-sh4 netbsd-sh4eb netbsd-sparc openbsd-i386 openbsd-ia64 openbsd-alpha openbsd-amd64 openbsd-armeb openbsd-arm openbsd-hppa openbsd-m32r openbsd-m68k openbsd-mips openbsd-mipsel openbsd-powerpc openbsd-ppc64 openbsd-s390 openbsd-s390x openbsd-sh3 openbsd-sh3eb openbsd-sh4 openbsd-sh4eb openbsd-sparc hurd-i386 hurd-ia64 hurd-alpha hurd-amd64 hurd-armeb hurd-arm hurd-hppa hurd-m32r hurd-m68k hurd-mips hurd-mipsel hurd-powerpc hurd-ppc64 hurd-s390 hurd-s390x hurd-sh3 hurd-sh3eb hurd-sh4 hurd-sh4eb hurd-sparc armel".split(" ")
+
+    # license terms taken from dh_make
+    LICENSES = list(LICENSE_AGREEMENT.iterkeys())
+
+    def __setitem__(self, path, files):
+
+        if not type(files)==list:
+            raise Py2debException("value of key path '%s' is not a list"%path)
+        if not files:
+            raise Py2debException("value of key path '%s' should'nt be empty"%path)
+        if not path.startswith("/"):
+            raise Py2debException("key path '%s' malformed (don't start with '/')"%path)
+        if path.endswith("/"):
+            raise Py2debException("key path '%s' malformed (shouldn't ends with '/')"%path)
+
+        nfiles=[]
+        for file in files:
+
+            if ".." in file:
+                raise Py2debException("file '%s' contains '..', please avoid that!"%file)
+
+
+            if "|" in file:
+                if file.count("|")!=1:
+                    raise Py2debException("file '%s' is incorrect (more than one pipe)"%file)
+
+                file, nfile = file.split("|")
+            else:
+                nfile=file  # same localisation
+
+            if os.path.isdir(file):
+                raise Py2debException("file '%s' is a folder, and py2deb refuse folders !"%file)
+
+            if not os.path.isfile(file):
+                raise Py2debException("file '%s' doesn't exist"%file)
+
+            if file.startswith("/"):    # if an absolute file is defined
+                if file==nfile:         # and not renamed (pipe trick)
+                    nfile=os.path.basename(file)   # it's simply copied to 'path'
+
+            nfiles.append((file, nfile))
+
+        nfiles.sort(lambda a, b: cmp(a[1], b[1]))    #sort according new name (nfile)
+
+        self.__files[path]=nfiles
+
+    def __delitem__(self, k):
+        del self.__files[k]
+
+    def __init__(self,
+                    name,
+                    description="no description",
+                    license="gpl",
+                    depends="",
+                    section="utils",
+                    arch="all",
+
+                    url="",
+                    author = None,
+                    mail = None,
+
+                    preinstall = None,
+                    postinstall = None,
+                    preremove = None,
+                    postremove = None
+                ):
+
+        if author is None:
+            author = ("USERNAME" in os.environ) and os.environ["USERNAME"] or None
+            if author is None:
+                author = ("USER" in os.environ) and os.environ["USER"] or "unknown"
+
+        if mail is None:
+            mail = author+"@"+socket.gethostname()
+
+        self.name = name
+        self.prettyName = ""
+        self.description = description
+        self.upgradeDescription = ""
+        self.bugTracker = ""
+        self.license = license
+        self.depends = depends
+        self.recommends = ""
+        self.section = section
+        self.arch = arch
+        self.url = url
+        self.author = author
+        self.mail = mail
+        self.icon = ""
+        self.distribution = ""
+        self.respository = ""
+        self.urgency = "low"
+
+        self.preinstall = preinstall
+        self.postinstall = postinstall
+        self.preremove = preremove
+        self.postremove = postremove
+
+        self.__files={}
+
+    def __repr__(self):
+        name = self.name
+        license = self.license
+        description = self.description
+        depends = self.depends
+        recommends = self.recommends
+        section = self.section
+        arch = self.arch
+        url = self.url
+        author = self.author
+        mail = self.mail
+
+        preinstall = self.preinstall
+        postinstall = self.postinstall
+        preremove = self.preremove
+        postremove = self.postremove
+
+        paths=self.__files.keys()
+        paths.sort()
+        files=[]
+        for path in paths:
+            for file, nfile in self.__files[path]:
+                #~ rfile=os.path.normpath(os.path.join(path, nfile))
+                rfile=os.path.join(path, nfile)
+                if nfile==file:
+                    files.append(rfile)
+                else:
+                    files.append(rfile + " (%s)"%file)
+
+        files.sort()
+        files = "\n".join(files)
+
+
+        lscripts = [    preinstall and "preinst",
+                        postinstall and "postinst",
+                        preremove and "prerm",
+                        postremove and "postrm",
+                    ]
+        scripts = lscripts and ", ".join([i for i in lscripts if i]) or "None"
+        return """
+----------------------------------------------------------------------
+NAME        : %(name)s
+----------------------------------------------------------------------
+LICENSE     : %(license)s
+URL         : %(url)s
+AUTHOR      : %(author)s
+MAIL        : %(mail)s
+----------------------------------------------------------------------
+DEPENDS     : %(depends)s
+RECOMMENDS  : %(recommends)s
+ARCH        : %(arch)s
+SECTION     : %(section)s
+----------------------------------------------------------------------
+DESCRIPTION :
+%(description)s
+----------------------------------------------------------------------
+SCRIPTS : %(scripts)s
+----------------------------------------------------------------------
+FILES :
+%(files)s
+""" % locals()
+
+    def generate(self, version, changelog="", rpm=False, src=False, build=True, tar=False, changes=False, dsc=False):
+        """ generate a deb of version 'version', with or without 'changelog', with or without a rpm
+            (in the current folder)
+            return a list of generated files
+        """
+        if not sum([len(i) for i in self.__files.values()])>0:
+            raise Py2debException("no files are defined")
+
+        if not changelog:
+            changelog="* no changelog"
+
+        name = self.name
+        description = self.description
+        license = self.license
+        depends = self.depends
+        recommends = self.recommends
+        section = self.section
+        arch = self.arch
+        url = self.url
+        distribution = self.distribution
+        repository = self.repository
+        urgency = self.urgency
+        author = self.author
+        mail = self.mail
+        files = self.__files
+        preinstall = self.preinstall
+        postinstall = self.postinstall
+        preremove = self.preremove
+        postremove = self.postremove
+
+        if section not in Py2deb.SECTIONS:
+            raise Py2debException("section '%s' is unknown (%s)" % (section, str(Py2deb.SECTIONS)))
+
+        if arch not in Py2deb.ARCHS:
+            raise Py2debException("arch '%s' is unknown (%s)"% (arch, str(Py2deb.ARCHS)))
+
+        if license not in Py2deb.LICENSES:
+            raise Py2debException("License '%s' is unknown (%s)" % (license, str(Py2deb.LICENSES)))
+
+        # create dates (buildDate, buildDateYear)
+        d=datetime.now()
+        buildDate=d.strftime("%a, %d %b %Y %H:%M:%S +0000")
+        buildDateYear=str(d.year)
+
+        #clean description (add a space before each next lines)
+        description=description.replace("\r", "").strip()
+        description = "\n ".join(description.split("\n"))
+
+        #clean changelog (add 2 spaces before each next lines)
+        changelog=changelog.replace("\r", "").strip()
+        changelog = "\n  ".join(changelog.split("\n"))
+
+        TEMP = ".py2deb_build_folder"
+        DEST = os.path.join(TEMP, name)
+        DEBIAN = os.path.join(DEST, "debian")
+
+        packageContents = locals()
+
+        # let's start the process
+        try:
+            shutil.rmtree(TEMP)
+        except:
+            pass
+
+        os.makedirs(DEBIAN)
+        try:
+            rules=[]
+            dirs=[]
+            for path in files:
+                for ofile, nfile in files[path]:
+                    if os.path.isfile(ofile):
+                        # it's a file
+
+                        if ofile.startswith("/"): # if absolute path
+                            # we need to change dest
+                            dest=os.path.join(DEST, nfile)
+                        else:
+                            dest=os.path.join(DEST, ofile)
+
+                        # copy file to be packaged
+                        destDir = os.path.dirname(dest)
+                        if not os.path.isdir(destDir):
+                            os.makedirs(destDir)
+
+                        shutil.copy2(ofile, dest)
+
+                        ndir = os.path.join(path, os.path.dirname(nfile))
+                        nname = os.path.basename(nfile)
+
+                        # make a line RULES to be sure the destination folder is created
+                        # and one for copying the file
+                        fpath = "/".join(["$(CURDIR)", "debian", name+ndir])
+                        rules.append('mkdir -p "%s"' % fpath)
+                        rules.append('cp -a "%s" "%s"' % (ofile, os.path.join(fpath, nname)))
+
+                        # append a dir
+                        dirs.append(ndir)
+
+                    else:
+                        raise Py2debException("unknown file '' "%ofile) # shouldn't be raised (because controlled before)
+
+            # make rules right
+            rules= "\n\t".join(rules) + "\n"
+            packageContents["rules"] = rules
+
+            # make dirs right
+            dirs= [i[1:] for i in set(dirs)]
+            dirs.sort()
+
+            #==========================================================================
+            # CREATE debian/dirs
+            #==========================================================================
+            open(os.path.join(DEBIAN, "dirs"), "w").write("\n".join(dirs))
+
+            #==========================================================================
+            # CREATE debian/changelog
+            #==========================================================================
+            clog="""%(name)s (%(version)s) stable; urgency=low
+
+  %(changelog)s
+
+ -- %(author)s <%(mail)s>  %(buildDate)s
+""" % packageContents
+
+            open(os.path.join(DEBIAN, "changelog"), "w").write(clog)
+
+            #==========================================================================
+            #Create pre/post install/remove
+            #==========================================================================
+            def mkscript(name, dest):
+                if name and name.strip()!="":
+                    if os.path.isfile(name):    # it's a file
+                        content = file(name).read()
+                    else:   # it's a script
+                        content = name
+                    open(os.path.join(DEBIAN, dest), "w").write(content)
+
+            mkscript(preinstall, "preinst")
+            mkscript(postinstall, "postinst")
+            mkscript(preremove, "prerm")
+            mkscript(postremove, "postrm")
+
+
+            #==========================================================================
+            # CREATE debian/compat
+            #==========================================================================
+            open(os.path.join(DEBIAN, "compat"), "w").write("5\n")
+
+            #==========================================================================
+            # CREATE debian/control
+            #==========================================================================
+            generalParagraphFields = [
+                "Source: %(name)s",
+                "Maintainer: %(author)s <%(mail)s>",
+                "Section: %(section)s",
+                "Priority: extra",
+                "Build-Depends: debhelper (>= 5)",
+                "Standards-Version: 3.7.2",
+            ]
+
+            specificParagraphFields = [
+                "Package: %(name)s",
+                "Architecture: %(arch)s",
+                "Depends: %(depends)s",
+                "Recommends: %(recommends)s",
+                "Description: %(description)s",
+            ]
+
+            if self.prettyName:
+                prettyName = "XSBC-Maemo-Display-Name: %s" % self.prettyName.strip()
+                specificParagraphFields.append("\n  ".join(prettyName.split("\n")))
+
+            if self.bugTracker:
+                bugTracker = "XSBC-Bugtracker: %s" % self.bugTracker.strip()
+                specificParagraphFields.append("\n  ".join(bugTracker.split("\n")))
+
+            if self.upgradeDescription:
+                upgradeDescription = "XSBC-Maemo-Upgrade-Description: %s" % self.upgradeDescription.strip()
+                specificParagraphFields.append("\n  ".join(upgradeDescription.split("\n")))
+
+            if self.icon:
+                f = open(self.icon, "rb")
+                try:
+                    rawIcon = f.read()
+                finally:
+                    f.close()
+                uueIcon = base64.b64encode(rawIcon)
+                uueIconLines = []
+                for i, c in enumerate(uueIcon):
+                    if i % 60 == 0:
+                        uueIconLines.append("")
+                    uueIconLines[-1] += c
+                uueIconLines[0:0] = ("XSBC-Maemo-Icon-26:", )
+                specificParagraphFields.append("\n  ".join(uueIconLines))
+
+            generalParagraph = "\n".join(generalParagraphFields)
+            specificParagraph = "\n".join(specificParagraphFields)
+            controlContent = "\n\n".join((generalParagraph, specificParagraph)) % packageContents
+            open(os.path.join(DEBIAN, "control"), "w").write(controlContent)
+
+            #==========================================================================
+            # CREATE debian/copyright
+            #==========================================================================
+            packageContents["txtLicense"] = LICENSE_AGREEMENT[license]
+            packageContents["pv"] =__version__
+            txt="""This package was py2debianized(%(pv)s) by %(author)s <%(mail)s> on
+%(buildDate)s.
+
+It was downloaded from %(url)s
+
+Upstream Author: %(author)s <%(mail)s>
+
+Copyright: %(buildDateYear)s by %(author)s
+
+License:
+
+%(txtLicense)s
+
+The Debian packaging is (C) %(buildDateYear)s, %(author)s <%(mail)s> and
+is licensed under the GPL, see above.
+
+
+# Please also look if there are files or directories which have a
+# different copyright/license attached and list them here.
+""" % packageContents
+            open(os.path.join(DEBIAN, "copyright"), "w").write(txt)
+
+            #==========================================================================
+            # CREATE debian/rules
+            #==========================================================================
+            txt="""#!/usr/bin/make -f
+# -*- makefile -*-
+# Sample debian/rules that uses debhelper.
+# This file was originally written by Joey Hess and Craig Small.
+# As a special exception, when this file is copied by dh-make into a
+# dh-make output file, you may use that output file without restriction.
+# This special exception was added by Craig Small in version 0.37 of dh-make.
+
+# Uncomment this to turn on verbose mode.
+#export DH_VERBOSE=1
+
+
+
+
+CFLAGS = -Wall -g
+
+ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
+       CFLAGS += -O0
+else
+       CFLAGS += -O2
+endif
+
+configure: configure-stamp
+configure-stamp:
+       dh_testdir
+       # Add here commands to configure the package.
+
+       touch configure-stamp
+
+
+build: build-stamp
+
+build-stamp: configure-stamp
+       dh_testdir
+       touch build-stamp
+
+clean:
+       dh_testdir
+       dh_testroot
+       rm -f build-stamp configure-stamp
+       dh_clean
+
+install: build
+       dh_testdir
+       dh_testroot
+       dh_clean -k
+       dh_installdirs
+
+       # ======================================================
+       #$(MAKE) DESTDIR="$(CURDIR)/debian/%(name)s" install
+       mkdir -p "$(CURDIR)/debian/%(name)s"
+
+       %(rules)s
+       # ======================================================
+
+# Build architecture-independent files here.
+binary-indep: build install
+# We have nothing to do by default.
+
+# Build architecture-dependent files here.
+binary-arch: build install
+       dh_testdir
+       dh_testroot
+       dh_installchangelogs debian/changelog
+       dh_installdocs
+       dh_installexamples
+#      dh_install
+#      dh_installmenu
+#      dh_installdebconf
+#      dh_installlogrotate
+#      dh_installemacsen
+#      dh_installpam
+#      dh_installmime
+#      dh_python
+#      dh_installinit
+#      dh_installcron
+#      dh_installinfo
+       dh_installman
+       dh_link
+       dh_strip
+       dh_compress
+       dh_fixperms
+#      dh_perl
+#      dh_makeshlibs
+       dh_installdeb
+       dh_shlibdeps
+       dh_gencontrol
+       dh_md5sums
+       dh_builddeb
+
+binary: binary-indep binary-arch
+.PHONY: build clean binary-indep binary-arch binary install configure
+""" % packageContents
+            open(os.path.join(DEBIAN, "rules"), "w").write(txt)
+            os.chmod(os.path.join(DEBIAN, "rules"), 0755)
+
+            ###########################################################################
+            ###########################################################################
+            ###########################################################################
+
+            generatedFiles = []
+
+            if build:
+                #http://www.debian.org/doc/manuals/maint-guide/ch-build.fr.html
+                ret = os.system('cd "%(DEST)s"; dpkg-buildpackage -tc -rfakeroot -us -uc' % packageContents)
+                if ret != 0:
+                    raise Py2debException("buildpackage failed (see output)")
+
+                l=glob("%(TEMP)s/%(name)s*.deb" % packageContents)
+                if len(l) != 1:
+                    raise Py2debException("didn't find builded deb")
+
+                tdeb = l[0]
+                deb = os.path.basename(tdeb)
+                shutil.move(tdeb, deb)
+
+                generatedFiles = [deb, ]
+
+                if rpm:
+                    rpmFilename = deb2rpm(deb)
+                    generatedFiles.append(rpmFilename)
+
+                if src:
+                    tarFilename = py2src(TEMP, name)
+                    generatedFiles.append(tarFilename)
+
+            if tar:
+                tarFilename = py2tar(DEST, TEMP, name, version)
+                generatedFiles.append(tarFilename)
+
+            if dsc:
+                dscFilename = py2dsc(TEMP, name, version, depends, author, mail, arch)
+                generatedFiles.append(dscFilename)
+
+            if changes:
+                changesFilenames = py2changes(packageContents)
+                generatedFiles.extend(changesFilenames)
+
+            return generatedFiles
+
+        #~ except Exception,m:
+            #~ raise Py2debException("build error :"+str(m))
+
+        finally:
+            if Py2deb.clear:
+                shutil.rmtree(TEMP)
+
+
+if __name__ == "__main__":
+    try:
+        os.chdir(os.path.dirname(sys.argv[0]))
+    except:
+        pass
+
+    p=Py2deb("python-py2deb")
+    p.description="Generate simple deb(/rpm/tgz) from python (2.4, 2.5 and 2.6)"
+    p.url = "http://www.manatlan.com/page/py2deb"
+    p.author=__author__
+    p.mail=__mail__
+    p.depends = "dpkg-dev, fakeroot, alien, python"
+    p.section="python"
+    p["/usr/lib/python2.6/dist-packages"] = ["py2deb.py", ]
+    p["/usr/lib/python2.5/site-packages"] = ["py2deb.py", ]
+    p["/usr/lib/python2.4/site-packages"] = ["py2deb.py", ]
+    #~ p.postinstall = "s.py"
+    #~ p.preinstall = "s.py"
+    #~ p.postremove = "s.py"
+    #~ p.preremove = "s.py"
+    print p
+    print p.generate(__version__, changelog = __doc__, src=True)
diff --git a/support/pylint.rc b/support/pylint.rc
new file mode 100644 (file)
index 0000000..2a371a1
--- /dev/null
@@ -0,0 +1,305 @@
+# lint Python modules using external checkers.
+#
+# This is the main checker controling the other ones and the reports
+# generation. It is itself both a raw checker and an astng checker in order
+# to:
+# * handle message activation / deactivation at the module level
+# * handle some basic but necessary stats'data (number of classes, methods...)
+#
+[MASTER]
+
+# Specify a configuration file.
+#rcfile=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Profiled execution.
+profile=no
+
+# Add <file or directory> to the black list. It should be a base name, not a
+# path. You may set this option multiple times.
+ignore=CVS
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Set the cache size for astng objects.
+cache-size=500
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+
+[MESSAGES CONTROL]
+
+# Enable only checker(s) with the given id(s). This option conflicts with the
+# disable-checker option
+#enable-checker=
+
+# Enable all checker(s) except those with the given id(s). This option
+# conflicts with the enable-checker option
+#disable-checker=
+
+# Enable all messages in the listed categories.
+#enable-msg-cat=
+
+# Disable all messages in the listed categories.
+#disable-msg-cat=
+
+# Enable the message(s) with the given id(s).
+#enable-msg=
+
+# Disable the message(s) with the given id(s).
+disable-msg=W0403,W0612,W0613,C0103,C0111,C0301,R0903,W0142,W0603,R0904,R0921,R0201
+
+[REPORTS]
+
+# set the output format. Available formats are text, parseable, colorized, msvs
+# (visual studio) and html
+output-format=colorized
+
+# Include message's id in output
+include-ids=yes
+
+# Put messages in a separate file for each module / package specified on the
+# command line instead of printing them on stdout. Reports (if any) will be
+# written in a file name "pylint_global.[txt|html]".
+files-output=no
+
+# Tells wether to display a full report or only the messages
+reports=no
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note).You have access to the variables errors warning, statement which
+# respectivly contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (R0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Add a comment according to your evaluation note. This is used by the global
+# evaluation report (R0004).
+comment=no
+
+# Enable the report(s) with the given id(s).
+#enable-report=
+
+# Disable the report(s) with the given id(s).
+#disable-report=
+
+
+# checks for
+# * unused variables / imports
+# * undefined variables
+# * redefinition of variable from builtins or from an outer scope
+# * use of variable before assigment
+#
+[VARIABLES]
+
+# Tells wether we should check for unused import in __init__ files.
+init-import=no
+
+# A regular expression matching names used for dummy variables (i.e. not used).
+dummy-variables-rgx=_|dummy
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+
+# checks for :
+# * doc strings
+# * modules / classes / functions / methods / arguments / variables name
+# * number of arguments, local variables, branchs, returns and statements in
+# functions, methods
+# * required module attributes
+# * dangerous default values as arguments
+# * redefinition of function / method / class
+# * uses of the global statement
+#
+[BASIC]
+
+# Required attributes for module, separated by a comma
+required-attributes=
+
+# Regular expression which should only match functions or classes name which do
+# not require a docstring
+no-docstring-rgx=__.*__
+
+# Regular expression which should only match correct module names
+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
+
+# Regular expression which should only match correct module level names
+const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$
+
+# Regular expression which should only match correct class names
+class-rgx=[A-Z_][a-zA-Z0-9]+$
+
+# Regular expression which should only match correct function names
+function-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct method names
+method-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match correct instance attribute names
+attr-rgx=[a-z_][a-zA-Z0-9_]{2,30}$
+
+# Regular expression which should only match correct argument names
+argument-rgx=[a-z_][a-zA-Z0-9_]{2,30}$
+
+# Regular expression which should only match correct variable names
+variable-rgx=[a-z_][a-zA-Z0-9_]{2,30}$
+
+# Regular expression which should only match correct list comprehension /
+# generator expression variable names
+inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=i,j,k,ex,Run,_
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=foo,bar,baz,toto,tutu,tata
+
+# List of builtins function names that should not be used, separated by a comma
+bad-functions=map,filter,apply,input
+
+
+# try to find bugs in the code using type inference
+# 
+[TYPECHECK]
+
+# Tells wether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# When zope mode is activated, consider the acquired-members option to ignore
+# access to some undefined attributes.
+zope=no
+
+# List of members which are usually get through zope's acquisition mecanism and
+# so shouldn't trigger E0201 when accessed (need zope=yes to be considered).
+acquired-members=REQUEST,acl_users,aq_parent
+
+
+# checks for sign of poor/misdesign:
+# * number of methods, attributes, local variables...
+# * size, complexity of functions, methods
+#
+[DESIGN]
+
+# Maximum number of arguments for function / method
+max-args=5
+
+# Maximum number of locals for function / method body
+max-locals=15
+
+# Maximum number of return / yield for function / method body
+max-returns=6
+
+# Maximum number of branch for function / method body
+max-branchs=12
+
+# Maximum number of statements in function / method body
+max-statements=50
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=15
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=1
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+
+# checks for :
+# * methods without self as first argument
+# * overridden methods signature
+# * access only to existant members via self
+# * attributes not defined in the __init__ method
+# * supported interfaces implementation
+# * unreachable code
+#
+[CLASSES]
+
+# List of interface methods to ignore, separated by a comma. This is used for
+# instance to not check methods defines in Zope's Interface base class.
+ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,__new__,setUp
+
+
+# checks for
+# * external modules dependencies
+# * relative / wildcard imports
+# * cyclic imports
+# * uses of deprecated modules
+#
+[IMPORTS]
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,string,TERMIOS,Bastion,rexec
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report R0402 must not be disabled)
+import-graph=
+
+# Create a graph of external dependencies in the given file (report R0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of internal dependencies in the given file (report R0402 must
+# not be disabled)
+int-import-graph=
+
+
+# checks for similarities and duplicated code. This computation may be
+# memory / CPU intensive, so you should disable it if you experiments some
+# problems.
+#
+[SIMILARITIES]
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+
+# checks for:
+# * warning notes in the code like FIXME, XXX
+# * PEP 263: source code with non ascii character but no encoding declaration
+#
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,XXX,TODO
+
+
+# checks for :
+# * unauthorized constructions
+# * strict indentation
+# * line length
+# * use of <> instead of !=
+#
+[FORMAT]
+
+# Maximum number of characters on a single line.
+# @note Limiting this to the most extreme cases
+max-line-length=100
+
+# Maximum number of lines in a module
+max-module-lines=1000
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string='\t'
diff --git a/support/test_syntax.py b/support/test_syntax.py
new file mode 100755 (executable)
index 0000000..65a373c
--- /dev/null
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+
+import commands
+
+
+verbose = False
+
+
+def syntax_test(file):
+       commandTemplate = """
+       python -t -t -W all -c "import py_compile; py_compile.compile ('%(filename)s', doraise=False)" """
+       compileCommand = commandTemplate % {"filename": file}
+       (status, text) = commands.getstatusoutput (compileCommand)
+       text = text.rstrip()
+       passed = len(text) == 0
+
+       if passed:
+               output = ("Syntax is correct for "+file) if verbose else ""
+       else:
+               output = ("Syntax is invalid for %s\n" % file) if verbose else ""
+               output += text
+       return (passed, output)
+
+
+if __name__ == "__main__":
+       import sys
+       import os
+       import optparse
+
+       opar = optparse.OptionParser()
+       opar.add_option("-v", "--verbose", dest="verbose", help="Toggle verbosity", action="store_true", default=False)
+       options, args = opar.parse_args(sys.argv[1:])
+       verbose = options.verbose
+
+       completeOutput = []
+       allPassed = True
+       for filename in args:
+               passed, output = syntax_test(filename)
+               if not passed:
+                       allPassed = False
+               if output.strip():
+                       completeOutput.append(output)
+       print "\n".join(completeOutput)
+
+       sys.exit(0 if allPassed else 1);
diff --git a/support/todo.py b/support/todo.py
new file mode 100755 (executable)
index 0000000..90cbd04
--- /dev/null
@@ -0,0 +1,104 @@
+#!/usr/bin/env python
+
+from __future__ import with_statement
+import itertools
+
+
+verbose = False
+
+
+def tag_parser(file, tag):
+       """
+       >>> nothing = []
+       >>> for todo in tag_parser(nothing, "@todo"):
+       ...     print todo
+       ...
+       >>> one = ["@todo Help!"]
+       >>> for todo in tag_parser(one, "@todo"):
+       ...     print todo
+       ...
+       1: @todo Help!
+       >>> mixed = ["one", "@todo two", "three"]
+       >>> for todo in tag_parser(mixed, "@todo"):
+       ...     print todo
+       ...
+       2: @todo two
+       >>> embedded = ["one @todo two", "three"]
+       >>> for todo in tag_parser(embedded, "@todo"):
+       ...     print todo
+       ...
+       1: @todo two
+       >>> continuation = ["one", "@todo two", " three"]
+       >>> for todo in tag_parser(continuation, "@todo"):
+       ...     print todo
+       ...
+       2: @todo two three
+       >>> series = ["one", "@todo two", "@todo three"]
+       >>> for todo in tag_parser(series, "@todo"):
+       ...     print todo
+       ...
+       2: @todo two
+       3: @todo three
+       """
+       currentTodo = []
+       prefix = None
+       for lineNumber, line in enumerate(file):
+               column = line.find(tag)
+               if column != -1:
+                       if currentTodo:
+                               yield "\n".join (currentTodo)
+                       prefix = line[0:column]
+                       currentTodo = ["%d: %s" % (lineNumber+1, line[column:].strip())]
+               elif prefix is not None and len(prefix)+1 < len(line) and line.startswith(prefix) and line[len(prefix)].isspace():
+                       currentTodo.append (line[len(prefix):].rstrip())
+               elif currentTodo:
+                       yield "\n".join (currentTodo)
+                       currentTodo = []
+                       prefix = None
+       if currentTodo:
+               yield "\n".join (currentTodo)
+
+
+def tag_finder(filename, tag):
+       todoList = []
+
+       with open(filename) as file:
+               body = "\n".join (tag_parser(file, tag))
+       passed = not body
+       if passed:
+               output = "No %s's for %s" % (tag, filename) if verbose else ""
+       else:
+               header = "%s's for %s:\n" % (tag, filename) if verbose else ""
+               output = header + body
+               output += "\n" if verbose else ""
+
+       return (passed, output)
+
+
+if __name__ == "__main__":
+       import sys
+       import os
+       import optparse
+
+       opar = optparse.OptionParser()
+       opar.add_option("-v", "--verbose", dest="verbose", help="Toggle verbosity", action="store_true", default=False)
+       options, args = opar.parse_args(sys.argv[1:])
+       verbose = options.verbose
+
+       bugsAsError = True
+       todosAsError = False
+
+       completeOutput = []
+       allPassed = True
+       for filename in args:
+               bugPassed, bugOutput = tag_finder(filename, "@bug")
+               todoPassed, todoOutput = tag_finder(filename, "@todo")
+               output = "\n".join ([bugOutput, todoOutput])
+               if (not bugPassed and bugsAsError) or (not todoPassed and todosAsError):
+                       allPassed = False
+               output = output.strip()
+               if output:
+                       completeOutput.append(filename+":\n"+output+"\n\n")
+       print "\n".join(completeOutput)
+       
+       sys.exit(0 if allPassed else 1);
diff --git a/tests/test_utils.py b/tests/test_utils.py
new file mode 100644 (file)
index 0000000..a2da797
--- /dev/null
@@ -0,0 +1,130 @@
+#!/usr/bin/env python
+
+
+from __future__ import with_statement
+
+import inspect
+import contextlib
+import functools
+
+
+def TODO(func):
+       """
+       unittest test method decorator that ignores
+       exceptions raised by test
+
+       Used to annotate test methods for code that may
+       not be written yet.  Ignores failures in the
+       annotated test method; fails if the text
+       unexpectedly succeeds.
+       !author http://kbyanc.blogspot.com/2007/06/pythons-unittest-module-aint-that-bad.html
+
+       Example:
+       >>> import unittest
+       >>> class ExampleTestCase(unittest.TestCase):
+       ...     @TODO
+       ...     def testToDo(self):
+       ...             MyModule.DoesNotExistYet('boo')
+       ...
+       """
+
+       @functools.wraps(func)
+       def wrapper(*args, **kw):
+               try:
+                       func(*args, **kw)
+                       succeeded = True
+               except:
+                       succeeded = False
+               assert succeeded is False, \
+                       "%s marked TODO but passed" % func.__name__
+       return wrapper
+
+
+def PlatformSpecific(platformList):
+       """
+       unittest test method decorator that only
+       runs test method if os.name is in the
+       given list of platforms
+       !author http://kbyanc.blogspot.com/2007/06/pythons-unittest-module-aint-that-bad.html
+       Example:
+       >>> import unittest
+       >>> class ExampleTestCase(unittest.TestCase):
+       ...     @PlatformSpecific(('mac', ))
+       ...     def testMacOnly(self):
+       ...             MyModule.SomeMacSpecificFunction()
+       ...
+       """
+
+       def decorator(func):
+               import os
+
+               @functools.wraps(func)
+               def wrapper(*args, **kw):
+                       if os.name in platformList:
+                               return func(*args, **kw)
+               return wrapper
+       return decorator
+
+
+def CheckReferences(func):
+       """
+       !author http://kbyanc.blogspot.com/2007/06/pythons-unittest-module-aint-that-bad.html
+       """
+
+       @functools.wraps(func)
+       def wrapper(*args, **kw):
+               refCounts = []
+               for i in range(5):
+                       func(*args, **kw)
+                       refCounts.append(XXXGetRefCount())
+               assert min(refCounts) != max(refCounts), "Reference counts changed - %r" % refCounts
+
+       return wrapper
+
+
+@contextlib.contextmanager
+def expected(exception):
+       """
+       >>> with expected2(ZeroDivisionError):
+       ...     1 / 0
+       >>> with expected2(AssertionError("expected ZeroDivisionError to have been thrown")):
+       ...     with expected(ZeroDivisionError):
+       ...             1 / 2
+       Traceback (most recent call last):
+               File "/usr/lib/python2.5/doctest.py", line 1228, in __run
+                       compileflags, 1) in test.globs
+               File "<doctest libraries.recipes.context.expected[1]>", line 3, in <module>
+                       1 / 2
+               File "/media/data/Personal/Development/bzr/Recollection-trunk/src/libraries/recipes/context.py", line 139, in __exit__
+                       assert t is not None, ("expected {0:%s} to have been thrown" % (self._t.__name__))
+       AssertionError: expected {0:ZeroDivisionError} to have been thrown
+       >>> with expected2(Exception("foo")):
+       ...     raise Exception("foo")
+       >>> with expected2(Exception("bar")):
+       ...     with expected(Exception("foo")): # this won't catch it
+       ...             raise Exception("bar")
+       ...     assert False, "should not see me"
+       >>> with expected2(Exception("can specify")):
+       ...     raise Exception("can specify prefixes")
+       >>> with expected2(Exception("Base class fun")):
+       True
+       >>> True
+       False
+       """
+       if isinstance(exception, Exception):
+               excType, excValue = type(exception), str(exception)
+       elif isinstance(exception, type):
+               excType, excValue = exception, ""
+
+       try:
+               yield
+       except Exception, e:
+               if not (excType in inspect.getmro(type(e)) and str(e).startswith(excValue)):
+                       raise
+       else:
+               raise AssertionError("expected {0:%s} to have been thrown" % excType.__name__)
+
+
+if __name__ == "__main__":
+       import doctest
+       doctest.testmod()
diff --git a/www/download.html b/www/download.html
new file mode 100644 (file)
index 0000000..a2b137b
--- /dev/null
@@ -0,0 +1,36 @@
+<html>
+       <head>
+               <title></title>
+       </head>
+       <body>
+               <h1>
+               </h1>
+               <h2></h2>
+               <h3><a href="index.html">[About]</a> <a href="screenshots.html">[Screenshots]</a> <a href="download.html">[Download]</a>
+               <h3>Download</h3>
+
+               <h4>Packages</h4>
+               <p>Maemo 5 and Later: Go to the application installer, enable Extras, and download</p>
+
+               <p>Maemo 4.1 and Earlier: Add the <a href="http://wiki.maemo.org/Extras">Extras Repository</a> and check the App Manager</p>
+
+               <p>Linux: <a href="">.deb files</a></p>
+
+               <h3>Development</h3>
+               <h4>Source</h4>
+               <p>For the most up to date version check out <a href="">git</a>.
+               </p>
+               <p>Requires</p>
+               <ul>
+                       <li>PyGTK / Glade</li>
+                       <li>Python bindings for hildon, osso, dbus, and conic</li>
+               </ul>
+
+               <h4>Bugs</h4>
+
+               <p>Discuss your issue on <a href="">Maemo.Org Talk</a></p>
+
+               <p>File a <a href="">bug report</a></p>
+               <p>View  <a href="">existing bug reports</a></p>
+       </body>
+</html>
diff --git a/www/index.html b/www/index.html
new file mode 100644 (file)
index 0000000..b794594
--- /dev/null
@@ -0,0 +1,30 @@
+<html>
+       <head>
+               <title></title>
+       </head>
+       <body>
+               <h1>
+               </h1>
+               <h2></h2>
+
+               <h3><a href="">[About]</a> <a href="screenshots.html">[Screenshots]</a> <a href="download.html">[Download]</a>
+
+               <h3>About</h3>
+               <p>
+               </p>
+
+
+               <p>This has been tested on Maemo 5, Maemo 4.1, and Ubuntu 9.04.  Go check out some <a href="">reviews</a>  or join the <a href="">conversation</a></p>
+
+               <p>This is Free Software and available under the <a href="http://www.gnu.org/licenses/lgpl-2.1.html">LGPLv2.1</a>.
+
+               <h4>Features</h4>
+
+               <p>(See <a href="">Maemo.Org Talk</a>)</p>
+
+               <ul>
+                       <li></li>
+               </ul>
+
+       </body>
+</html>
diff --git a/www/screenshots.html b/www/screenshots.html
new file mode 100644 (file)
index 0000000..a7bdf98
--- /dev/null
@@ -0,0 +1,14 @@
+<html>
+       <head>
+               <title></title>
+       </head>
+       <body>
+               <h1>
+               </h1>
+               <h2></h2>
+               <h3><a href="index.html">[About]</a> <a href="screenshots.html">[Screenshots]</a> <a href="download.html">[Download]</a>
+
+               <h3>Screen shots</h3>
+
+       </body>
+</html>