diff options
Diffstat (limited to 'src/jarabe/view')
-rw-r--r-- | src/jarabe/view/Makefile.am | 13 | ||||
-rw-r--r-- | src/jarabe/view/Makefile.in | 450 | ||||
-rw-r--r-- | src/jarabe/view/__init__.py | 15 | ||||
-rw-r--r-- | src/jarabe/view/buddyicon.py | 65 | ||||
-rw-r--r-- | src/jarabe/view/buddymenu.py | 180 | ||||
-rw-r--r-- | src/jarabe/view/customizebundle.py | 217 | ||||
-rw-r--r-- | src/jarabe/view/keyhandler.py | 216 | ||||
-rw-r--r-- | src/jarabe/view/launcher.py | 172 | ||||
-rw-r--r-- | src/jarabe/view/palettes.py | 255 | ||||
-rw-r--r-- | src/jarabe/view/pulsingicon.py | 237 | ||||
-rw-r--r-- | src/jarabe/view/service.py | 90 | ||||
-rw-r--r-- | src/jarabe/view/tabbinghandler.py | 149 | ||||
-rw-r--r-- | src/jarabe/view/viewsource.py | 570 |
13 files changed, 2629 insertions, 0 deletions
diff --git a/src/jarabe/view/Makefile.am b/src/jarabe/view/Makefile.am new file mode 100644 index 0000000..630f184 --- /dev/null +++ b/src/jarabe/view/Makefile.am @@ -0,0 +1,13 @@ +sugardir = $(pythondir)/jarabe/view +sugar_PYTHON = \ + __init__.py \ + buddyicon.py \ + buddymenu.py \ + customizebundle.py \ + keyhandler.py \ + launcher.py \ + palettes.py \ + pulsingicon.py \ + service.py \ + tabbinghandler.py \ + viewsource.py diff --git a/src/jarabe/view/Makefile.in b/src/jarabe/view/Makefile.in new file mode 100644 index 0000000..2ef1572 --- /dev/null +++ b/src/jarabe/view/Makefile.in @@ -0,0 +1,450 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +subdir = src/jarabe/view +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ + $(sugar_PYTHON) +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__py_compile = PYTHON=$(PYTHON) $(SHELL) $(py_compile) +am__installdirs = "$(DESTDIR)$(sugardir)" +py_compile = $(top_srcdir)/py-compile +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +ALL_LINGUAS = @ALL_LINGUAS@ +AMTAR = @AMTAR@ +AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CATALOGS = @CATALOGS@ +CATOBJEXT = @CATOBJEXT@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CYGPATH_W = @CYGPATH_W@ +DATADIRNAME = @DATADIRNAME@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +GCONFTOOL = @GCONFTOOL@ +GCONF_SCHEMA_CONFIG_SOURCE = @GCONF_SCHEMA_CONFIG_SOURCE@ +GCONF_SCHEMA_FILE_DIR = @GCONF_SCHEMA_FILE_DIR@ +GETTEXT_PACKAGE = @GETTEXT_PACKAGE@ +GMOFILES = @GMOFILES@ +GMSGFMT = @GMSGFMT@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INSTOBJEXT = @INSTOBJEXT@ +INTLLIBS = @INTLLIBS@ +INTLTOOL_EXTRACT = @INTLTOOL_EXTRACT@ +INTLTOOL_MERGE = @INTLTOOL_MERGE@ +INTLTOOL_PERL = @INTLTOOL_PERL@ +INTLTOOL_UPDATE = @INTLTOOL_UPDATE@ +INTLTOOL_V_MERGE = @INTLTOOL_V_MERGE@ +INTLTOOL_V_MERGE_OPTIONS = @INTLTOOL_V_MERGE_OPTIONS@ +INTLTOOL__v_MERGE_ = @INTLTOOL__v_MERGE_@ +INTLTOOL__v_MERGE_0 = @INTLTOOL__v_MERGE_0@ +LDFLAGS = @LDFLAGS@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LTLIBOBJS = @LTLIBOBJS@ +MAINT = @MAINT@ +MAKEINFO = @MAKEINFO@ +MKDIR_P = @MKDIR_P@ +MKINSTALLDIRS = @MKINSTALLDIRS@ +MSGFMT = @MSGFMT@ +MSGFMT_OPTS = @MSGFMT_OPTS@ +MSGMERGE = @MSGMERGE@ +OBJEXT = @OBJEXT@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +PKG_CONFIG = @PKG_CONFIG@ +PKG_CONFIG_LIBDIR = @PKG_CONFIG_LIBDIR@ +PKG_CONFIG_PATH = @PKG_CONFIG_PATH@ +POFILES = @POFILES@ +POSUB = @POSUB@ +PO_IN_DATADIR_FALSE = @PO_IN_DATADIR_FALSE@ +PO_IN_DATADIR_TRUE = @PO_IN_DATADIR_TRUE@ +PYTHON = @PYTHON@ +PYTHON_EXEC_PREFIX = @PYTHON_EXEC_PREFIX@ +PYTHON_PLATFORM = @PYTHON_PLATFORM@ +PYTHON_PREFIX = @PYTHON_PREFIX@ +PYTHON_VERSION = @PYTHON_VERSION@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +SHELL_CFLAGS = @SHELL_CFLAGS@ +SHELL_LIBS = @SHELL_LIBS@ +STRIP = @STRIP@ +SUCROSE_VERSION = @SUCROSE_VERSION@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_CC = @ac_ct_CC@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build_alias = @build_alias@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host_alias = @host_alias@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +intltool__v_merge_options_ = @intltool__v_merge_options_@ +intltool__v_merge_options_0 = @intltool__v_merge_options_0@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +pkgpyexecdir = @pkgpyexecdir@ +pkgpythondir = @pkgpythondir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +pyexecdir = @pyexecdir@ +pythondir = @pythondir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +sugardir = $(pythondir)/jarabe/view +sugar_PYTHON = \ + __init__.py \ + buddyicon.py \ + buddymenu.py \ + customizebundle.py \ + keyhandler.py \ + launcher.py \ + palettes.py \ + pulsingicon.py \ + service.py \ + tabbinghandler.py \ + viewsource.py + +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: @MAINTAINER_MODE_TRUE@ $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/jarabe/view/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign src/jarabe/view/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): @MAINTAINER_MODE_TRUE@ $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-sugarPYTHON: $(sugar_PYTHON) + @$(NORMAL_INSTALL) + test -z "$(sugardir)" || $(MKDIR_P) "$(DESTDIR)$(sugardir)" + @list='$(sugar_PYTHON)'; dlist=; list2=; test -n "$(sugardir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then b=; else b="$(srcdir)/"; fi; \ + if test -f $$b$$p; then \ + $(am__strip_dir) \ + dlist="$$dlist $$f"; \ + list2="$$list2 $$b$$p"; \ + else :; fi; \ + done; \ + for file in $$list2; do echo $$file; done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(sugardir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(sugardir)" || exit $$?; \ + done || exit $$?; \ + if test -n "$$dlist"; then \ + $(am__py_compile) --destdir "$(DESTDIR)" \ + --basedir "$(sugardir)" $$dlist; \ + else :; fi + +uninstall-sugarPYTHON: + @$(NORMAL_UNINSTALL) + @list='$(sugar_PYTHON)'; test -n "$(sugardir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + test -n "$$files" || exit 0; \ + dir='$(DESTDIR)$(sugardir)'; \ + filesc=`echo "$$files" | sed 's|$$|c|'`; \ + fileso=`echo "$$files" | sed 's|$$|o|'`; \ + st=0; \ + for files in "$$files" "$$filesc" "$$fileso"; do \ + $(am__uninstall_files_from_dir) || st=$$?; \ + done; \ + exit $$st +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: + for dir in "$(DESTDIR)$(sugardir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-sugarPYTHON + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-sugarPYTHON + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic distclean \ + distclean-generic distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip install-sugarPYTHON installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-generic pdf pdf-am ps ps-am uninstall \ + uninstall-am uninstall-sugarPYTHON + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/src/jarabe/view/__init__.py b/src/jarabe/view/__init__.py new file mode 100644 index 0000000..85f6a24 --- /dev/null +++ b/src/jarabe/view/__init__.py @@ -0,0 +1,15 @@ +# Copyright (C) 2006-2007, Red Hat, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/src/jarabe/view/buddyicon.py b/src/jarabe/view/buddyicon.py new file mode 100644 index 0000000..e0e8b3f --- /dev/null +++ b/src/jarabe/view/buddyicon.py @@ -0,0 +1,65 @@ +# Copyright (C) 2006-2007 Red Hat, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +from sugar.graphics.icon import CanvasIcon +from sugar.graphics import style + +from jarabe.view.buddymenu import BuddyMenu + +_FILTERED_ALPHA = 0.33 + + +class BuddyIcon(CanvasIcon): + def __init__(self, buddy, size=style.STANDARD_ICON_SIZE): + CanvasIcon.__init__(self, icon_name='computer-xo', size=size) + + self._filtered = False + self._buddy = buddy + self._buddy.connect('notify::present', self.__buddy_notify_present_cb) + self._buddy.connect('notify::color', self.__buddy_notify_color_cb) + + self.palette_invoker.cache_palette = False + + self._update_color() + + def create_palette(self): + return BuddyMenu(self._buddy) + + def __buddy_notify_present_cb(self, buddy, pspec): + # Update the icon's color when the buddy comes and goes + self._update_color() + + def __buddy_notify_color_cb(self, buddy, pspec): + self._update_color() + + def _update_color(self): + # keep the icon in the palette in sync with the view + palette = self.get_palette() + self.props.xo_color = self._buddy.get_color() + if self._filtered: + self.alpha = _FILTERED_ALPHA + if palette is not None: + palette.props.icon.props.stroke_color = self.props.stroke_color + palette.props.icon.props.fill_color = self.props.fill_color + else: + self.alpha = 1.0 + if palette is not None: + palette.props.icon.props.xo_color = self._buddy.get_color() + + def set_filter(self, query): + self._filtered = (self._buddy.get_nick().lower().find(query) == -1) \ + and not self._buddy.is_owner() + self._update_color() diff --git a/src/jarabe/view/buddymenu.py b/src/jarabe/view/buddymenu.py new file mode 100644 index 0000000..de5a772 --- /dev/null +++ b/src/jarabe/view/buddymenu.py @@ -0,0 +1,180 @@ +# Copyright (C) 2006-2007 Red Hat, Inc. +# Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import logging +from gettext import gettext as _ + +import gtk +import gconf +import glib +import dbus + +from sugar.graphics.palette import Palette +from sugar.graphics.menuitem import MenuItem +from sugar.graphics.icon import Icon + +from jarabe.model import shell +from jarabe.model import friends +from jarabe.model.session import get_session_manager +from jarabe.controlpanel.gui import ControlPanel +import jarabe.desktop.homewindow + + +class BuddyMenu(Palette): + def __init__(self, buddy): + self._buddy = buddy + + buddy_icon = Icon(icon_name='computer-xo', + xo_color=buddy.get_color(), + icon_size=gtk.ICON_SIZE_LARGE_TOOLBAR) + nick = buddy.get_nick() + Palette.__init__(self, None, + primary_text=glib.markup_escape_text(nick), + icon=buddy_icon) + self._invite_menu = None + self._active_activity_changed_hid = None + self.connect('destroy', self.__destroy_cb) + + self._buddy.connect('notify::nick', self.__buddy_notify_nick_cb) + + if buddy.is_owner(): + self._add_my_items() + else: + self._add_buddy_items() + + def __destroy_cb(self, menu): + if self._active_activity_changed_hid is not None: + home_model = shell.get_model() + home_model.disconnect(self._active_activity_changed_hid) + self._buddy.disconnect_by_func(self.__buddy_notify_nick_cb) + + def _add_buddy_items(self): + if friends.get_model().has_buddy(self._buddy): + menu_item = MenuItem(_('Remove friend'), 'list-remove') + menu_item.connect('activate', self._remove_friend_cb) + else: + menu_item = MenuItem(_('Make friend'), 'list-add') + menu_item.connect('activate', self._make_friend_cb) + + self.menu.append(menu_item) + menu_item.show() + + self._invite_menu = MenuItem('') + self._invite_menu.connect('activate', self._invite_friend_cb) + self.menu.append(self._invite_menu) + + home_model = shell.get_model() + self._active_activity_changed_hid = home_model.connect( + 'active-activity-changed', self._cur_activity_changed_cb) + activity = home_model.get_active_activity() + self._update_invite_menu(activity) + + def _add_my_items(self): + item = MenuItem(_('Shutdown'), 'system-shutdown') + item.connect('activate', self.__shutdown_activate_cb) + self.menu.append(item) + item.show() + + client = gconf.client_get_default() + + if client.get_bool('/desktop/sugar/show_restart'): + item = MenuItem(_('Restart'), 'system-restart') + item.connect('activate', self.__reboot_activate_cb) + self.menu.append(item) + item.show() + + if client.get_bool('/desktop/sugar/show_logout'): + item = MenuItem(_('Logout'), 'system-logout') + item.connect('activate', self.__logout_activate_cb) + self.menu.append(item) + item.show() + + item = MenuItem(_('My Settings'), 'preferences-system') + item.connect('activate', self.__controlpanel_activate_cb) + self.menu.append(item) + item.show() + + def _quit(self, action): + home_window = jarabe.desktop.homewindow.get_instance() + home_window.busy_during_delayed_action(action) + + def __logout_activate_cb(self, menu_item): + self._quit(get_session_manager().logout) + + def __reboot_activate_cb(self, menu_item): + self._quit(get_session_manager().reboot) + + def __shutdown_activate_cb(self, menu_item): + self._quit(get_session_manager().shutdown) + + def __controlpanel_activate_cb(self, menu_item): + panel = ControlPanel() + panel.set_transient_for(self.get_toplevel()) + panel.show() + + def _update_invite_menu(self, activity): + buddy_activity = self._buddy.props.current_activity + if buddy_activity is not None: + buddy_activity_id = buddy_activity.activity_id + else: + buddy_activity_id = None + + if activity is None or activity.is_journal() or \ + activity.get_activity_id() == buddy_activity_id: + self._invite_menu.hide() + else: + title = activity.get_title() + label = self._invite_menu.get_children()[0] + label.set_text(_('Invite to %s') % title) + + icon = Icon(file=activity.get_icon_path()) + icon.props.xo_color = activity.get_icon_color() + self._invite_menu.set_image(icon) + icon.show() + + self._invite_menu.show() + + def _cur_activity_changed_cb(self, home_model, activity_model): + self._update_invite_menu(activity_model) + + def __buddy_notify_nick_cb(self, buddy, pspec): + self.set_primary_text(glib.markup_escape_text(buddy.props.nick)) + + def _make_friend_cb(self, menuitem): + friends.get_model().make_friend(self._buddy) + + def _remove_friend_cb(self, menuitem): + friends.get_model().remove(self._buddy) + + def _invite_friend_cb(self, menuitem): + activity = shell.get_model().get_active_activity() + service = activity.get_service() + if service: + try: + service.InviteContact(self._buddy.props.account, + self._buddy.props.contact_id) + except dbus.DBusException, e: + expected_exceptions = [ + 'org.freedesktop.DBus.Error.UnknownMethod', + 'org.freedesktop.DBus.Python.NotImplementedError'] + if e.get_dbus_name() in expected_exceptions: + logging.warning('Trying deprecated Activity.Invite') + service.Invite(self._buddy.props.key) + else: + raise + else: + logging.error('Invite failed, activity service not ') diff --git a/src/jarabe/view/customizebundle.py b/src/jarabe/view/customizebundle.py new file mode 100644 index 0000000..42da1b3 --- /dev/null +++ b/src/jarabe/view/customizebundle.py @@ -0,0 +1,217 @@ +# Copyright (C) 2011 Walter Bender +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import os +import glob +import hashlib + +import gtk + +from sugar import profile +from sugar.activity import bundlebuilder +from sugar.datastore import datastore +from sugar.env import get_user_activities_path + +import logging +_logger = logging.getLogger('ViewSource') + + +BADGE_SUBPATH = 'emblems/emblem-view-source.svg' +BADGE_TRANSFORM = ' <g transform="matrix(0.45,0,0,0.45,32,32)">\n' +ICON_TRANSFORM = ' <g transform="matrix(1.0,0,0,1.0,0,0)">\n' +XML_HEADER = '<?xml version="1.0" ?> \ +<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" \ +"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [\n\ +<!ENTITY stroke_color "#010101">\n\ +<!ENTITY fill_color "#FFFFFF">\n]>\n' +SVG_START = '<svg enable-background="new 0 0 55 55" height="55px" \ +version="1.1" viewBox="0 0 55 55" width="55px" x="0px" xml:space="preserve" \ +xmlns="http://www.w3.org/2000/svg" \ +xmlns:xlink="http://www.w3.org/1999/xlink" y="0px">\n' +SVG_END = '</svg>\n' + + +def generate_unique_id(): + """Generate an id based on the user's nick name and their public key + (Based on schema used by IRC activity). + + """ + nick = profile.get_nick_name() + pubkey = profile.get_pubkey() + m = hashlib.sha1() + m.update(pubkey) + hexhash = m.hexdigest() + + nick_letters = "".join([x for x in nick if x.isalpha()]) + + if not nick_letters: + nick_letters = 'XO' + + return nick_letters + '_' + hexhash[:4] + + +def generate_bundle(nick, new_basename): + """Generate a new .xo bundle for the activity and copy it into the + Journal. + + """ + new_activity_name = _customize_activity_info( + nick, new_basename) + + user_activities_path = get_user_activities_path() + if os.path.exists(os.path.join(user_activities_path, new_basename, + 'dist')): + for path in glob.glob(os.path.join(user_activities_path, new_basename, + 'dist', '*')): + os.remove(path) + + config = bundlebuilder.Config(source_dir=os.path.join( + user_activities_path, new_basename), + dist_name='%s-1.xo' % (new_activity_name)) + bundlebuilder.cmd_dist_xo(config, None) + + dsobject = datastore.create() + dsobject.metadata['title'] = '%s-1.xo' % (new_activity_name) + dsobject.metadata['mime_type'] = 'application/vnd.olpc-sugar' + dsobject.set_file_path(os.path.join( + user_activities_path, new_basename, 'dist', + '%s-1.xo' % (new_activity_name))) + datastore.write(dsobject) + dsobject.destroy() + + +def _customize_activity_info(nick, new_basename): + """Modify bundle_id in new activity.info file: + (1) change the bundle_id to bundle_id_[NICKNAME]; + (2) change the activity_icon [NICKNAME]-activity-icon.svg; + (3) set activity_version to 1; + (4) modify the activity icon by applying a customize overlay. + + """ + new_activity_name = '' + user_activities_path = get_user_activities_path() + + info_old = open(os.path.join(user_activities_path, new_basename, + 'activity', 'activity.info'), 'r') + info_new = open(os.path.join(user_activities_path, new_basename, + 'activity', 'new_activity.info'), 'w') + + for line in info_old: + if line.find('=') < 0: + info_new.write(line) + continue + name, value = [token.strip() for token in line.split('=', 1)] + if name == 'bundle_id': + new_value = '%s_%s' % (value, nick) + elif name == 'activity_version': + new_value = '1' + elif name == 'icon': + new_value = value + icon_name = value + elif name == 'name': + new_value = '%s_copy_of_%s' % (nick, value) + new_activity_name = new_value + else: + info_new.write(line) + continue + + info_new.write('%s = %s\n' % (name, new_value)) + + info_old.close() + info_new.close() + + os.rename(os.path.join(user_activities_path, new_basename, + 'activity', 'new_activity.info'), + os.path.join(user_activities_path, new_basename, + 'activity', 'activity.info')) + + _create_custom_icon(new_basename, icon_name) + + return new_activity_name + + +def _create_custom_icon(new_basename, icon_name): + """Modify activity icon by overlaying a badge: + (1) Extract the payload from the badge icon; + (2) Add a transform to resize it and position it; + (3) Insert it into the activity icon. + + """ + user_activities_path = get_user_activities_path() + badge_path = None + for path in gtk.icon_theme_get_default().get_search_path(): + if os.path.exists(os.path.join(path, 'sugar', 'scalable', + BADGE_SUBPATH)): + badge_path = path + break + + if badge_path is None: + _logger.debug('%s not found', BADGE_SUBPATH) + return + + badge_fd = open(os.path.join(badge_path, 'sugar', 'scalable', + BADGE_SUBPATH), 'r') + badge_payload = _extract_svg_payload(badge_fd) + badge_fd.close() + + badge_svg = BADGE_TRANSFORM + badge_payload + '\n</g>' + + icon_path = os.path.join(user_activities_path, new_basename, 'activity', + icon_name + '.svg') + icon_fd = open(icon_path, 'r') + icon_payload = _extract_svg_payload(icon_fd) + icon_fd.close() + + icon_svg = ICON_TRANSFORM + icon_payload + '\n</g>' + + tmp_path = os.path.join(user_activities_path, new_basename, 'activity', + 'tmp.svg') + tmp_icon_fd = open(tmp_path, 'w') + tmp_icon_fd.write(XML_HEADER) + tmp_icon_fd.write(SVG_START) + tmp_icon_fd.write(icon_svg) + tmp_icon_fd.write(badge_svg) + tmp_icon_fd.write(SVG_END) + tmp_icon_fd.close() + + os.remove(icon_path) + os.rename(tmp_path, icon_path) + + +def _extract_svg_payload(fd): + """Returns everything between <svg ...> and </svg>""" + payload = '' + looking_for_start_svg_token = True + looking_for_close_token = True + looking_for_end_svg_token = True + for line in fd: + if looking_for_start_svg_token: + if line.find('<svg') < 0: + continue + looking_for_start_svg_token = False + line = line.split('<svg', 1)[1] + if looking_for_close_token: + if line.find('>') < 0: + continue + looking_for_close_token = False + line = line.split('>', 1)[1] + if looking_for_end_svg_token: + if line.find('</svg>') < 0: + payload += line + continue + payload += line.split('</svg>')[0] + break + return payload diff --git a/src/jarabe/view/keyhandler.py b/src/jarabe/view/keyhandler.py new file mode 100644 index 0000000..530da75 --- /dev/null +++ b/src/jarabe/view/keyhandler.py @@ -0,0 +1,216 @@ +# Copyright (C) 2006-2007, Red Hat, Inc. +# Copyright (C) 2009 Simon Schampijer +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import os +import logging + +import dbus +import gtk + +from sugar._sugarext import KeyGrabber + +from jarabe.model import sound +from jarabe.model import shell +from jarabe.model import session +from jarabe.view.tabbinghandler import TabbingHandler +from jarabe.model.shell import ShellModel +from jarabe import config +from jarabe.journal import journalactivity + + +_VOLUME_STEP = sound.VOLUME_STEP +_VOLUME_MAX = 100 +_TABBING_MODIFIER = gtk.gdk.MOD1_MASK + + +_actions_table = { + 'F1': 'zoom_mesh', + 'F2': 'zoom_group', + 'F3': 'zoom_home', + 'F4': 'zoom_activity', + 'F5': 'open_search', + 'F6': 'frame', + 'XF86AudioMute': 'volume_mute', + 'F11': 'volume_down', + 'XF86AudioLowerVolume': 'volume_down', + 'F12': 'volume_up', + 'XF86AudioRaiseVolume': 'volume_up', + '<alt>F11': 'volume_min', + '<alt>F12': 'volume_max', + 'XF86MenuKB': 'frame', + '<alt>Tab': 'next_window', + '<alt><shift>Tab': 'previous_window', + '<alt>Escape': 'close_window', + 'XF86WebCam': 'open_search', +# the following are intended for emulator users + '<alt><shift>f': 'frame', + '<alt><shift>q': 'quit_emulator', + 'XF86Search': 'open_search', + '<alt><shift>o': 'open_search' +} + + +_instance = None + + +class KeyHandler(object): + def __init__(self, frame): + self._frame = frame + self._key_pressed = None + self._keycode_pressed = 0 + self._keystate_pressed = 0 + + self._key_grabber = KeyGrabber() + self._key_grabber.connect('key-pressed', + self._key_pressed_cb) + self._key_grabber.connect('key-released', + self._key_released_cb) + + self._tabbing_handler = TabbingHandler(self._frame, _TABBING_MODIFIER) + + for f in os.listdir(os.path.join(config.ext_path, 'globalkey')): + if f.endswith('.py') and not f.startswith('__'): + module_name = f[:-3] + try: + logging.debug('Loading module %r', module_name) + module = __import__('globalkey.' + module_name, globals(), + locals(), [module_name]) + for key in module.BOUND_KEYS: + if key in _actions_table: + raise ValueError('Key %r is already bound' % key) + _actions_table[key] = module + except Exception: + logging.exception('Exception while loading extension:') + + self._key_grabber.grab_keys(_actions_table.keys()) + + def _change_volume(self, step=None, value=None): + if step is not None: + volume = sound.get_volume() + step + elif value is not None: + volume = value + + volume = min(max(0, volume), _VOLUME_MAX) + + sound.set_volume(volume) + sound.set_muted(volume == 0) + + def handle_previous_window(self, event_time): + self._tabbing_handler.previous_activity(event_time) + + def handle_next_window(self, event_time): + self._tabbing_handler.next_activity(event_time) + + def handle_close_window(self, event_time): + active_activity = shell.get_model().get_active_activity() + if active_activity.is_journal(): + return + + active_activity.get_window().close() + + def handle_zoom_mesh(self, event_time): + shell.get_model().set_zoom_level(ShellModel.ZOOM_MESH, event_time) + + def handle_zoom_group(self, event_time): + shell.get_model().set_zoom_level(ShellModel.ZOOM_GROUP, event_time) + + def handle_zoom_home(self, event_time): + shell.get_model().set_zoom_level(ShellModel.ZOOM_HOME, event_time) + + def handle_zoom_activity(self, event_time): + shell.get_model().set_zoom_level(ShellModel.ZOOM_ACTIVITY, event_time) + + def handle_volume_max(self, event_time): + self._change_volume(value=_VOLUME_MAX) + + def handle_volume_min(self, event_time): + self._change_volume(value=0) + + def handle_volume_mute(self, event_time): + if sound.get_muted() is True: + sound.set_muted(False) + else: + sound.set_muted(True) + + def handle_volume_up(self, event_time): + self._change_volume(step=_VOLUME_STEP) + + def handle_volume_down(self, event_time): + self._change_volume(step=-_VOLUME_STEP) + + def handle_frame(self, event_time): + self._frame.notify_key_press() + + def handle_quit_emulator(self, event_time): + session.get_session_manager().shutdown() + + def handle_open_search(self, event_time): + journalactivity.get_journal().focus_search() + + def _key_pressed_cb(self, grabber, keycode, state, event_time): + key = grabber.get_key(keycode, state) + logging.debug('_key_pressed_cb: %i %i %s', keycode, state, key) + if key is not None: + self._key_pressed = key + self._keycode_pressed = keycode + self._keystate_pressed = state + + action = _actions_table[key] + if self._tabbing_handler.is_tabbing(): + # Only accept window tabbing events, everything else + # cancels the tabbing operation. + if not action in ['next_window', 'previous_window']: + self._tabbing_handler.stop(event_time) + return True + + if hasattr(action, 'handle_key_press'): + action.handle_key_press(key) + elif isinstance(action, basestring): + method = getattr(self, 'handle_' + action) + method(event_time) + else: + raise TypeError('Invalid action %r' % action) + + return True + else: + # If this is not a registered key, then cancel tabbing. + if self._tabbing_handler.is_tabbing(): + if not grabber.is_modifier(keycode): + self._tabbing_handler.stop(event_time) + return True + + return False + + def _key_released_cb(self, grabber, keycode, state, event_time): + logging.debug('_key_released_cb: %i %i', keycode, state) + if self._tabbing_handler.is_tabbing(): + # We stop tabbing and switch to the new window as soon as the + # modifier key is raised again. + if grabber.is_modifier(keycode, mask=_TABBING_MODIFIER): + self._tabbing_handler.stop(event_time) + + return True + return False + + +def setup(frame): + global _instance + + if _instance: + del _instance + + _instance = KeyHandler(frame) diff --git a/src/jarabe/view/launcher.py b/src/jarabe/view/launcher.py new file mode 100644 index 0000000..5c645c4 --- /dev/null +++ b/src/jarabe/view/launcher.py @@ -0,0 +1,172 @@ +# Copyright (C) 2008, Red Hat, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import logging +from gettext import gettext as _ + +import gtk +import gobject + +from sugar import wm +from sugar.graphics import style + +from jarabe.model import shell +from jarabe.view.pulsingicon import PulsingIcon + + +class LaunchWindow(gtk.Window): + + def __init__(self, activity_id, icon_path, icon_color): + gobject.GObject.__init__(self) + + self.props.type_hint = gtk.gdk.WINDOW_TYPE_HINT_NORMAL + self.props.decorated = False + self.modify_bg(gtk.STATE_NORMAL, style.COLOR_WHITE.get_gdk_color()) + + canvas = gtk.VBox() + canvas.show() + self.add(canvas) + + bar_size = gtk.gdk.screen_height() / 5 * 2 + + header = gtk.VBox() + header.set_size_request(-1, bar_size) + header.show() + canvas.pack_start(header, expand=False) + + self._activity_id = activity_id + + self._activity_icon = PulsingIcon(file=icon_path, + pixel_size=style.XLARGE_ICON_SIZE) + self._activity_icon.set_base_color(icon_color) + self._activity_icon.set_zooming(style.SMALL_ICON_SIZE, + style.XLARGE_ICON_SIZE, 10) + self._activity_icon.set_pulsing(True) + self._activity_icon.show() + canvas.pack_start(self._activity_icon) + + footer = gtk.VBox(spacing=style.DEFAULT_SPACING) + footer.set_size_request(-1, bar_size) + footer.show() + canvas.pack_end(footer, expand=False) + + self.error_text = gtk.Label() + self.error_text.props.use_markup = True + footer.pack_start(self.error_text, expand=False) + + button_box = gtk.Alignment(xalign=0.5) + button_box.show() + footer.pack_start(button_box, expand=False) + self.cancel_button = gtk.Button(stock=gtk.STOCK_STOP) + button_box.add(self.cancel_button) + + self.connect('realize', self.__realize_cb) + + screen = gtk.gdk.screen_get_default() + screen.connect('size-changed', self.__size_changed_cb) + + self._home = shell.get_model() + self._home.connect('active-activity-changed', + self.__active_activity_changed_cb) + + self.connect('destroy', self.__destroy_cb) + + self._update_size() + + def show(self): + self.present() + + def _update_size(self): + self.resize(gtk.gdk.screen_width(), gtk.gdk.screen_height()) + + def __realize_cb(self, widget): + wm.set_activity_id(widget.window, str(self._activity_id)) + widget.window.property_change('_SUGAR_WINDOW_TYPE', 'STRING', 8, + gtk.gdk.PROP_MODE_REPLACE, 'launcher') + + def __size_changed_cb(self, screen): + self._update_size() + + def __active_activity_changed_cb(self, model, activity): + if activity.get_activity_id() == self._activity_id: + self._activity_icon.props.paused = False + else: + self._activity_icon.props.paused = True + + def __destroy_cb(self, box): + self._activity_icon.props.pulsing = False + self._home.disconnect_by_func(self.__active_activity_changed_cb) + + +def setup(): + model = shell.get_model() + model.connect('launch-started', __launch_started_cb) + model.connect('launch-failed', __launch_failed_cb) + model.connect('launch-completed', __launch_completed_cb) + + +def add_launcher(activity_id, icon_path, icon_color): + model = shell.get_model() + + if model.get_launcher(activity_id) is not None: + return + + launch_window = LaunchWindow(activity_id, icon_path, icon_color) + launch_window.show() + + model.register_launcher(activity_id, launch_window) + + +def __launch_started_cb(home_model, home_activity): + add_launcher(home_activity.get_activity_id(), + home_activity.get_icon_path(), home_activity.get_icon_color()) + + +def __launch_failed_cb(home_model, home_activity): + activity_id = home_activity.get_activity_id() + launcher = shell.get_model().get_launcher(activity_id) + + if launcher is None: + logging.error('Launcher for %s is missing', activity_id) + else: + launcher.error_text.props.label = _('<b>%s</b> failed to start.') % \ + home_activity.get_activity_name() + launcher.error_text.show() + + launcher.cancel_button.connect('clicked', + __cancel_button_clicked_cb, home_activity) + launcher.cancel_button.show() + + +def __cancel_button_clicked_cb(button, home_activity): + _destroy_launcher(home_activity) + + +def __launch_completed_cb(home_model, home_activity): + _destroy_launcher(home_activity) + + +def _destroy_launcher(home_activity): + activity_id = home_activity.get_activity_id() + + launcher = shell.get_model().get_launcher(activity_id) + if launcher is None: + if not home_activity.is_journal(): + logging.error('Launcher was not registered for %s', activity_id) + return + + shell.get_model().unregister_launcher(activity_id) + launcher.destroy() diff --git a/src/jarabe/view/palettes.py b/src/jarabe/view/palettes.py new file mode 100644 index 0000000..3195c0c --- /dev/null +++ b/src/jarabe/view/palettes.py @@ -0,0 +1,255 @@ +# Copyright (C) 2008 One Laptop Per Child +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import os +import statvfs +from gettext import gettext as _ +import logging + +import gconf +import glib +import gtk + +from sugar import env +from sugar.graphics.palette import Palette +from sugar.graphics.menuitem import MenuItem +from sugar.graphics.icon import Icon +from sugar.graphics import style +from sugar.graphics.xocolor import XoColor +from sugar.activity.i18n import pgettext + +from jarabe.model import shell +from jarabe.view.viewsource import setup_view_source +from jarabe.journal import misc + + +class BasePalette(Palette): + def __init__(self, home_activity): + Palette.__init__(self) + + self._notify_launch_hid = None + + if home_activity.props.launch_status == shell.Activity.LAUNCHING: + self._notify_launch_hid = home_activity.connect( \ + 'notify::launch-status', self.__notify_launch_status_cb) + self.set_primary_text(glib.markup_escape_text(_('Starting...'))) + elif home_activity.props.launch_status == shell.Activity.LAUNCH_FAILED: + self._on_failed_launch() + else: + self.setup_palette() + + def setup_palette(self): + raise NotImplementedError + + def _on_failed_launch(self): + message = _('Activity failed to start') + self.set_primary_text(glib.markup_escape_text(message)) + + def __notify_launch_status_cb(self, home_activity, pspec): + home_activity.disconnect(self._notify_launch_hid) + self._notify_launch_hid = None + if home_activity.props.launch_status == shell.Activity.LAUNCH_FAILED: + self._on_failed_launch() + else: + self.setup_palette() + + +class CurrentActivityPalette(BasePalette): + def __init__(self, home_activity): + self._home_activity = home_activity + BasePalette.__init__(self, home_activity) + + def setup_palette(self): + activity_name = self._home_activity.get_activity_name() + if activity_name: + self.props.primary_text = glib.markup_escape_text(activity_name) + + title = self._home_activity.get_title() + if title and title != activity_name: + self.props.secondary_text = glib.markup_escape_text(title) + + menu_item = MenuItem(_('Resume'), 'activity-start') + menu_item.connect('activate', self.__resume_activate_cb) + self.menu.append(menu_item) + menu_item.show() + + # TODO: share-with, keep + + menu_item = MenuItem(_('View Source'), 'view-source') + # TODO Make this accelerator translatable + menu_item.props.accelerator = '<Alt><Shift>v' + menu_item.connect('activate', self.__view_source__cb) + self.menu.append(menu_item) + menu_item.show() + + separator = gtk.SeparatorMenuItem() + self.menu.append(separator) + separator.show() + + menu_item = MenuItem(_('Stop'), 'activity-stop') + menu_item.connect('activate', self.__stop_activate_cb) + self.menu.append(menu_item) + menu_item.show() + + def __resume_activate_cb(self, menu_item): + self._home_activity.get_window().activate(gtk.get_current_event_time()) + + def __view_source__cb(self, menu_item): + setup_view_source(self._home_activity) + shell_model = shell.get_model() + if self._home_activity is not shell_model.get_active_activity(): + self._home_activity.get_window().activate( \ + gtk.get_current_event_time()) + + def __stop_activate_cb(self, menu_item): + self._home_activity.get_window().close(1) + + +class ActivityPalette(Palette): + __gtype_name__ = 'SugarActivityPalette' + + def __init__(self, activity_info): + self._activity_info = activity_info + + client = gconf.client_get_default() + color = XoColor(client.get_string('/desktop/sugar/user/color')) + activity_icon = Icon(file=activity_info.get_icon(), + xo_color=color, + icon_size=gtk.ICON_SIZE_LARGE_TOOLBAR) + + name = activity_info.get_name() + Palette.__init__(self, primary_text=glib.markup_escape_text(name), + icon=activity_icon) + + xo_color = XoColor('%s,%s' % (style.COLOR_WHITE.get_svg(), + style.COLOR_TRANSPARENT.get_svg())) + menu_item = MenuItem(text_label=_('Start new'), + file_name=activity_info.get_icon(), + xo_color=xo_color) + menu_item.connect('activate', self.__start_activate_cb) + self.menu.append(menu_item) + menu_item.show() + + # TODO: start-with + + def __start_activate_cb(self, menu_item): + self.popdown(immediate=True) + misc.launch(self._activity_info) + + +class JournalPalette(BasePalette): + def __init__(self, home_activity): + self._home_activity = home_activity + self._progress_bar = None + self._free_space_label = None + + BasePalette.__init__(self, home_activity) + + def setup_palette(self): + title = self._home_activity.get_title() + self.set_primary_text(glib.markup_escape_text(title)) + + vbox = gtk.VBox() + self.set_content(vbox) + vbox.show() + + self._progress_bar = gtk.ProgressBar() + vbox.add(self._progress_bar) + self._progress_bar.show() + + self._free_space_label = gtk.Label() + self._free_space_label.set_alignment(0.5, 0.5) + vbox.add(self._free_space_label) + self._free_space_label.show() + + self.connect('popup', self.__popup_cb) + + menu_item = MenuItem(_('Show contents')) + + icon = Icon(file=self._home_activity.get_icon_path(), + icon_size=gtk.ICON_SIZE_MENU, + xo_color=self._home_activity.get_icon_color()) + menu_item.set_image(icon) + icon.show() + + menu_item.connect('activate', self.__open_activate_cb) + self.menu.append(menu_item) + menu_item.show() + + def __open_activate_cb(self, menu_item): + self._home_activity.get_window().activate(gtk.get_current_event_time()) + + def __popup_cb(self, palette): + stat = os.statvfs(env.get_profile_path()) + free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL] + total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS] + + fraction = (total_space - free_space) / float(total_space) + self._progress_bar.props.fraction = fraction + self._free_space_label.props.label = _('%(free_space)d MB Free') % \ + {'free_space': free_space / (1024 * 1024)} + + +class VolumePalette(Palette): + def __init__(self, mount): + Palette.__init__(self, label=mount.get_name()) + self._mount = mount + + path = mount.get_root().get_path() + self.props.secondary_text = glib.markup_escape_text(path) + + vbox = gtk.VBox() + self.set_content(vbox) + vbox.show() + + self._progress_bar = gtk.ProgressBar() + vbox.add(self._progress_bar) + self._progress_bar.show() + + self._free_space_label = gtk.Label() + self._free_space_label.set_alignment(0.5, 0.5) + vbox.add(self._free_space_label) + self._free_space_label.show() + + self.connect('popup', self.__popup_cb) + + menu_item = MenuItem(pgettext('Volume', 'Remove')) + + icon = Icon(icon_name='media-eject', icon_size=gtk.ICON_SIZE_MENU) + menu_item.set_image(icon) + icon.show() + + menu_item.connect('activate', self.__unmount_activate_cb) + self.menu.append(menu_item) + menu_item.show() + + def __unmount_activate_cb(self, menu_item): + self._mount.unmount(self.__unmount_cb) + + def __unmount_cb(self, mount, result): + logging.debug('__unmount_cb %r %r', mount, result) + mount.unmount_finish(result) + + def __popup_cb(self, palette): + mount_point = self._mount.get_root().get_path() + stat = os.statvfs(mount_point) + free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL] + total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS] + + fraction = (total_space - free_space) / float(total_space) + self._progress_bar.props.fraction = fraction + self._free_space_label.props.label = _('%(free_space)d MB Free') % \ + {'free_space': free_space / (1024 * 1024)} diff --git a/src/jarabe/view/pulsingicon.py b/src/jarabe/view/pulsingicon.py new file mode 100644 index 0000000..9a98a80 --- /dev/null +++ b/src/jarabe/view/pulsingicon.py @@ -0,0 +1,237 @@ +# Copyright (C) 2008 One Laptop Per Child +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import math + +import gobject + +from sugar.graphics.icon import Icon, CanvasIcon +from sugar.graphics import style + +_INTERVAL = 100 +_STEP = math.pi / 10 # must be a fraction of pi, for clean caching +_MINIMAL_ALPHA_VALUE = 0.33 + + +class Pulser(object): + def __init__(self, icon): + self._pulse_hid = None + self._icon = icon + self._phase = 0 + self._start_scale = 1.0 + self._end_scale = 1.0 + self._zoom_steps = 1 + self._current_zoom_step = 1 + self._current_scale_step = 1 + + def set_zooming(self, start_scale, end_scale, zoom_steps): + """ Set start and end scale and number of steps in zoom animation """ + self._start_scale = start_scale + self._end_scale = end_scale + self._zoom_steps = zoom_steps + self._current_scale_step = abs(self._start_scale - self._end_scale) / \ + self._zoom_steps + self._icon.scale = self._start_scale + + def start(self, restart=False): + if restart: + self._phase = 0 + if self._pulse_hid is None: + self._pulse_hid = gobject.timeout_add(_INTERVAL, self.__pulse_cb) + if self._start_scale != self._end_scale: + self._icon.scale = self._start_scale + \ + self._current_scale_step * self._current_zoom_step + + def stop(self): + if self._pulse_hid is not None: + gobject.source_remove(self._pulse_hid) + self._pulse_hid = None + self._icon.xo_color = self._icon.get_base_color() + self._phase = 0 + self._icon.alpha = 1.0 + + def update(self): + self._icon.xo_color = self._icon.base_color + self._icon.alpha = _MINIMAL_ALPHA_VALUE + \ + (1 - _MINIMAL_ALPHA_VALUE) * (math.cos(self._phase) + 1) / 2 + + def __pulse_cb(self): + self._phase += _STEP + if self._current_zoom_step <= self._zoom_steps and \ + self._start_scale != self._end_scale: + self._icon.scale = self._start_scale + \ + self._current_scale_step * self._current_zoom_step + self._current_zoom_step += 1 + self.update() + return True + + +class PulsingIcon(Icon): + __gtype_name__ = 'SugarPulsingIcon' + + def __init__(self, **kwargs): + self._pulser = Pulser(self) + self._base_color = None + self._pulse_color = None + self._paused = False + self._pulsing = False + + Icon.__init__(self, **kwargs) + + self._palette = None + self.connect('destroy', self.__destroy_cb) + + def set_pulse_color(self, pulse_color): + self._pulse_color = pulse_color + self._pulser.update() + + def get_pulse_color(self): + return self._pulse_color + + pulse_color = gobject.property( + type=object, getter=get_pulse_color, setter=set_pulse_color) + + def set_base_color(self, base_color): + self._base_color = base_color + self._pulser.update() + + def get_base_color(self): + return self._base_color + + def set_zooming(self, start_size=style.SMALL_ICON_SIZE, + end_size=style.XLARGE_ICON_SIZE, + zoom_steps=10): + if start_size > end_size: + start_scale = 1.0 + end_scale = float(end_size) / start_size + else: + start_scale = float(start_size) / end_size + end_scale = 1.0 + self._pulser.set_zooming(start_scale, end_scale, zoom_steps) + + base_color = gobject.property( + type=object, getter=get_base_color, setter=set_base_color) + + def set_paused(self, paused): + self._paused = paused + + if self._paused: + self._pulser.stop() + else: + self._pulser.start(restart=False) + + def get_paused(self): + return self._paused + + paused = gobject.property( + type=bool, default=False, getter=get_paused, setter=set_paused) + + def set_pulsing(self, pulsing): + self._pulsing = pulsing + + if self._pulsing: + self._pulser.start(restart=True) + else: + self._pulser.stop() + + def get_pulsing(self): + return self._pulsing + + pulsing = gobject.property( + type=bool, default=False, getter=get_pulsing, setter=set_pulsing) + + def _get_palette(self): + return self._palette + + def _set_palette(self, palette): + if self._palette is not None: + self._palette.props.invoker = None + self._palette = palette + + palette = property(_get_palette, _set_palette) + + def __destroy_cb(self, icon): + self._pulser.stop() + if self._palette is not None: + self._palette.destroy() + + +class CanvasPulsingIcon(CanvasIcon): + __gtype_name__ = 'SugarCanvasPulsingIcon' + + def __init__(self, **kwargs): + self._pulser = Pulser(self) + self._base_color = None + self._pulse_color = None + self._paused = False + self._pulsing = False + + CanvasIcon.__init__(self, **kwargs) + + self.connect('destroy', self.__destroy_cb) + + def __destroy_cb(self, box): + self._pulser.stop() + + def set_pulse_color(self, pulse_color): + self._pulse_color = pulse_color + self._pulser.update() + + def get_pulse_color(self): + return self._pulse_color + + pulse_color = gobject.property( + type=object, getter=get_pulse_color, setter=set_pulse_color) + + def set_base_color(self, base_color): + self._base_color = base_color + self._pulser.update() + + def get_base_color(self): + return self._base_color + + base_color = gobject.property( + type=object, getter=get_base_color, setter=set_base_color) + + def set_paused(self, paused): + self._paused = paused + + if self._paused: + self._pulser.stop() + elif self._pulsing: + self._pulser.start(restart=False) + + def get_paused(self): + return self._paused + + paused = gobject.property( + type=bool, default=False, getter=get_paused, setter=set_paused) + + def set_pulsing(self, pulsing): + self._pulsing = pulsing + if self._paused: + return + + if self._pulsing: + self._pulser.start(restart=True) + else: + self._pulser.stop() + + def get_pulsing(self): + return self._pulsing + + pulsing = gobject.property( + type=bool, default=False, getter=get_pulsing, setter=set_pulsing) diff --git a/src/jarabe/view/service.py b/src/jarabe/view/service.py new file mode 100644 index 0000000..29e46b2 --- /dev/null +++ b/src/jarabe/view/service.py @@ -0,0 +1,90 @@ +# Copyright (C) 2006-2007 Red Hat, Inc. +# Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +"""D-bus service providing access to the shell's functionality""" + +import dbus +import gtk + +from jarabe.model import shell +from jarabe.model import bundleregistry + + +_DBUS_SERVICE = 'org.laptop.Shell' +_DBUS_SHELL_IFACE = 'org.laptop.Shell' +_DBUS_PATH = '/org/laptop/Shell' + + +class UIService(dbus.service.Object): + """Provides d-bus service to script the shell's operations + + Uses a shell_model object to observe events such as changes to: + + * nickname + * colour + * icon + * currently active activity + + and pass the event off to the methods in the dbus signature. + + Key method here at the moment is add_bundle, which is used to + do a run-time registration of a bundle using it's application path. + + XXX At the moment the d-bus service methods do not appear to do + anything other than add_bundle + """ + + def __init__(self): + bus = dbus.SessionBus() + bus_name = dbus.service.BusName(_DBUS_SERVICE, bus=bus) + dbus.service.Object.__init__(self, bus_name, _DBUS_PATH) + + self._shell_model = shell.get_model() + + @dbus.service.method(_DBUS_SHELL_IFACE, + in_signature='s', out_signature='s') + def GetBundlePath(self, bundle_id): + bundle = bundleregistry.get_registry().get_bundle(bundle_id) + if bundle: + return bundle.get_path() + else: + return '' + + @dbus.service.method(_DBUS_SHELL_IFACE, + in_signature='s', out_signature='b') + def ActivateActivity(self, activity_id): + """Switch to the window related to this activity_id and return a + boolean indicating if there is a real (ie. not a launcher window) + activity already open. + """ + activity = self._shell_model.get_activity_by_id(activity_id) + + if activity is not None and activity.get_window() is not None: + activity.get_window().activate(gtk.get_current_event_time()) + return self._shell_model.get_launcher(activity_id) is None + + return False + + @dbus.service.method(_DBUS_SHELL_IFACE, + in_signature='ss', out_signature='') + def NotifyLaunch(self, bundle_id, activity_id): + shell.get_model().notify_launch(activity_id, bundle_id) + + @dbus.service.method(_DBUS_SHELL_IFACE, + in_signature='s', out_signature='') + def NotifyLaunchFailure(self, activity_id): + shell.get_model().notify_launch_failed(activity_id) diff --git a/src/jarabe/view/tabbinghandler.py b/src/jarabe/view/tabbinghandler.py new file mode 100644 index 0000000..0889792 --- /dev/null +++ b/src/jarabe/view/tabbinghandler.py @@ -0,0 +1,149 @@ +# Copyright (C) 2008, Benjamin Berg <benjamin@sipsolutions.net> +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import logging + +import gobject +import gtk + +from jarabe.model import shell + + +_RAISE_DELAY = 250 + + +class TabbingHandler(object): + def __init__(self, frame, modifier): + self._frame = frame + self._tabbing = False + self._modifier = modifier + self._timeout = None + + def _start_tabbing(self): + if not self._tabbing: + logging.debug('Grabing the input.') + + screen = gtk.gdk.screen_get_default() + window = screen.get_root_window() + keyboard_grab_result = gtk.gdk.keyboard_grab(window) + pointer_grab_result = gtk.gdk.pointer_grab(window) + + self._tabbing = (keyboard_grab_result == gtk.gdk.GRAB_SUCCESS and + pointer_grab_result == gtk.gdk.GRAB_SUCCESS) + + # Now test that the modifier is still active to prevent race + # conditions. We also test if one of the grabs failed. + mask = window.get_pointer()[2] + if not self._tabbing or not (mask & self._modifier): + logging.debug('Releasing grabs again.') + + # ungrab keyboard/pointer if the grab was successfull. + if keyboard_grab_result == gtk.gdk.GRAB_SUCCESS: + gtk.gdk.keyboard_ungrab() + if pointer_grab_result == gtk.gdk.GRAB_SUCCESS: + gtk.gdk.pointer_ungrab() + + self._tabbing = False + else: + self._frame.show(self._frame.MODE_NON_INTERACTIVE) + + def __timeout_cb(self, event_time): + self._activate_current(event_time) + self._timeout = None + return False + + def _start_timeout(self, event_time): + self._cancel_timeout() + self._timeout = gobject.timeout_add(_RAISE_DELAY, + lambda: self.__timeout_cb(event_time)) + + def _cancel_timeout(self): + if self._timeout: + gobject.source_remove(self._timeout) + self._timeout = None + + def _activate_current(self, event_time): + home_model = shell.get_model() + activity = home_model.get_tabbing_activity() + if activity and activity.get_window(): + activity.get_window().activate(event_time) + + def next_activity(self, event_time): + if not self._tabbing: + first_switch = True + self._start_tabbing() + else: + first_switch = False + + if self._tabbing: + shell_model = shell.get_model() + zoom_level = shell_model.zoom_level + zoom_activity = (zoom_level == shell.ShellModel.ZOOM_ACTIVITY) + + if not zoom_activity and first_switch: + activity = shell_model.get_active_activity() + else: + activity = shell_model.get_tabbing_activity() + activity = shell_model.get_next_activity(current=activity) + + shell_model.set_tabbing_activity(activity) + self._start_timeout(event_time) + else: + self._activate_next_activity(event_time) + + def previous_activity(self, event_time): + if not self._tabbing: + first_switch = True + self._start_tabbing() + else: + first_switch = False + + if self._tabbing: + shell_model = shell.get_model() + zoom_level = shell_model.zoom_level + zoom_activity = (zoom_level == shell.ShellModel.ZOOM_ACTIVITY) + + if not zoom_activity and first_switch: + activity = shell_model.get_active_activity() + else: + activity = shell_model.get_tabbing_activity() + activity = shell_model.get_previous_activity(current=activity) + + shell_model.set_tabbing_activity(activity) + self._start_timeout(event_time) + else: + self._activate_next_activity(event_time) + + def _activate_next_activity(self, event_time): + next_activity = shell.get_model().get_next_activity() + if next_activity: + next_activity.get_window().activate(event_time) + + def stop(self, event_time): + gtk.gdk.keyboard_ungrab() + gtk.gdk.pointer_ungrab() + self._tabbing = False + + self._frame.hide() + + self._cancel_timeout() + self._activate_current(event_time) + + home_model = shell.get_model() + home_model.set_tabbing_activity(None) + + def is_tabbing(self): + return self._tabbing diff --git a/src/jarabe/view/viewsource.py b/src/jarabe/view/viewsource.py new file mode 100644 index 0000000..1285e69 --- /dev/null +++ b/src/jarabe/view/viewsource.py @@ -0,0 +1,570 @@ +# Copyright (C) 2008 One Laptop Per Child +# Copyright (C) 2009 Tomeu Vizoso, Simon Schampijer +# Copyright (C) 2011 Walter Bender +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import os +import shutil +import sys +import logging +from gettext import gettext as _ + +import gobject +import pango +import gtk +import gtksourceview2 +import dbus +import gconf + +from sugar.graphics import style +from sugar.graphics.icon import Icon +from sugar.graphics.xocolor import XoColor +from sugar.graphics.menuitem import MenuItem +from sugar.graphics.toolbutton import ToolButton +from sugar.graphics.radiotoolbutton import RadioToolButton +from sugar.bundle.activitybundle import ActivityBundle +from sugar.datastore import datastore +from sugar.env import get_user_activities_path +from sugar import mime + +from jarabe.view import customizebundle + +_EXCLUDE_EXTENSIONS = ('.pyc', '.pyo', '.so', '.o', '.a', '.la', '.mo', '~', + '.xo', '.tar', '.bz2', '.zip', '.gz') +_EXCLUDE_NAMES = ['.deps', '.libs'] + +_SOURCE_FONT = pango.FontDescription('Monospace %d' % style.FONT_SIZE) + +_logger = logging.getLogger('ViewSource') +map_activity_to_window = {} + + +def setup_view_source(activity): + service = activity.get_service() + if service is not None: + try: + service.HandleViewSource() + return + except dbus.DBusException, e: + expected_exceptions = ['org.freedesktop.DBus.Error.UnknownMethod', + 'org.freedesktop.DBus.Python.NotImplementedError'] + if e.get_dbus_name() not in expected_exceptions: + logging.exception('Exception occured in HandleViewSource():') + except Exception: + logging.exception('Exception occured in HandleViewSource():') + + window_xid = activity.get_xid() + if window_xid is None: + _logger.error('Activity without a window xid') + return + + bundle_path = activity.get_bundle_path() + + if window_xid in map_activity_to_window: + _logger.debug('Viewsource window already open for %s %s', window_xid, + bundle_path) + return + + document_path = None + if service is not None: + try: + document_path = service.GetDocumentPath() + except dbus.DBusException, e: + expected_exceptions = ['org.freedesktop.DBus.Error.UnknownMethod', + 'org.freedesktop.DBus.Python.NotImplementedError'] + if e.get_dbus_name() not in expected_exceptions: + logging.exception('Exception occured in GetDocumentPath():') + except Exception: + logging.exception('Exception occured in GetDocumentPath():') + + if bundle_path is None and document_path is None: + _logger.debug('Activity without bundle_path nor document_path') + return + + sugar_toolkit_path = None + for path in sys.path: + if path.endswith('site-packages'): + if os.path.exists(os.path.join(path, 'sugar')): + sugar_toolkit_path = os.path.join(path, 'sugar') + break + + view_source = ViewSource(window_xid, bundle_path, document_path, + sugar_toolkit_path, activity.get_title()) + map_activity_to_window[window_xid] = view_source + view_source.show() + + +class ViewSource(gtk.Window): + __gtype_name__ = 'SugarViewSource' + + def __init__(self, window_xid, bundle_path, document_path, + sugar_toolkit_path, title): + gtk.Window.__init__(self) + + _logger.debug('ViewSource paths: %r %r %r', bundle_path, + document_path, sugar_toolkit_path) + + self.set_decorated(False) + self.set_position(gtk.WIN_POS_CENTER_ALWAYS) + self.set_border_width(style.LINE_WIDTH) + + width = gtk.gdk.screen_width() - style.GRID_CELL_SIZE * 2 + height = gtk.gdk.screen_height() - style.GRID_CELL_SIZE * 2 + self.set_size_request(width, height) + + self._parent_window_xid = window_xid + self._sugar_toolkit_path = sugar_toolkit_path + + self.connect('realize', self.__realize_cb) + self.connect('destroy', self.__destroy_cb, document_path) + self.connect('key-press-event', self.__key_press_event_cb) + + vbox = gtk.VBox() + self.add(vbox) + vbox.show() + + toolbar = Toolbar(title, bundle_path, document_path, + sugar_toolkit_path) + vbox.pack_start(toolbar, expand=False) + toolbar.connect('stop-clicked', self.__stop_clicked_cb) + toolbar.connect('source-selected', self.__source_selected_cb) + toolbar.show() + + pane = gtk.HPaned() + vbox.pack_start(pane) + pane.show() + + self._selected_bundle_file = None + self._selected_sugar_file = None + file_name = '' + + activity_bundle = ActivityBundle(bundle_path) + command = activity_bundle.get_command() + if len(command.split(' ')) > 1: + name = command.split(' ')[1].split('.')[-1] + tmppath = command.split(' ')[1].replace('.', '/') + file_name = tmppath[0:-(len(name) + 1)] + '.py' + path = os.path.join(activity_bundle.get_path(), file_name) + self._selected_bundle_file = path + + # Split the tree pane into two vertical panes, one of which + # will be hidden + tree_panes = gtk.VPaned() + tree_panes.show() + + self._bundle_source_viewer = FileViewer(bundle_path, file_name) + self._bundle_source_viewer.connect('file-selected', + self.__file_selected_cb) + tree_panes.add1(self._bundle_source_viewer) + self._bundle_source_viewer.show() + + file_name = 'env.py' + self._selected_sugar_file = os.path.join(sugar_toolkit_path, file_name) + self._sugar_source_viewer = FileViewer(sugar_toolkit_path, file_name) + self._sugar_source_viewer.connect('file-selected', + self.__file_selected_cb) + tree_panes.add2(self._sugar_source_viewer) + self._sugar_source_viewer.hide() + + pane.add1(tree_panes) + + self._source_display = SourceDisplay() + pane.add2(self._source_display) + self._source_display.show() + self._source_display.file_path = self._selected_bundle_file + + if document_path is not None: + self._select_source(document_path) + + def _calculate_char_width(self, char_count): + widget = gtk.Label('') + context = widget.get_pango_context() + pango_font = context.load_font(_SOURCE_FONT) + metrics = pango_font.get_metrics() + return pango.PIXELS(metrics.get_approximate_char_width()) * char_count + + def __realize_cb(self, widget): + self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DIALOG) + self.window.set_accept_focus(True) + + parent = gtk.gdk.window_foreign_new(self._parent_window_xid) + self.window.set_transient_for(parent) + + def __stop_clicked_cb(self, widget): + self.destroy() + + def __source_selected_cb(self, widget, path): + self._select_source(path) + + def _select_source(self, path): + if os.path.isfile(path): + _logger.debug('_select_source called with file: %r', path) + self._source_display.file_path = path + self._bundle_source_viewer.hide() + self._sugar_source_viewer.hide() + elif path == self._sugar_toolkit_path: + _logger.debug('_select_source called with sugar toolkit path: %r', + path) + self._sugar_source_viewer.set_path(path) + self._source_display.file_path = self._selected_sugar_file + self._sugar_source_viewer.show() + self._bundle_source_viewer.hide() + else: + _logger.debug('_select_source called with path: %r', path) + self._bundle_source_viewer.set_path(path) + self._source_display.file_path = self._selected_bundle_file + self._bundle_source_viewer.show() + self._sugar_source_viewer.hide() + + def __destroy_cb(self, window, document_path): + del map_activity_to_window[self._parent_window_xid] + if document_path is not None and os.path.exists(document_path): + os.unlink(document_path) + + def __key_press_event_cb(self, window, event): + keyname = gtk.gdk.keyval_name(event.keyval) + if keyname == 'Escape': + self.destroy() + + def __file_selected_cb(self, file_viewer, file_path): + if file_path is not None and os.path.isfile(file_path): + self._source_display.file_path = file_path + if file_viewer == self._bundle_source_viewer: + self._selected_bundle_file = file_path + else: + self._selected_sugar_file = file_path + else: + self._source_display.file_path = None + + +class DocumentButton(RadioToolButton): + __gtype_name__ = 'SugarDocumentButton' + + def __init__(self, file_name, document_path, title, bundle=False): + RadioToolButton.__init__(self) + + self._document_path = document_path + self._title = title + self._jobject = None + + self.props.tooltip = _('Instance Source') + + client = gconf.client_get_default() + self._color = client.get_string('/desktop/sugar/user/color') + icon = Icon(file=file_name, + icon_size=gtk.ICON_SIZE_LARGE_TOOLBAR, + xo_color=XoColor(self._color)) + self.set_icon_widget(icon) + icon.show() + + if bundle: + menu_item = MenuItem(_('Duplicate')) + icon = Icon(icon_name='edit-duplicate', + icon_size=gtk.ICON_SIZE_MENU, + xo_color=XoColor(self._color)) + menu_item.connect('activate', self.__copy_to_home_cb) + else: + menu_item = MenuItem(_('Keep')) + icon = Icon(icon_name='document-save', + icon_size=gtk.ICON_SIZE_MENU, + xo_color=XoColor(self._color)) + menu_item.connect('activate', self.__keep_in_journal_cb) + + menu_item.set_image(icon) + + self.props.palette.menu.append(menu_item) + menu_item.show() + + def __copy_to_home_cb(self, menu_item): + """Make a local copy of the activity bundle in user_activities_path""" + user_activities_path = get_user_activities_path() + nick = customizebundle.generate_unique_id() + new_basename = '%s_copy_of_%s' % ( + nick, os.path.basename(self._document_path)) + if not os.path.exists(os.path.join(user_activities_path, + new_basename)): + shutil.copytree(self._document_path, + os.path.join(user_activities_path, new_basename), + symlinks=True) + customizebundle.generate_bundle(nick, new_basename) + else: + _logger.debug('%s already exists', new_basename) + + def __keep_in_journal_cb(self, menu_item): + mime_type = mime.get_from_file_name(self._document_path) + if mime_type == 'application/octet-stream': + mime_type = mime.get_for_file(self._document_path) + + self._jobject = datastore.create() + title = _('Source') + ': ' + self._title + self._jobject.metadata['title'] = title + self._jobject.metadata['keep'] = '0' + self._jobject.metadata['buddies'] = '' + self._jobject.metadata['preview'] = '' + self._jobject.metadata['icon-color'] = self._color + self._jobject.metadata['mime_type'] = mime_type + self._jobject.metadata['source'] = '1' + self._jobject.file_path = self._document_path + datastore.write(self._jobject, transfer_ownership=True, + reply_handler=self.__internal_save_cb, + error_handler=self.__internal_save_error_cb) + + def __internal_save_cb(self): + _logger.debug('Saved Source object to datastore.') + self._jobject.destroy() + + def __internal_save_error_cb(self, err): + _logger.debug('Error saving Source object to datastore: %s', err) + self._jobject.destroy() + + +class Toolbar(gtk.Toolbar): + __gtype_name__ = 'SugarViewSourceToolbar' + + __gsignals__ = { + 'stop-clicked': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ([])), + 'source-selected': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, + ([str])), + } + + def __init__(self, title, bundle_path, document_path, sugar_toolkit_path): + gtk.Toolbar.__init__(self) + + document_button = None + self.bundle_path = bundle_path + self.sugar_toolkit_path = sugar_toolkit_path + + self._add_separator() + + activity_bundle = ActivityBundle(bundle_path) + file_name = activity_bundle.get_icon() + + if document_path is not None and os.path.exists(document_path): + document_button = DocumentButton(file_name, document_path, title) + document_button.connect('toggled', self.__button_toggled_cb, + document_path) + self.insert(document_button, -1) + document_button.show() + self._add_separator() + + if bundle_path is not None and os.path.exists(bundle_path): + activity_button = DocumentButton(file_name, bundle_path, title, + bundle=True) + icon = Icon(file=file_name, + icon_size=gtk.ICON_SIZE_LARGE_TOOLBAR, + fill_color=style.COLOR_TRANSPARENT.get_svg(), + stroke_color=style.COLOR_WHITE.get_svg()) + activity_button.set_icon_widget(icon) + icon.show() + if document_button is not None: + activity_button.props.group = document_button + activity_button.props.tooltip = _('Activity Bundle Source') + activity_button.connect('toggled', self.__button_toggled_cb, + bundle_path) + self.insert(activity_button, -1) + activity_button.show() + self._add_separator() + + if sugar_toolkit_path is not None: + sugar_button = RadioToolButton() + icon = Icon(icon_name='computer-xo', + icon_size=gtk.ICON_SIZE_LARGE_TOOLBAR, + fill_color=style.COLOR_TRANSPARENT.get_svg(), + stroke_color=style.COLOR_WHITE.get_svg()) + sugar_button.set_icon_widget(icon) + icon.show() + if document_button is not None: + sugar_button.props.group = document_button + else: + sugar_button.props.group = activity_button + sugar_button.props.tooltip = _('Sugar Toolkit Source') + sugar_button.connect('toggled', self.__button_toggled_cb, + sugar_toolkit_path) + self.insert(sugar_button, -1) + sugar_button.show() + self._add_separator() + + self.activity_title_text = _('View source: %s') % title + self.sugar_toolkit_title_text = _('View source: %r') % 'Sugar Toolkit' + self.label = gtk.Label() + self.label.set_markup('<b>%s</b>' % self.activity_title_text) + self.label.set_alignment(0, 0.5) + self._add_widget(self.label) + + self._add_separator(True) + + stop = ToolButton(icon_name='dialog-cancel') + stop.set_tooltip(_('Close')) + stop.connect('clicked', self.__stop_clicked_cb) + self.insert(stop, -1) + stop.show() + + def _add_separator(self, expand=False): + separator = gtk.SeparatorToolItem() + separator.props.draw = False + if expand: + separator.set_expand(True) + else: + separator.set_size_request(style.DEFAULT_SPACING, -1) + self.insert(separator, -1) + separator.show() + + def _add_widget(self, widget, expand=False): + tool_item = gtk.ToolItem() + tool_item.set_expand(expand) + + tool_item.add(widget) + widget.show() + + self.insert(tool_item, -1) + tool_item.show() + + def __stop_clicked_cb(self, button): + self.emit('stop-clicked') + + def __button_toggled_cb(self, button, path): + if button.props.active: + self.emit('source-selected', path) + if path == self.sugar_toolkit_path: + self.label.set_markup('<b>%s</b>' % self.sugar_toolkit_title_text) + else: # Use activity title for either bundle path or document path + self.label.set_markup('<b>%s</b>' % self.activity_title_text) + + +class FileViewer(gtk.ScrolledWindow): + __gtype_name__ = 'SugarFileViewer' + + __gsignals__ = { + 'file-selected': (gobject.SIGNAL_RUN_FIRST, + gobject.TYPE_NONE, + ([str])), + } + + def __init__(self, path, initial_filename): + gtk.ScrolledWindow.__init__(self) + + self.props.hscrollbar_policy = gtk.POLICY_AUTOMATIC + self.props.vscrollbar_policy = gtk.POLICY_AUTOMATIC + self.set_size_request(style.GRID_CELL_SIZE * 3, -1) + + self._path = None + self._initial_filename = initial_filename + + self._tree_view = gtk.TreeView() + self.add(self._tree_view) + self._tree_view.show() + + self._tree_view.props.headers_visible = False + selection = self._tree_view.get_selection() + selection.connect('changed', self.__selection_changed_cb) + + cell = gtk.CellRendererText() + column = gtk.TreeViewColumn() + column.pack_start(cell, True) + column.add_attribute(cell, 'text', 0) + self._tree_view.append_column(column) + self._tree_view.set_search_column(0) + + self.set_path(path) + + def set_path(self, path): + self.emit('file-selected', None) + if self._path == path: + return + + self._path = path + self._tree_view.set_model(gtk.TreeStore(str, str)) + self._model = self._tree_view.get_model() + self._add_dir_to_model(path) + + def _add_dir_to_model(self, dir_path, parent=None): + for f in os.listdir(dir_path): + if f.endswith(_EXCLUDE_EXTENSIONS) or f in _EXCLUDE_NAMES: + continue + + full_path = os.path.join(dir_path, f) + if os.path.isdir(full_path): + new_iter = self._model.append(parent, [f, full_path]) + self._add_dir_to_model(full_path, new_iter) + else: + current_iter = self._model.append(parent, [f, full_path]) + if f == self._initial_filename: + selection = self._tree_view.get_selection() + selection.select_iter(current_iter) + + def __selection_changed_cb(self, selection): + model, tree_iter = selection.get_selected() + if tree_iter is None: + file_path = None + else: + file_path = model.get_value(tree_iter, 1) + self.emit('file-selected', file_path) + + +class SourceDisplay(gtk.ScrolledWindow): + __gtype_name__ = 'SugarSourceDisplay' + + def __init__(self): + gtk.ScrolledWindow.__init__(self) + + self.props.hscrollbar_policy = gtk.POLICY_AUTOMATIC + self.props.vscrollbar_policy = gtk.POLICY_AUTOMATIC + + self._buffer = gtksourceview2.Buffer() + self._buffer.set_highlight_syntax(True) + + self._source_view = gtksourceview2.View(self._buffer) + self._source_view.set_editable(False) + self._source_view.set_cursor_visible(True) + self._source_view.set_show_line_numbers(True) + self._source_view.set_show_right_margin(True) + self._source_view.set_right_margin_position(80) + #self._source_view.set_highlight_current_line(True) #FIXME: Ugly color + self._source_view.modify_font(_SOURCE_FONT) + self.add(self._source_view) + self._source_view.show() + + self._file_path = None + + def _set_file_path(self, file_path): + self._file_path = file_path + + if self._file_path is None: + self._buffer.set_text('') + return + + mime_type = mime.get_for_file(self._file_path) + _logger.debug('Detected mime type: %r', mime_type) + + language_manager = gtksourceview2.language_manager_get_default() + detected_language = None + for language_id in language_manager.get_language_ids(): + language = language_manager.get_language(language_id) + if mime_type in language.get_mime_types(): + detected_language = language + break + + if detected_language is not None: + _logger.debug('Detected language: %r', + detected_language.get_name()) + + self._buffer.set_language(detected_language) + self._buffer.set_text(open(self._file_path, 'r').read()) + + def _get_file_path(self): + return self._file_path + + file_path = property(_get_file_path, _set_file_path) |