quickly-widgets-12.03/0000775000000000000000000000000011727704224011542 5ustar quickly-widgets-12.03/po/0000775000000000000000000000000011727704224012160 5ustar quickly-widgets-12.03/po/quickly-widgets.pot0000664000000000000000000001006411727674640016042 0ustar # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2011-02-03 13:16-0500\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" #: ../quickly/widgets/grid_column.py:762 msgid "yes" msgstr "" #: ../quickly/widgets/web_cam_box.py:123 msgid "Cannot display web cam output. Ignoring play command" msgstr "" #: ../quickly/widgets/web_cam_box.py:159 msgid "/Pictures/" msgstr "" #: ../quickly/widgets/media_player_box.py:169 msgid "" "WARNING: MediaPlayerBox window not realized.\n" " Will try to play anyway, but bad things could happen\n" " if there is video to play" msgstr "" #: ../quickly/widgets/url_fetch_progressbox.py:59 #, python-format msgid "Downloading %s" msgstr "" #: ../quickly/prompts/__init__.py:105 ../quickly/prompts/__init__.py:149 msgid "Input String" msgstr "" #: ../quickly/prompts/__init__.py:105 ../quickly/prompts/__init__.py:149 msgid "Input a String:" msgstr "" #: ../quickly/prompts/__init__.py:172 ../quickly/prompts/__init__.py:220 msgid "Choose Date" msgstr "" #: ../quickly/prompts/__init__.py:172 ../quickly/prompts/__init__.py:220 msgid "Choose a Date:" msgstr "" #: ../quickly/prompts/__init__.py:247 ../quickly/prompts/__init__.py:306 #: ../quickly/prompts/__init__.py:387 msgid "Enter Number" msgstr "" #: ../quickly/prompts/__init__.py:247 ../quickly/prompts/__init__.py:306 #: ../quickly/prompts/__init__.py:387 msgid "Enter an Integer Value:" msgstr "" #: ../quickly/prompts/__init__.py:324 ../quickly/prompts/__init__.py:433 #: ../quickly/prompts/__init__.py:494 msgid "Enter Price" msgstr "" #: ../quickly/prompts/__init__.py:324 ../quickly/prompts/__init__.py:433 #: ../quickly/prompts/__init__.py:494 msgid "Choose a Price:" msgstr "" #: ../quickly/prompts/__init__.py:525 msgid "Choose Yes or No" msgstr "" #: ../quickly/prompts/__init__.py:576 msgid "Choose an option" msgstr "" #: ../quickly/prompts/__init__.py:623 msgid "Warning" msgstr "" #: ../quickly/prompts/__init__.py:642 msgid "Error" msgstr "" #: ../quickly/prompts/__init__.py:662 msgid "Information" msgstr "" #: ../quickly/prompts/__init__.py:726 ../quickly/prompts/__init__.py:871 msgid "Choose an Image" msgstr "" #: ../quickly/prompts/__init__.py:894 msgid "Choose a Directory" msgstr "" #: ../quickly/widgets/asynch_task_progressbox.py:160 msgid "Working" msgstr "" #: ../quickly/widgets/grid_filter.py:113 msgid "M_atch All of the following" msgstr "" #: ../quickly/widgets/grid_filter.py:117 msgid "Match any _of the following" msgstr "" #: ../quickly/widgets/grid_filter.py:403 msgid "contains" msgstr "" #: ../quickly/widgets/grid_filter.py:404 msgid "does not contain" msgstr "" #: ../quickly/widgets/grid_filter.py:405 msgid "starts with" msgstr "" #: ../quickly/widgets/grid_filter.py:406 msgid "ends with" msgstr "" #: ../quickly/widgets/grid_filter.py:440 msgid "has any of these tags" msgstr "" #: ../quickly/widgets/grid_filter.py:441 msgid "has all of these tags" msgstr "" #: ../quickly/widgets/grid_filter.py:442 msgid "does not have one of these tags" msgstr "" #: ../quickly/widgets/grid_filter.py:443 msgid "does not have any of these tags" msgstr "" #: ../quickly/widgets/grid_filter.py:630 msgid "before" msgstr "" #: ../quickly/widgets/grid_filter.py:631 msgid "on or before" msgstr "" #: ../quickly/widgets/grid_filter.py:632 msgid "on" msgstr "" #: ../quickly/widgets/grid_filter.py:633 msgid "on or after" msgstr "" #: ../quickly/widgets/grid_filter.py:634 msgid "after" msgstr "" #: ../quickly/widgets/grid_filter.py:722 msgid "checked" msgstr "" #: ../quickly/widgets/grid_filter.py:723 msgid "not Checked" msgstr "" #: ../quickly/widgets/grid_filter.py:724 msgid "unset" msgstr "" quickly-widgets-12.03/Copyright0000664000000000000000000000133411623512000013416 0ustar # Copyright (C) 2010 Rick Spencer ### BEGIN AUTOMATIC LICENSE GENERATION #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END AUTOMATIC LICENSE GENERATION quickly-widgets-12.03/debian/0000775000000000000000000000000011727704224012764 5ustar quickly-widgets-12.03/debian/compat0000664000000000000000000000000211725471213014157 0ustar 8 quickly-widgets-12.03/debian/copyright0000664000000000000000000000202311623512000014674 0ustar Format: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?op=file&rev=166 Upstream-Name: Quickly Widgets Upstream-Contact: Rick Spencer Source: https://code.launchpad.net/~quickly-committers/quidgets/trunk Files: * Copyright: 2010,2011 Rick Spencer License: GPL-3 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 3 of the License. . 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, see . . On Debian systems, the full text of the GNU General Public License version 3 can be found in the file /usr/share/common-licenses/GPL-3. quickly-widgets-12.03/debian/rules0000775000000000000000000000005511725471213014041 0ustar #!/usr/bin/make -f %: dh $@ --with python2 quickly-widgets-12.03/debian/changelog0000664000000000000000000000507111727703525014644 0ustar quickly-widgets (12.03) precise; urgency=low * Setting editable should not recreate the treeview in DictionaryGrid (LP: #812266) * DictionaryGrid.editable does not work for CheckColumn (LP: #841357) * Quickly Widgets should use GOI (LP: #678225) * debian/control: - Update Dependencies for python-gi -- Michael Terry Tue, 13 Mar 2012 12:54:42 -0400 quickly-widgets (11.08) oneiric; urgency=low * debian/control, debian/compat, debian/rules: - Convert to dh 8 - Convert to dh_python2 - Remove obsolete langpack.make include, causing FTBFS (LP: #835770) * __init__.py: - Remove, it was getting installed to an inappropriately global location (LP: #826062) -- Michael Terry Mon, 29 Aug 2011 15:41:30 -0400 quickly-widgets (11.03.1) natty; urgency=low * New upstream release * debian/copyright: - Update to latest version of spec * debian/source/format: - Use '3.0 (native)' -- Michael Terry Thu, 03 Feb 2011 13:14:25 -0500 quickly-widgets (11.03.0.1) natty; urgency=low * debian/control: - Whoops, should have renamed the package to python-quickly.widgets, not python-quickly-widgets. -- Michael Terry Mon, 06 Dec 2010 15:24:15 -0500 quickly-widgets (11.03) natty; urgency=low * New upstream release * debian/control: - Rename to python-quickly-widgets (LP: #517179) - No-change update to Standards-Version 3.9.1 -- Michael Terry Mon, 06 Dec 2010 14:55:52 -0500 quickly-widgets (10.09) maverick; urgency=low * New upstream release (LP: #637188) -- Didier Roche Mon, 13 Sep 2010 15:52:56 +0200 quickly-widgets (10.04.1) lucid; urgency=low * New bugfix release (LP: #555935) -- Didier Roche Tue, 06 Apr 2010 12:10:58 +0200 quickly-widgets (10.04) lucid; urgency=low * New bugfix release * debian/control: - depends on python-quickly-core (LP: #519633) - bump Standards-Version to 3.8.4 -- Didier Roche Fri, 02 Apr 2010 10:33:44 +0200 quickly-widgets (10.02.2) lucid; urgency=low * Add a dependency on quickly (LP: #517441) -- Brian Murray Fri, 12 Feb 2010 15:52:09 -0800 quickly-widgets (10.02.1) lucid; urgency=low * Remove __init__.py file conflicting with Quickly -- Didier Roche Wed, 03 Feb 2010 15:11:09 -0800 quickly-widgets (10.02) lucid; urgency=low * This is the initial release -- Didier Roche Wed, 03 Feb 2010 11:27:01 -0800 quickly-widgets-12.03/debian/python-quickly.widgets.install0000664000000000000000000000000411725471213021010 0ustar usr quickly-widgets-12.03/debian/source/0000775000000000000000000000000011727704224014264 5ustar quickly-widgets-12.03/debian/source/format0000664000000000000000000000001511623512000015453 0ustar 3.0 (native) quickly-widgets-12.03/debian/control0000664000000000000000000000206011727676676014410 0ustar Source: quickly-widgets Section: python Priority: extra Build-Depends: debhelper (>= 8), python-all (>= 2.6.6-3~), python-distutils-extra (>= 2.10) Maintainer: Ubuntu Developers Standards-Version: 3.9.1 X-Python-Version: >= 2.6 Package: python-quickly.widgets Architecture: all Depends: ${misc:Depends}, ${python:Depends}, python-quickly-core, python-gi, python-testtools, gir1.2-gtk-3.0 Provides: ${python:Provides} Replaces: quickly-widgets (<< 11.03) Conflicts: quickly-widgets (<< 11.03) Description: Library for easing some PyGtk coding tasks Library for easing some PyGtk coding tasks. Note that this is experimental, the API will change, there are bugs. Package: quickly-widgets Architecture: all Section: oldlibs Depends: ${misc:Depends}, python-quickly.widgets Description: Transitional package for python-quickly.widgets This is a transitional package for python-quickly.widgets and can be safely removed after the installation is complete. quickly-widgets-12.03/quickly/0000775000000000000000000000000011727704224013223 5ustar quickly-widgets-12.03/quickly/prompts/0000775000000000000000000000000011727704224014727 5ustar quickly-widgets-12.03/quickly/prompts/__init__.py0000664000000000000000000010452511725471213017044 0ustar ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE #import Gtk #import gobject #import GLib from gi.repository import Gtk from gi.repository import GObject from gi.repository import GLib import os import gettext from gettext import gettext as _ gettext.textdomain('quickly-widgets') #TODO: stop using **kwargs and go back to named arguments so you can pass them from the function to the class class Prompt(Gtk.Dialog): """A base class for some quickly.prompts - creates Ok and Cancel buttons, displays a title and a label. qiuckly.prompts.Prompt is intended for receiving information back from users. If you only want to display a message, use a quickly.prompts.Alert. Useful subclasses and helper functions are provided: quickly.prompts.string() uses quickly.prompts.StringPrompt quickly.prompts.date() uses quickly.prompts.DatePrompt quickly.prompts.integer() uses quickly.prompts.IntegerPrompt quickly.prompts.decimal() uses quickly.prompts.DecimalPrompt quickly.prompts.price() uses quickly.prompts.PricePrompt Using A quickly.prompts.prompt object is not intended to be used without configuring or extending it. Otherwise, it will only display a blank dialog with OK and Cancel buttons and a label. Configuring #add some widgets to the prompt using the #the prompt's content_box member (which is a Gtk.VBox) #These widgets will appear below the label #StringPrompt works similar to this: p = quickly.prompts.Prompt(title,text) entry = Gtk.Entry() entry.set_text(default_value) entry.set_activates_default(True) entry.show() p.content_box.pack_end(entry, True, True, 5) response = p.run() if response = Gtk.ResponseType.OK: my_string = entry.get_text() #A Prompt is a Gtk.Dialog, so you can use Gtk.DialogMembers action_area = p.get_action_area() Extending #Typically you will add widgets to a prompt and override the #get_value function to return the appropriate value entered by the user. #String prompt is implemented as follows: class StringPrompt(Prompt): def __init__(self, title = "Input String", text = "Input a String:", default_value = ""): Prompt.__init__(self, title, text) self._entry = Gtk.Entry() self._entry.set_text(default_value) self._entry.set_activates_default(True) self._entry.show() self.content_box.pack_end(self._entry, True, True, 5) def get_value(self): return self._entry.get_text() """ def __init__(self, title, text): """Creates a Prompt arguments: title - The title for the dialog window text - The string to display in the Prompts label """ Gtk.Dialog.__init__(self, title, None, Gtk.DialogFlags.MODAL,(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK, Gtk.ResponseType.OK)) #self.set_has_separator(False) content_area = self.get_content_area() content_area.set_border_width(5) self.set_default_response(Gtk.ResponseType.OK) self.content_box = Gtk.VBox(False, 10) label = Gtk.Label(text) label.set_line_wrap(True) self.content_box.pack_start(label,False, False, 5) content_area.pack_start(self.content_box,False, False, 5) self.content_box.show() label.show() def string(title = _("Input String"), text = _("Input a String:"), default_value = ""): """string - prompts to enter a string via a dialog box. aguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - a string to see the entry in the dialog box returns a tuple of (Gtk.DialogResponse, string value) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) """ sp = StringPrompt(title, text, default_value) response = sp.run() val = sp.get_value() sp.destroy() return (response, val) class StringPrompt(Prompt): """A class for receiving a string from a user Using #Collect a string from the user by using the #quickly.prompts.string() helper function reponse, val = string("String select test","String select test") if response == Gtk.ResponseType.OK: my_string = val Configuring #Add widgets to the conent_box member sp = StringPrompt(title, text, default_string) sp.content_box.pack_end(my_additional_widget, False, False, 5) #Modify the _entry member sp._entry.set_max_length(144) Extending A StringPrompt is a Prompt which is Gtk.Dialog """ def __init__(self, title = _("Input String"), text = _("Input a String:"), default_value = ""): """Create a StringPrompt arguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - a string to see the entry in the dialog box """ Prompt.__init__(self, title, text) self._entry = Gtk.Entry() self._entry.set_text(default_value) self._entry.set_activates_default(True) self._entry.show() self.content_box.pack_end(self._entry, True, True, 5) def get_value(self): """get_value - returns the value the user has entered into the Gtk.Entry """ return self._entry.get_text() def date(title = _("Choose Date"), text = _("Choose a Date:"), default_value = None): """date - prompts to enter a date using a calendar via a dialog box. aguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - a tuple in the form of integers for (year,month,day) where month is zero indexed (Jaunary is 0, December is 11) returns a tuple of (Gtk.DialogResponse, tuple) The returnd tuple is in the form of integers for (year,month,day) where month is zero indexed (Jaunary is 0, December is 11) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) """ dp = DatePrompt(title, text, default_value) response = dp.run() val = dp.get_value() dp.destroy() return (response, val) class DatePrompt(Prompt): """A class for receiving a date from a user Using #Collect a date from the user by using the #quickly.prompts.date() helper function reponse, val = date("Date prompt title","Date prompt message") if response == Gtk.ResponseType.OK: my_date = val Configuring #Add widgets to the content_box member dp = DatePrompt(title, text, default_integer) dp.content_box.pack_end(my_additional_widget) #Modify the _calendar member dp._calendar.set_display_options(Gtk.CALENDAR_SHOW_DAY_NAMES) Extending A DatePrompt is a Prompt which is a Gtk.Dialog. """ def __init__(self, title = _("Choose Date"), text = _("Choose a Date:"), default_value = None): """Creates a DatePrompt title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - a tuple in the form of integers for (year,month,day) where month is zero indexed (Jaunary is 0, December is 11) """ Prompt.__init__(self, title, text) self._calendar = Gtk.Calendar() self._calendar.show() self.content_box.pack_end(self._calendar, True, True, 5) if default_value is not None and len(default_value) is 3: year, month, day = default_value self._calendar.select_month(month, year) self._calendar.select_day(day) def get_value(self): """get_value - return the date currently set in the _calendar member A tuple is in the form of integers for (year,month,day) where month is zero indexed (Jaunary is 0, December is 11) """ return self._calendar.get_date() def integer(title = _("Enter Number"), text = _("Enter an Integer Value:"), default_value=0, min_value = -1000000000, max_value=1000000000, step = 1): """integer - prompts to enter an integer using a spinner via a dialog box. arguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - an integer to display by default, should be greater than keyword arguments: the min_value and less then the max_value min_value - the lowest number accepted by the spinner, defaults to -1000000000 step - set the incriments for each click of the spinner buttons, defaults to 1 max_value, the highest number accepted by the spinner, defaults to 1000000000 returns a tuple of (Gtk.DialogResponse, integer) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) """ ip = IntegerPrompt(title,text,default_value, min_value, max_value, step) response = ip.run() val = ip.get_value() ip.destroy() return (response, val) class IntegerPrompt(Prompt): """A Prompt for collecting an integer number value from user. Uses a Gtk.Spinner for data entry. Using #Collect an integer value from the user by using the #quickly.prompts.integer() helper function reponse, val = integer("Integer prompt title","Integer prompt message") if response == Gtk.ResponseType.OK: my_date = val Configuring #Add widgets to the content_box member dp = IntegerPrompt(title, text, default_date) dp.content_box.pack_end(my_additional_widget) #Modify the _spinner member dp._spinner.set_value(20) Extending An IntegerPrompt is a Prompt which is a Gtk.Dialog """ def __init__(self, title=_("Enter Number"), text=_("Enter an Integer Value:"), default_value=0, min_value = -1000000000, max_value=1000000000, step = 1): """Creates an Integer Prompt """ Prompt.__init__(self, title, text) adj = Gtk.Adjustment(default_value,min_value,max_value,step) self._spinner = Gtk.SpinButton() self._spinner.set_adjustment(adj) self._spinner.set_activates_default(True) self._spinner.show() self._spinner.set_numeric(True) self.content_box.pack_end(self._spinner, True, True, 5) def get_value(self): return self._spinner.get_value_as_int() def decimal(title=_("Enter Price"), text=_("Choose a Price:"), default_value=0, min_value=-1000000000, max_value=1000000000, step=1,digits=20): """decimal - prompts to enter a number that inlcudes decimal places using a spinner via a dialog box. aguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog keyword arguments: default_value - an integer to display by default, should be greater than the min_value and less then the max_value min_value - the lowest number accepted by the spinner, defaults to -1000000000 step - set the incriments for each click of the spinner buttons, defaults to 1 max_value, the highest number accepted by the spinner, defaults to 1000000000 digits - the number of decimal places to include, defaults to 20 supports a maximum of 20 decimal places. Values great than 20 will be converted to 20, and values less than 0 will be converted to 0 returns a tuple of (Gtk.DialogResponse, number) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) """ dp = DecimalPrompt(title, text, default_value, min_value, max_value, step, digits) response = dp.run() val = dp.get_value() dp.destroy() return (response, val) class DecimalPrompt(Prompt): """A Prompt for collecting a decimal number value from user. Uses a Gtk.Spinner for data entry. Using #Collect a number from the user by using the #quickly.prompts.decimal() helper function reponse, val = decimal("Decimal prompt title","Decimal prompt message") if response == Gtk.ResponseType.OK: my_decimal = val Configuring #Add widgets to the content_box member dp = DecimalPrompt(title, text, default_number) dp.content_box.pack_end(my_additional_widget) #Modify the _spinner member dp._spinner.set_value(20.0) Extending An DecimalPrompt is a Prompt which is a Gtk.Dialog """ def __init__(self, title=_("Enter Number"), text=_("Enter an Integer Value:"), default_value=0, min_value=-1000000000, max_value=1000000000, step=1, digits=20): """Creates a DecimalPrompt arguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - an integer to display by default, should be greater than keyword arguments: default_value - an integer to display by default, should be greater than the min_value and less then the max_value min_value - the lowest number accepted by the spinner, defaults to -1000000000 step - set the incriments for each click of the spinner buttons, defaults to 1 max_value, the highest number accepted by the spinner, defaults to 1000000000 digits - the number of decimal places to include, defaults to 20 supports a maximum of 20 decimal places. Values great than 20 will be converted to 20, and values less than 0 will be converted to 0 returns a tuple of (Gtk.DialogResponse, number) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) """ Prompt.__init__(self, title, text) self._adjustment = Gtk.Adjustment(default_value,min_value,max_value,step) if digits > 20: digits = 20 if digits < 0: digits = 0 self._spinner = Gtk.SpinButton() self._spinner.set_adjustment(self._adjustment) self._spinner.set_digits(digits) self._spinner.set_activates_default(True) self._spinner.show() self._spinner.set_numeric(True) self.content_box.pack_end(self._spinner, True, True, 5) def get_value(self): return self._spinner.get_value() def price(title=_("Enter Price"), text=_("Choose a Price:"), default_value=0, min_value=-1000000000, max_value=1000000000, step=1): """price - prompts to enter a number up to the hundreths place using a spinner via a dialog box. aguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - an integer to display by default, should be greater than keyword arguments: the min_value and less then the max_value min_value - the lowest number accepted by the spinner, defaults to -1000000000 max_value, the highest number accepted by the spinner, defaults to 1000000000 step - set the incriments for each click of the spinner buttons, defaults to 1 returns a tuple of (Gtk.DialogResponse, number) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) """ pp = PricePrompt(title, text, default_value, min_value, max_value, step) response = pp.run() val = pp.get_value() pp.destroy() return (response, val) class PricePrompt(DecimalPrompt): """A Prompt for collecting a decimal number value from the user, formatted with two decimal places appropriate for entering a currence ammount. Uses a Gtk.Spinner for data entry. Using #Collect a number from the user by using the #quickly.prompts.price() helper function reponse, val = price("Price prompt title","Price prompt message") if response == Gtk.ResponseType.OK: my_date = val Configuring #Add widgets to the content_box member pp = PricePrompt(title, text, default_number) pp.content_box.pack_end(my_additional_widget) #Modify the _spinner member pp._spinner.set_value(20.00) Extending An PricePrompt is Decimal Prompt which is a Prompt which is a Gtk.Dialog """ def __init__(self, title=_("Enter Price"), text=_("Choose a Price:"), default_value=0, min_value=-1000000000, max_value=1000000000, step=1): """Creates a DecimalPrompt arguments: title - a string to be the title of the dialog text - a string to provide a prompt for the user within dialog default_value - an integer to display by default, should be greater than keywrod arguments: keyword arguments: the min_value and less then the max_value min_value - the lowest number accepted by the spinner, defaults to -1000000000 max_value, the highest number accepted by the spinner, defaults to 1000000000 step - set the incriments for each click of the spinner buttons, defaults to 1 returns a tuple of (Gtk.DialogResponse, number) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) """ DecimalPrompt.__init__(self,title,text,default_value,min_value, max_value, step) self._spinner.set_digits(2) def yes_no(title = _("Choose Yes or No"), text = "", yes="", no=""): """yes_no - prompts the user to choose between two options, one "yes" and one "no", though typically the button labels should be set as verbs. aguments: title - a string to be the title of the dialog text - a string, typically a question, prompting the user to choose Yes or No yes - a string that is a verb representing the Yes action no - a string that is a verb representing the No action returns a Gtk.DialogResponse Gtk.ResponseType.YES means the user clicked the "YES" button, otherwise Gtk.ResponseType.NO means the user clicked the "NO" button, otherwise the user dismissed the dialogv(Gtk.ResponseType.DELETE_EVENT) """ yn = YesNoPrompt(title,text,yes,no) response = yn.run() yn.destroy() return response class YesNoPrompt(Gtk.Dialog): """A prompt to collect a user choice between two options, one "yes" and one "no", though typically the button labels should be set as verbs. Using #Collect a response from the user using the #quickly.prompts.yes_no() helper function reponse = decimal(title,message,"Do it", "Don't do it") if response == Gtk.ResponseType.YES: yes = True else: yes = False Configuring #Add widgets to the content_box member dp = DecimalPrompt(title, text, default_number) dp.content_box.pack_end(my_additional_widget) #add a widget to the response by creating it and #passing it in with a Gtk.ResponseType.ID dp.add_action_widget(new_widget, response_id) Extending An YesNoPrompt is a Gtk.Dialog """ def __init__(self, title=_("Choose an option"),text="",yes="",no=""): """creaets a YesNoPrompt. aguments: title - a string to be the title of the dialog text - a string, typically a question, prompting the user to choose Yes or No yes - a string that is a verb representing the Yes action no - a string that is a verb representing the No action """ Gtk.Dialog.__init__(self, title, None, Gtk.DialogFlags.MODAL) if no == "": no_button = Gtk.Button(stock=Gtk.STOCK_NO) else: no_button = Gtk.Button(label=no, use_underline=True) self.add_action_widget(no_button,Gtk.ResponseType.NO) no_button.show() if yes == "": yes_button = Gtk.Button(stock=Gtk.STOCK_YES) else: yes_button = Gtk.Button(label=yes, use_underline=True) self.add_action_widget(yes_button,Gtk.ResponseType.YES) yes_button.show() yes_button.set_can_default(True) #self.set_has_separator(False) content_area = self.get_content_area() content_area.set_border_width(5) self.set_default_response(Gtk.ResponseType.YES) self.content_box = Gtk.HBox(False, 10) img = Gtk.Image() img.set_from_stock(Gtk.STOCK_DIALOG_QUESTION,Gtk.IconSize.DIALOG) self.content_box.pack_start(img, False, False, 5) label = Gtk.Label(text) label.set_line_wrap(True) self.content_box.pack_start(label,False, False, 5) content_area.pack_start(self.content_box, False, False, 5) self.content_box.show() label.show() img.show() def warning(title = _("Warning"), text = ""): """warning - displays a warning to the user, includes an appropriate icon and an OK button aguments: title - a string to be the title of the dialog text - a string describing the warning returns a Gtk.DialogResponse Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user dismissed the dialogv(Gtk.ResponseType.DELETE_EVENT) """ w = Alert(title,text,Gtk.STOCK_DIALOG_WARNING) response = w.run() w.destroy() return response def error(title = _("Error"), text = ""): """error - displays an error to the user, includes an appropriate icon and an OK button aguments: title - a string to be the title of the dialog text - a string describing the error returns a Gtk.DialogResponse Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user dismissed the dialogv(Gtk.ResponseType.DELETE_EVENT) """ e = Alert(title,text,Gtk.STOCK_DIALOG_ERROR) response = e.run() e.destroy() return response def info(title = _("Information"), text = ""): """info - displays information to the user, includes an appropriate icon and an OK button aguments: title - a string to be the title of the dialog text - a string providing the information returns a Gtk.DialogResponse Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user dismissed the dialogv(Gtk.ResponseType.DELETE_EVENT) """ i = Alert(title,text,Gtk.STOCK_DIALOG_INFO) response = i.run() i.destroy() return response class Alert(Gtk.Dialog): """Displays an icon, a message, and an OK button to users. Used by quickly.prompts.info(), quickly.prompts.warning(), and quickly.prompts.error(). Using #Display a message to the user using one of the helper functions quickly.prompts.info(title,useful_message) Configuring #Add widgets to the content_box member alert = Alert(title, text, image) alert.content_box.pack_end(my_additional_widget, False, False, 5) #change the image by passing in a stock Gtk image alert.set_image(stock_image) Extending An Alert is a Gtk.Dialog. """ def __init__(self,title="",text="",image=None): Gtk.Dialog.__init__(self, title,None,Gtk.DialogFlags.MODAL,(Gtk.STOCK_OK, Gtk.ResponseType.OK)) #self.set_has_separator(False) content_area = self.get_content_area() content_area.set_border_width(5) self.set_default_response(Gtk.ResponseType.OK) self.content_box = Gtk.HBox(False, 10) label = Gtk.Label(text) label.set_line_wrap(True) self._image = Gtk.Image() self._image.set_from_stock(image,Gtk.IconSize.DIALOG) self.content_box.pack_start(self._image, False, False, 5) self.content_box.pack_end(label,False, False, 5) content_area.pack_start(self.content_box, False, False, 5) self.content_box.show() label.show() self._image.show() def set_image(self, image): self._image.set_from_stock(image,Gtk.IconSize.DIALOG) def save_image_file(title=_("Choose an Image"),path=None): """save_image_file - prompts the user to choose an image file aguments: title - a string to be the title of the dialog path - a string providing a path to a directory where the dialog should start. Defaults to Pictures directory. returns a Gtk.DialogResponse Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user clicked "Cancel" or the userdismissed the dialogv(Gtk.ResponseType.DELETE_EVENT) """ sid = SaveImageDialog(title,path) response = sid.run() value = sid.get_filename() sid.destroy() return (response, value) class ImageDialog(Gtk.FileChooserDialog): """A base class for OpenImageDialog and SaveImageDialog Sets up typical mime types and file name patterns suitable for saving images. This class is not typically used configured or extended directly, but rather through OpenImageDialog and SaveImageDialog. """ def __init__(self, action, button, title="", path=None): """Create an ImageDialog. arguments: action - a file chooser action, either Gtk.FILE_CHOOSER_ACTION_SAVE or Gtk.FILE_CHOOSER_ACTION_OPEN button - a Gtk stock button for the intended action, either Gtk.STOCK_SAVE or Gtk.STOCK_OPEN keyword arguments: title - a title for the dialog, defaults to an empty string path - a directory path to initially open to, defaults to ~/Pictures """ Gtk.FileChooserDialog.__init__(self,title, None, action, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, button, Gtk.ResponseType.OK)) self.set_default_response(Gtk.ResponseType.OK) if path == None: path = GLib.get_user_special_dir(GLib.USER_DIRECTORY_PICTURES) self.set_current_folder(path) self._filter = Gtk.FileFilter() self._filter.set_name("All files") self._filter.add_pattern("*") self.add_filter(self._filter) self._filter = Gtk.FileFilter() self._filter.set_name("Images") self._filter.add_mime_type("image/png") self._filter.add_mime_type("image/jpeg") self._filter.add_mime_type("image/gif") self._filter.add_pattern("*.png") self._filter.add_pattern("*.jpg") self._filter.add_pattern("*.gif") self._filter.add_pattern("*.tif") self._filter.add_pattern("*.xpm") self.add_filter(self._filter) self.set_do_overwrite_confirmation(True) class SaveImageDialog(ImageDialog): """ A dialog to prompt the user for a place to save an image file. Using #Collect a location using the quickly.prompts.save_image_file() #helper function response, path = save_image_file(title) if response == Gtk.ResponseType.OK: save_to_path = path Configuring #Modify the _filter member sid._filter.add_mime_type("image/svg") sid._filter.add_pattern("*.svg") Extending A SaveImageDialog is an ImageDialog which is a Gtk.FileChooserDialog """ def __init__(self, title="Choose File Location", path=None): """Create a SaveImageDialog. keyword arguments: title - a title for the dialog, defaults to an empty string path - a directory path to initially open to, defaults to ~/Pictures """ ImageDialog.__init__(self,Gtk.FileChooserAction.SAVE, Gtk.STOCK_SAVE, title,path) class OpenImageDialog(ImageDialog): """ A dialog to prompt the user for an image to open Using #Collect a location using the quickly.prompts.open_image_file() #helper function response, path = open_image_file(title) if response == Gtk.ResponseType.OK: path_to_image = path Configuring #Modify the _filter member sid._filter.add_mime_type("image/svg") sid._filter.add_pattern("*.svg") Extending A SaveImageDialog is an ImageDialog which is a Gtk.FileChooserDialog """ def __init__(self, title="Choose File Location", path=None): """Create an OpenImageDialog. keyword arguments: title - a title for the dialog, defaults to an empty string path - a directory path to initially open to, defaults to ~/Pictures """ ImageDialog.__init__(self,Gtk.FileChooserAction.OPEN, Gtk.STOCK_OPEN, title,path) def open_image_file(title=_("Choose an Image"),path=None): """open_image_file - prompts the user to choose an image file aguments: title - a string to be the title of the dialog path - a string providing a path to a directory where the dialog should start. Defaults to Pictures directory. returns a tuple of (Gtk.DialogResponse, str) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) The str is the path to the image chosen by the user, if any. """ oid = OpenImageDialog(title,path) response = oid.run() value = oid.get_filename() oid.destroy() return (response, value) def choose_directory(title=_("Choose a Directory"),path=None): """choose_directory - prompts the user to choose an directory aguments: title - a string to be the title of the dialog path - a string providing a path to a directory where the dialog should start. returns a tuple of (Gtk.DialogResponse, str) Gtk.ResponseType.OK means the user clicked the "OK" button, otherwise the user cancelled (Gtk.ResponseType.CANCEL) or dismissed the dialog (Gtk.ResponseType.DELETE_EVENT) The str is the path to the directory chosen by the user, if any. """ dcd = DirectoryChooserDialog(title, path) response = dcd.run() value = dcd.get_filename() dcd.destroy() return (response, value) class DirectoryChooserDialog(Gtk.FileChooserDialog): """A Dialog to prompt the user to choose a directory path. Using #prompt the user to provide a directory path using quickly.prompts.choose_directory(title) Configuring #A DirectoryChooseDialog is a Gtk.FileChooserDialog, so you can #use Gtk.FileChooseDialog members dcd = DirectoryChooserDialog(title) dcd.set_local_only(False) Extending #A DirectoryChooseDialog is a Gtk.FileChooserDialog """ def __init__(self, title, path=None): """Creates a DirectoryChooseDialog arguments: title - A title for the dialog keyword arguments: path - a default location for opening the dialogs """ Gtk.FileChooserDialog.__init__(self, title, None, Gtk.FileChooserAction.SELECT_FOLDER, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) self.set_default_response(Gtk.ResponseType.OK) if path is not None: self.set_current_folder(path) if __name__ == "__main__": """test code to try out the dialogs""" #these don't have return values to test for warning("Warning Prompt","Warning Prompt") info("Information Prompt","Information Prompt") error("Error Prompt","Error Prompt") #the rest of values to test for response, val = choose_directory("directory choose test") if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "selected directory was " + str(val) response, val = open_image_file("image open test") if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "selected locations was " + str(val) response, val = save_image_file("image save test") if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "selected locations was " + str(val) reponse, val = string("String select test","String select test") if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "string was " + str(val) reponse, val = date("Date select test","Date select test") if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "date was " + str(val) reponse, val = integer("Integer select test","Integer select test",default_value=20) if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "integer was " + str(val) reponse, val = decimal("Decimal select test","Decimal select test",default_value=20,digits=5) if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "decimal was " + str(val) reponse, val = price("Price select test","Price select test",default_value=20) if response == Gtk.ResponseType.OK: print "response was OK" else: print "response was not OK" print "price was " + str(val) response = yes_no("Yes/No Test","Yes/No Test", "_Yes Verb","_No Verb") if response == Gtk.ResponseType.YES: print "response was yes" quickly-widgets-12.03/quickly/widgets/0000775000000000000000000000000011727704224014671 5ustar quickly-widgets-12.03/quickly/widgets/press_and_hold_button.py0000664000000000000000000000614411725471710021626 0ustar ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """A Button that fires a tick event as long as the user holds it down. So long as the user is holding down the button, it will fire a tick event every 250 milliseconds by default. Using #create the button and connect to the tick event pah = PressAndHoldButton() pah.connect('tick',__handle_on_tick) def __handle_on_tick(widget, data=None): #do something once on each tick Configuring #Change the timeout period in milliseconds by adjusting the #timeout property pah.timeout = 10000 #set the label as a normal button pah.set_labe("Press and Hold") Extending A PressAndHoldButton is Gtk.Button """ from gi.repository import GObject from gi.repository import Gtk class PressAndHoldButton(Gtk.Button): def __init__(self): """Create a PressAndHoldButton After creating it, you can change the frequency of the tick event by setting timeout property in milliseconds. The default timeout period is 250 milliseconds. """ Gtk.Button.__init__(self) self.timeout = 250 self.connect("pressed",self.__pressed) self.connect("released",self.__released) self.__continue_ticking = True def __pressed(self, widget, data=None): self.__continue_ticking = True widget.emit("tick",self) GObject.timeout_add(self.timeout, self.__tick) def __released(self, widget, data=None): self.__continue_ticking = False def __tick(self, data=None): if self.__continue_ticking: self.emit("tick",self) return self.__continue_ticking __gsignals__ = {'tick' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } def __test_tick(sender, widget, label): """internal method for testing. Do not use. """ label.set_text(str(int(label.get_text()) + 1)) if __name__ == "__main__": """creates a test PressAndHoldButton""" #create and show a test window win = Gtk.Window() win.set_title("Press and Hold Test Window") win.connect("destroy",Gtk.main_quit) win.show() #create a top level container vbox = Gtk.VBox(False, 10) vbox.show() win.add(vbox) button = PressAndHoldButton() button.set_label("Press and hold") button.show() vbox.pack_start(button, False, False, 5) label = Gtk.Label("0") label.show() vbox.pack_end(label, False, False, 5) button.timeout = 10 button.connect("tick",__test_tick, label) Gtk.main() quickly-widgets-12.03/quickly/widgets/conventions.py0000664000000000000000000000316311725471710017612 0ustar ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE from grid_column import StringColumn, CurrencyColumn, CheckColumn from grid_column import IntegerColumn, TagsColumn, DateColumn def get_column(key, index, dictionary_index, editable): if key.lower() == "id": return IntegerColumn(key, index, dictionary_index, editable) elif key.endswith("?"): return CheckColumn(key, index, dictionary_index, editable) elif key.lower().endswith(" price") or key.lower() == "price": return CurrencyColumn(key, index, dictionary_index, editable) elif key.lower() == "tags": return TagsColumn(key, index, dictionary_index, editable) elif key.lower().endswith(" count") or key.lower() == "count": return IntegerColumn(key, index, dictionary_index, editable) elif key.lower().endswith(" date") or key.lower() == "date": return DateColumn(key, index, dictionary_index, editable) else: return StringColumn(key, index, dictionary_index, editable) quickly-widgets-12.03/quickly/widgets/text_editor.py0000664000000000000000000003175011725471710017602 0ustar ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """Module for the TextView widgth wich encapsulates management of TextBuffer and TextIter for common functionality, such as cut, copy, paste, undo, redo, and highlighting of text. Using #create the TextEditor and set the text editor = TextEditor() editor.text = "Text to add to the editor" #use cut, works the same for copy, paste, undo, and redo def __handle_on_cut(self, widget, data=None): self.editor.cut() #add string to highlight self.editor.add_highlight("Ubuntu") self.editor.add_highlight("Quickly") #remove highlights self.editor.clear_highlight("Ubuntu") self.editor.clear_all_highlight() Configuring #Configure as a TextView self.editor.set_wrap_mode(Gtk.WRAP_CHAR) #Access the Gtk.TextBuffer if needed buffer = self.editor.get_buffer() Extending A TextEditor is Gtk.TextView """ try: from gi.repository import Gtk from gi.repository import Gdk import re except: print "couldn't load depencies" class TextEditor( Gtk.TextView ): """TextEditor encapsulates management of TextBuffer and TextIter for common functionality, such as cut, copy, paste, undo, redo, and highlighting of text. """ def __init__(self): """Create a TextEditor """ Gtk.TextView.__init__(self) self.undo_max = None self._highlight_strings = [] found_tag = Gtk.TextTag(name="highlight") found_tag.set_property("background","yellow") self.get_buffer().get_tag_table().add(found_tag) self.insert_event = self.get_buffer().connect("insert-text",self._on_insert) self.delete_event = self.get_buffer().connect("delete-range",self._on_delete) self.change_event = self.get_buffer().connect("changed",self._on_text_changed) self._auto_bullet = None self.auto_bullets = False display = self.get_display() self.clipboard = Gtk.Clipboard.get_for_display(display, Gdk.SELECTION_CLIPBOARD) self.undos = [] self.redos = [] @property def text(self): """text - a string specifying all the text currently in the TextEditor's buffer. This property is read/write. """ start_iter = self.get_buffer().get_iter_at_offset(0) end_iter = self.get_buffer().get_iter_at_offset(-1) return self.get_buffer().get_text(start_iter,end_iter, False) @text.setter def text(self, text): self.get_buffer().set_text(text) def append(self, text): """append: appends text to the end of the textbuffer. arguments: text - a string to add to the buffer. The text will be the last text in the buffer. The insertion cursor will not be moved. """ end_iter = self.get_buffer().get_iter_at_offset(-1) self.get_buffer().insert(end_iter, text) def prepend(self, text): """prepend: appends text to the start of the textbuffer. arguments: text - a string to add to the buffer. The text will be the first text in the buffer. The insertion cursor will not be moved. """ start_iter = self.get_buffer().get_iter_at_offset(0) self.get_buffer().insert(start_iter, text) insert_iter = self.get_buffer().get_iter_at_offset(len(text)-1) self.get_buffer().place_cursor(insert_iter) def cursor_to_end(self): """cursor_to_end: moves the insertion curson to the last position in the buffer. """ end_iter = self.get_buffer().get_iter_at_offset(-1) self.get_buffer().place_cursor(end_iter) def cursor_to_start(self): """cursor_to_start: moves the insertion curson to the first position in the buffer. """ start_iter = self.get_buffer().get_iter_at_offset(0) self.get_buffer().place_cursor(start_iter) def add_highlight(self, text): """add_highlight: add string to be highlighted when entered in the buffer. arguments: text - a string to be highlighted """ if text not in self._highlight_strings: self._highlight_strings.append(text) self._highlight() def clear_highlight(self, text): """clear_highlight: stops a string from being highlighted in the buffer. arguments: text - the string to stop highlighting. If the string is not currently being highlighted, the function will be ignored. """ if text in self._highlight_strings: del(self._highlight_strings[text]) self._highlight() def clear_all_highlights(self): """clear_all_highlight: stops highlighting all strings in the buffer. The TextEditor will forget about all strings specified for highlighting. If no strings are currently set for highlighting, the function will be ignored. """ self._highlight_strings = [] self._highlight() def _highlight(self): """_highlight: internal method to trigger highlighting. Do not call directly. """ start_iter = self.get_buffer().get_iter_at_offset(0) end_iter = self.get_buffer().get_iter_at_offset(-1) text = self.get_buffer().get_text(start_iter,end_iter, False) self.get_buffer().remove_all_tags(start_iter, end_iter) for s in self._highlight_strings: hits = [match.start() for match in re.finditer(re.escape(s), text)] for hit in hits: start_iter = self.get_buffer().get_iter_at_offset(hit) end_iter = self.get_buffer().get_iter_at_offset(hit + len(s)) self.get_buffer().apply_tag_by_name("highlight",start_iter,end_iter) def cut(self, widget=None, data=None): """cut: cut currently selected text and put it on the clipboard. This function can be called as a function, or assigned as a signal handler. """ self.get_buffer().cut_clipboard(self.clipboard, True) def copy(self, widget=None, data=None): """copy: copy currently selected text to the clipboard. This function can be called as a function, or assigned as a signal handler. """ self.get_buffer().copy_clipboard(self.clipboard) def paste(self, widget=None, data=None): """paste: Insert any text currently on the clipboard into the buffer. This function can be called as a function, or assigned as a signal handler. """ self.get_buffer().paste_clipboard(self.clipboard,None,True) def undo(self, widget=None, data=None): """undo: revert (undo) the last action. This function can be called as a function, or assigned as a signal handler. """ if len(self.undos) == 0: return self.get_buffer().disconnect(self.delete_event) self.get_buffer().disconnect(self.insert_event) undo = self.undos[-1] redo = self._do_action(undo) self.redos.append(redo) del(self.undos[-1]) self.insert_event = self.get_buffer().connect("insert-text",self._on_insert) self.delete_event = self.get_buffer().connect("delete-range",self._on_delete) self._highlight() def _do_action(self, action): if action["action"] == "delete": start_iter = self.get_buffer().get_iter_at_offset(action["offset"]) end_iter = self.get_buffer().get_iter_at_offset(action["offset"] + len(action["text"])) self.get_buffer().delete(start_iter, end_iter) action["action"] = "insert" elif action["action"] == "insert": start_iter = self.get_buffer().get_iter_at_offset(action["offset"]) self.get_buffer().insert(start_iter, action["text"]) action["action"] = "delete" return action def redo(self, widget=None, data=None): """redo: revert (undo) the last revert (undo) action. This function can be called as a function, or assigned as a signal handler. """ if len(self.redos) == 0: return self.get_buffer().disconnect(self.delete_event) self.get_buffer().disconnect(self.insert_event) redo = self.redos[-1] undo = self._do_action(redo) self.undos.append(undo) del(self.redos[-1]) self.insert_event = self.get_buffer().connect("insert-text",self._on_insert) self.delete_event = self.get_buffer().connect("delete-range",self._on_delete) self._highlight() def _on_text_changed(self, buff): if self._auto_bullet is not None: self.get_buffer().disconnect(self.change_event) buff.insert_at_cursor(self._auto_bullet) self._auto_bullet = None self.change_event = self.get_buffer().connect("changed",self._on_text_changed) def _on_insert(self, text_buffer, iter, text, length, data=None): """_on_insert: internal function to handle programatically inserted text. Do not call directly. """ self._highlight() cmd = {"action":"delete","offset":iter.get_offset(),"text":text} self._add_undo(cmd) self.redos = [] if text == "\n" and self.auto_bullets: cur_line = iter.get_line() prev_line_iter = self.get_buffer().get_iter_at_line(cur_line) pl_offset = prev_line_iter.get_offset() pl_text = self.get_buffer().get_text(prev_line_iter, iter, False) if pl_text.strip().find("*") == 0: ws = "" if not pl_text.startswith("*"): ws = (pl_text.split("*")[0]) self._auto_bullet = ws + "* " def _on_delete(self, text_buffer, start_iter, end_iter, data=None): """_on_insert: internal function to handle delete text. Do not call directly. """ self._highlight() text = self.get_buffer().get_text(start_iter,end_iter, False) cmd = {"action":"insert","offset":start_iter.get_offset(),"text":text} self._add_undo(cmd) def _add_undo(self, cmd): """internal function to capture current state to add to undo stack. Do not call directly. """ #delete the oldest undo if undo maximum is in effect if self.undo_max is not None and len(self.undos) >= self.undo_max: del(self.undos[0]) self.undos.append(cmd) class TestWindow(Gtk.Window): """For testing and demonstrating AsycnTaskProgressBox. """ def __init__(self): #create a window a VBox to hold the controls Gtk.Window.__init__(self) self.set_title("TextEditor Test Window") windowbox = Gtk.VBox(False, 2) windowbox.show() self.add(windowbox) self.editor = TextEditor() self.editor.show() windowbox.pack_end(self.editor, True, True, 0) self.set_size_request(200,200) self.show() self.maximize() self.connect("destroy", Gtk.main_quit) self.editor.text = "this is some inserted text" self.editor.append("\nLine 3") self.editor.prepend("Line1\n") self.editor.cursor_to_end() self.editor.cursor_to_start() self.editor.add_highlight("his") self.editor.clear_all_highlights() self.editor.add_highlight("some") self.editor.undo_max = 100 self.editor.auto_bullets = True cut_button = Gtk.Button("Cut") cut_button.connect("clicked",self.editor.cut) cut_button.show() windowbox.pack_start(cut_button, False, False, 0) copy_button = Gtk.Button("Copy") copy_button.connect("clicked",self.editor.copy) copy_button.show() windowbox.pack_start(copy_button, False, False, 0) paste_button = Gtk.Button("Paste") paste_button.connect("clicked",self.editor.paste) paste_button.show() windowbox.pack_start(paste_button, False, False, 0) undo_button = Gtk.Button("Undo") undo_button.connect("clicked",self.editor.undo) undo_button.show() windowbox.pack_start(undo_button, False, False, 0) redo_button = Gtk.Button("Redo") redo_button.connect("clicked",self.editor.redo) redo_button.show() windowbox.pack_start(redo_button, False, False, 0) print self.editor.text if __name__== "__main__": test = TestWindow() Gtk.main() quickly-widgets-12.03/quickly/widgets/grid_filter.py0000664000000000000000000007155411727673205017555 0ustar # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """Widgets and Objects for filtering a DictionaryGrid GridFilter is as Gtk.VBox that provides filtering UI for a DictionaryGrid. Provides multiple filters, and choosing between "And" and "Or" filtering. Provides default filters appropriate for each column. GridFilter row is a Gtk.HBox that is a container for displaying FilterCombos. FilterCombos display a filter and handle filtering of rows to display and hide in the associated DictionaryGrid. The GridColumns determine the type of filter to use by default. Using #create a DictionaryGrid and use it to create a GridFilter grid = DictionaryGrid(dictionaries=dicts) grid.show() filt = GridFilter(grid) filt.show() Configuring #Create a custom filter combo and use it for a column #the filter functions should take a stored value and a value to filter against for each row and return True if the results should cause the row to be displayed and False if the row should not be displayed blank_filter = BlankFilterBox() blank_filter.append("=",custom_equals_function ) blank_filter.append("<>",custom_no_equals_function ) filter_hints = {"status":blank_filter} filt = GridFilter(grid, filter_hints) filt.show() Extending A custom filter combo is easiest to create by deriving from BlankFilterBox and using the BlankFilterBox.append function to display new filters. class StringFilterBox( BlankFilterBox ): def __init__(self): BlankFilterBox.__init__(self) self.append("contains",lambda x,y: x.find(y) > -1) self.append("does not contain",lambda x,y: x.find(y) == -1) self.append("starts with",lambda x,y: x.startswith(y)) self.append("ends with",lambda x,y: x.endswith(y)) Filter UI could be created to use widgets other than Gtk.Combo so long as the widget has a get_model function that returns a Gtk.ListStore with filtering functions stored as the last value (column) in the liststore. """ import sys import datetime import gettext from gettext import gettext as _ gettext.textdomain('quickly-widgets') from gi.repository import GObject from gi.repository import Gtk class GridFilter( Gtk.VBox ): """GridFilter: A widget that provides a user interface for filtering a treeview. A GridFilter hosts one ore more GridRows, which in turn host an active filter. """ def __init__(self, grid, filter_hints={} ): """Create a GridFilter for filtering an associated treeview. This class is used by BugsPane. arguments: grid - A DictionaryGrid to filter options arguments: filter_hints - a dictionary of column keys to FilterCombo types to provide custom filtering. """ Gtk.VBox.__init__( self, False, 10 ) self.grid = grid self.store = grid.get_model() self.filter_hints = filter_hints #create the and/or radio buttons radio_box = Gtk.HBox(False,2) radio_box.show() self.pack_start(radio_box, False, False, 0) self.and_button = Gtk.RadioButton.new_with_label_from_widget(None,_("M_atch All of the following")) self.and_button.show() self.and_button.connect("toggled",self.__filter_changed) radio_box.pack_start(self.and_button, False, False, 0) or_button = Gtk.RadioButton.new_with_label_from_widget(self.and_button,_("Match any _of the following")) or_button.show() radio_box.pack_start(or_button, False, False, 0) self.rows = [] self._add_row(self) def _add_row(self, widget, data=None): """_add_row: internal signal handler that receives a request from a FilterRow to add a new row. Sets up and adds the row to the GridFilter. Do not call directly """ #TODO: I suppose this is leaking references to filter rows row = FilterRow(self.grid, len(self.rows) > 0, self.filter_hints ) row.connect('add_row_requested',self._add_row) row.connect('remove_row_requested',self._remove_row) row.connect('refilter_requested',self.__filter_changed) row.show() self.rows.append(row) self.pack_start(row, False, False, 0) def _remove_row(self, widget, data=None): """_remove_row: internal signal handler that receives a request from a FilterRow to remove itself from the GridFilter. Do not call directly """ self.rows.remove(widget) self.remove(widget) self.__filter_changed(self) def __filter_changed(self,widget, data=None): """__filter_changed: internal signal handler that handles requests to reapply the fitlers in the GridFilter's FilterRows. """ filt = self.store.filter_new() sort_mod = Gtk.TreeModelSort(model=filt) filt.set_visible_func(self.__filter_func, data ) filt.refilter() self.grid.set_model(sort_mod) def __filter_func(self, model, iter, data): """filter_func: called for each row in the treeview model in response to a __filter_changed signal. Determines for each row whether it should be visible based on the FilterRows in the GridFilter. Do not call directly """ #determine whether this is an "and" or an "or" filter match_all = self.and_button.get_active() for r in self.rows: rez = r.is_match(iter.copy(),model) #check the result of each filter if match_all: #if it's an "and" filter if not rez: #and if the filter does not match return False #then the row should not be visible else: #but if it's an "or" filter if rez: #and it is a match return True #return that the row should be visible return match_all #all filters match an "and" or none matched an "or" class FilterRow( Gtk.HBox): """FilterRow: A widget that displays a single filter in a GridFilter. Typically, this class will not be used directly, but only via a GridFilter. """ wait_for_input = False def __init__(self, grid, removable=True, filter_hints={}): """Create a FilterRow to be used in a GridFilter. A FitlerRow is comprised of a combo that lists the treeview headings. The combo stores the string to display for the heading, as well as the widget that is used to filter each heading. When the user changes the value in the dropdown, the FilterRow retrieves the correct filter from the combo, and displays that filter to the user. The FilterRow also handles offering UI for the user to add and remove FilterRows for the GridFilter containing it. grid - keyword arguments: removable - True if the row should be able to be removed from the GridFilter Typicall False for the first row. filter_hints - a dictionary of keys mapped to custom filters to apply to the column designated by the key """ Gtk.HBox.__init__( self, False, 10 ) self.store = grid.get_model() self.grid = grid heading_combo_store = Gtk.ListStore(GObject.TYPE_STRING,GObject.TYPE_PYOBJECT,GObject.TYPE_INT) #apply default combos for i, k in enumerate(self.grid.keys): if k in filter_hints: filt_combo = filter_hints[k] else: filt_combo = grid.get_columns()[i].default_filter() column_title = grid.get_columns()[i].get_title() heading_combo_store.append([column_title,filt_combo,i]) filt_combo.connect("changed",self.__filter_changed) filt_combo.show() self.column_combo = Gtk.ComboBox.new_with_model(heading_combo_store) cell = Gtk.CellRendererText() self.column_combo.pack_start(cell, True) self.column_combo.add_attribute(cell, 'text', 0) self.filter_space = Gtk.HBox(False,1) self.filter_space.show() self.column_combo.show() vb = Gtk.VBox(False, 5) vb.show() vb.pack_start(self.column_combo, True, False, 0) self.pack_start(vb,False, False, 0) self.column_combo.connect("changed",self.__column_changed) self.column_combo.set_active(0) self.pack_start(self.filter_space, False, False, 0) button_box = Gtk.HBox(False,2) button_box.show() self.pack_start(button_box,False,False, 0) #add a button that can create a new row in the grid filter add_button = Gtk.Button(stock = Gtk.STOCK_ADD) add_button.show() vb2 = Gtk.VBox(False, 5) vb2.show() vb2.pack_start(add_button, True, False, 0) button_box.pack_start(vb2, False, False, 0) add_button.connect("clicked",lambda x: self.emit('add_row_requested',self) ) #add a button to remove the row if applicable if removable: rm_button = Gtk.Button(stock = Gtk.STOCK_REMOVE) rm_button.show() vb3 = Gtk.VBox(False, 5) vb3.show() vb3.pack_start(rm_button, True, False, 0) rm_button.connect('clicked', lambda x: self.emit("remove_row_requested",self) ) button_box.pack_start(vb3, True, True, 0) __gsignals__ = {'add_row_requested' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), 'remove_row_requested' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), 'refilter_requested' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)) } def __column_changed(self, widget, data = None): """column_changed: internal signal handler for the user changing the combo for the column that they wish to apply the filter to. removes the other filter widgets and replaces them widgets stored in the filter widget. """ if len(self.filter_space.get_children()) > 0: self.filter_space.remove(self.filter_space.get_children()[0]) iter = widget.get_model().get_iter(widget.get_active()) filter_box = widget.get_model().get_value(iter,1) self.filter_space.pack_start(filter_box, False, False, 0) def __filter_changed(self,widget, data=None): """filter_changed: internal signal handler called when the FilterRow has changed. Used to tell the GridFilter to refilter. Only emits if the filter is active (a heading is selected in the combo and the user has entered text in the filter. """ #if not self.wait_for_input: #if self.__get_current_filter_combo().get_active > -1: self.emit('refilter_requested',self) def __get_current_filter_combo(self): """get_current_filter_combo: internal function that retrieves the combobox stored for the filter for the user selected treeview column. """ iter = self.column_combo.get_model().get_iter(self.column_combo.get_active()) return self.column_combo.get_model().get_value(iter,1) def is_match(self, store_iter, model): """is_match: returns true if the filter set in the FilterRow matches the value specified in the column and row. Used to determine whether to hide or show a row. Typically called for each treeview row and each FilterRow in response to a change in one of the FilterRows. arguments: store_iter: the iter pointing the the row in the treeview to test model: the treeview model containing the rows being tested """ col_iter = self.column_combo.get_model().get_iter(self.column_combo.get_active()) filter_widget = self.column_combo.get_model().get_value(col_iter,1) treeview_col = self.column_combo.get_model().get_value(col_iter,2) orig_val = model.get_value(store_iter.copy(), treeview_col) return filter_widget.filter(orig_val) class BlankFilterBox( Gtk.HBox): """BlankFilterBox provides a base class for FilterCombos, as well as an empty combo that can be used without subclassing by calling BlankFilterBox.append """ __gsignals__ = {'changed' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } def __init__(self): """create a BlankFilterBox """ Gtk.HBox.__init__(self,False) self.__combo_store = Gtk.ListStore(GObject.TYPE_STRING,GObject.TYPE_PYOBJECT) self.combo = Gtk.ComboBox.new_with_model(self.__combo_store) cell = Gtk.CellRendererText() self.combo.pack_start(cell, True) self.combo.add_attribute(cell, 'text', 0) self.combo.show() self.combo.connect("changed",self.__changed) self.entry = Gtk.Entry() self.entry.show() self.entry.connect("changed",self.__changed) self.pack_start(self.combo, False, False, 0) self.pack_start(self.entry, True, True, 0) def filter(self, orig_val): if self.combo.get_active() == -1: return True filt_iter = self.combo.get_model().get_iter(self.combo.get_active()) filt_func = self.combo.get_model().get_value(filt_iter,1) target_val = self.entry.get_text() return filt_func(orig_val, self.entry.get_text()) def __changed(self, widget, data=None): self.emit("changed",data) def append(self, text, func): """append: adds a row to the FilterCombo that includes a string to display in the combo, and a function to determine if a row should displayed or hidden by the filter. func should take a value indicated by text, and a value entered by the user in the supplied Gtk.TextEntry, and return True if the row should be displayed or False if it should be hidden. """ self.__combo_store.append([text, func]) class StringFilterBox( BlankFilterBox ): """StringFilterBox: A default string filter class for use in a FilterRow. Lets the user specify if the row should be displayed based on containing, not containing, starting with, or ending with a user specified string. """ def __init__(self): """create a StringFilterBox. """ BlankFilterBox.__init__(self) self.append(_("contains"),self.contains) self.append(_("does not contain"),self.not_contains) self.append(_("starts with"),self.starts_with) self.append(_("ends with"),self.ends_with) def contains(self, orig_val, target_val): if len(self.entry.get_text()) == 0 or orig_val is None: return True return orig_val.find(target_val) > -1 def not_contains(self, orig_val, target_val): if len(target_val) == 0 or orig_val is None: return True return orig_val.find(target_val) == -1 def starts_with(self, orig_val, target_val): if len(target_val) == 0 or orig_val is None: return True return orig_val.startswith(target_val) def ends_with(self, orig_val, target_val): if len(target_val) == 0 or orig_val is None: return True return orig_val.endswith(target_val) class TagsFilterBox( BlankFilterBox ): """TagsFilterBox: A default tag filter class for use in a FilterRow. Lets the user specify if the row should be displayed based on containing a one tag or all tags. Assumes tags are seperated by spaces. """ def __init__(self): BlankFilterBox.__init__(self) self.append(_("has any of these tags"), self._filter_any) self.append(_("has all of these tags"), self._filter_all) self.append(_("does not have one of these tags"), self._filter_not) self.append(_("does not have any of these tags"), self._filter_not_all) def _filter_any(self, orig_val, target_val): """ _filter_any: filter function that hides rows if none of the tags supplied in "bugs_tags_s" are found in the Gtk.TextEntry. Do not call directly """ if len(target_val) == 0: return True tags_on_bug = orig_val.split() tags_in_filter = target_val.split() for tag in tags_in_filter: if tag in tags_on_bug: return True return False def _filter_all(self, orig_val, target_val): """ _filter_any: filter function that hides rows if not all of the tags supplied in "bugs_tags_s" are found in the Gtk.TextEntry. Do not call directly """ if len(target_val) == 0: return True tags_on_bug = orig_val.split() tags_in_filter = self.entry.get_text().split() for tag in tags_in_filter: if tag not in tags_on_bug: return False return True def _filter_not(self, orig_val, target_val): """ _filter_not: filter function that hides rows if one of the tags supplied in "bugs_tags_s" are found in the Gtk.TextEntry. Do not call directly """ if len(target_val) == 0: return True tags_on_bug = orig_val.split() tags_in_filter = target_val.split() for tag in tags_in_filter: if tag not in tags_on_bug: return True return False def _filter_not_all(self, orig_val, target_val): """ _filter_not all: filter function that hides rows if all of the tags supplied in "bugs_tags_s" are found in the Gtk.TextEntry. Do not call directly """ if len(self.entry.get_text()) == 0: return True tags_on_bug = orig_val.split() tags_in_filter = target_val.split() for tag in tags_in_filter: if tag in tags_on_bug: return False return True class IntegerFilterBox( Gtk.HBox ): """ """ __gsignals__ = {'changed' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } def __init__(self): Gtk.HBox.__init__(self, False, 10) self.__combo_store = Gtk.ListStore(GObject.TYPE_STRING,GObject.TYPE_PYOBJECT) self.combo = Gtk.ComboBox.new_with_model(self.__combo_store) cell = Gtk.CellRendererText() self.combo.pack_start(cell, True) self.combo.add_attribute(cell, 'text', 0) self.combo.show() self.combo.connect("changed",self.__changed) adj = Gtk.Adjustment(0,-1000000000,1000000000,1) self.spinner = Gtk.SpinButton.new(adj,1,0) self.spinner.set_activates_default(True) self.spinner.show() self.spinner.set_numeric(True) self.spinner.connect("value-changed",self.__changed) self.pack_start(self.combo, False, False, 0) self.pack_start(self.spinner, True, True, 0) self.__combo_store.append(["=",self._equals]) self.__combo_store.append(["<",self._less_than]) self.__combo_store.append([">",self._greater_than]) self.__combo_store.append(["<=",self._less_than_equals]) self.__combo_store.append([">=",self._greater_than_equals]) def __changed(self, widget, data=None): self.emit("changed",data) def filter(self, orig_val): if self.combo.get_active() == -1: return True filt_iter = self.combo.get_model().get_iter(self.combo.get_active()) filt_func = self.combo.get_model().get_value(filt_iter,1) try: target_val = int(self.spinner.get_value_as_int()) except Exception, inst: print inst return False return filt_func(orig_val, target_val) def _equals(self, orig_val, target_val): if orig_val == "": return False return int(orig_val) == target_val def _less_than(self, orig_val, target_val): if orig_val == "": return False return int(orig_val) < target_val def _greater_than(self, orig_val, target_val): if orig_val == "": return False return int(orig_val) > target_val def _less_than_equals(self, orig_val, target_val): if orig_val == "": return False return int(orig_val) <= target_val def _greater_than_equals(self, orig_val, target_val): if orig_val == "": return False return int(orig_val) >= target_val class DateFilterBox( Gtk.HBox ): """DateFilterCombo: A default date filter class for use in a FilterRow. Lets the user specify if the row should be displayed based on the settings in a date widget. """ __gsignals__ = {'changed' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } def __init__(self): """create a CheckFilterCombo """ Gtk.HBox.__init__(self, False, 10) self.__combo_store = Gtk.ListStore(GObject.TYPE_STRING,GObject.TYPE_PYOBJECT) self.combo = Gtk.ComboBox.new_with_model(self.__combo_store) cell = Gtk.CellRendererText() self.combo.pack_start(cell, False) self.combo.add_attribute(cell, 'text', 0) self.combo.show() self.combo.connect("changed",self.__changed) self.__combo_store.append([ _("before"),self.before ]) self.__combo_store.append([ _("on or before"),self.on_before ]) self.__combo_store.append([ _("on"), self.on_date ]) self.__combo_store.append([ _("on or after"),self.on_after ]) self.__combo_store.append([ _("after"),self.after ]) self.calendar = Gtk.Calendar() self.calendar.show() self.calendar.connect("day-selected", self.__changed) vb = Gtk.VBox(False, 5) vb.show() vb.pack_start(self.combo, True, False, 0) self.pack_start(vb, False, False, 0) self.pack_start(self.calendar, False, False, 0) def before(self, orig_val): stored_date, target_date = self.__get_dates(orig_val, self.calendar.get_date()) if stored_date is None: return False return stored_date < target_date def on_before(self, orig_val): stored_date, target_date = self.__get_dates(orig_val, self.calendar.get_date()) if stored_date is None: return False return stored_date <= target_date def on_date(self, orig_val): stored_date, target_date = self.__get_dates(orig_val, self.calendar.get_date()) if stored_date is None: return False return stored_date == target_date def on_after(self, orig_val): stored_date, target_date = self.__get_dates(orig_val, self.calendar.get_date()) if stored_date is None: return False return stored_date >= target_date def after(self, orig_val): stored_date, target_date = self.__get_dates(orig_val, self.calendar.get_date()) if stored_date is None: return False return stored_date > target_date def __get_dates(self, orig_val, target_date): target_date = self.calendar.get_date() target_date = datetime.date(int(target_date[0]),int(target_date[1] + 1),int(target_date[2])) if orig_val is not None and len(orig_val) > 0: p = orig_val.split("-") stored_date = datetime.date(int(p[0]),int(p[1]),int(p[2])) else: stored_date = None return (stored_date, target_date) def filter(self, orig_val): if self.combo.get_active() == -1: return True filt_iter = self.combo.get_model().get_iter(self.combo.get_active()) filt_func = self.combo.get_model().get_value(filt_iter,1) return filt_func(orig_val) def __changed(self, widget, data=None): self.emit("changed",data) class CheckFilterBox( Gtk.HBox ): """CheckFilterCombo: A default checkbox filter class for use in a FilterRow. Lets the user specify if the row should be displayed based on whether a Checkbox is active, inactive, or not set. """ __gsignals__ = {'changed' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } def __init__(self): """create a CheckFilterCombo """ Gtk.HBox.__init__(self, False, 10) self.__combo_store = Gtk.ListStore(GObject.TYPE_STRING,GObject.TYPE_PYOBJECT) self.combo = Gtk.ComboBox.new_with_model(self.__combo_store) cell = Gtk.CellRendererText() self.combo.pack_start(cell, True) self.combo.add_attribute(cell, 'text', 0) self.combo.show() self.combo.connect("changed",self.__changed) self.__combo_store.append([ _("checked"),self.filter_checked ]) self.__combo_store.append([ _("not Checked"),self.filter_not_checked ]) self.__combo_store.append([ _("unset"), self.filter_unset ]) self.pack_start(self.combo, False, False, 0) def filter(self, orig_val): if self.combo.get_active() == -1: return True filt_iter = self.combo.get_model().get_iter(self.combo.get_active()) filt_func = self.combo.get_model().get_value(filt_iter,1) return filt_func(orig_val) def filter_checked(self, orig_val): return orig_val == 1 def filter_not_checked(self, orig_val): return orig_val == 0 def filter_unset(self, orig_val): return orig_val == -1 def __changed(self, widget, data=None): self.emit("changed",data) class NumericFilterBox( BlankFilterBox ): """NumericFilterCombo: A default number filter class for use in a FilterRow. Lets the user specify if the row should be displayed based on numeric relationships to a number specified by the user. """ def __init__(self): """create a NumericFilterCombo """ BlankFilterBox.__init__( self ) self.append("=",self._equals ) self.append("<",self._less_than ) self.append(">",self._greater_than ) self.append("<=",self._less_than_equals) self.append(">=",self._greater_than_equals ) def _equals(self, orig_val): try: return float(orig_val) == float(self.entry.get_text()) except: return True def _less_than(self, orig_val): try: return float(orig_val) < float(self.entry.get_text()) except: return True def _greater_than(self, orig_val): try: return float(orig_val) > float(self.entry.get_text()) except: return True def _less_than_equals(self, orig_val): try: return float(orig_val) <= float(self.entry.get_text()) except: return True def _greater_than_equals(self, orig_val): try: return float(orig_val) >= float(self.entry.get_text()) except: return True # Test case begins here. def __delete_test(button, grid): grid.remove_selected_rows(delete=True) if __name__ == "__main__": """creates a test DictionaryGrid and GridFilter if called directly""" from dictionary_grid import DictionaryGrid #create and show a test window win = Gtk.Window.new(Gtk.WindowType.TOPLEVEL) win.set_title("CouchGrid Test Window") win.connect("destroy",Gtk.main_quit) win.show() #create a top level container vbox = Gtk.VBox(False, 10) vbox.show() win.add(vbox) #create a test widget with test database values dicts = [{"ID": 0, "key?": True, "tags": "aaa bbb ccc", "string":"aaaaaaa","date":"2010-08-01"}, {"ID": 1, "key?": False, "tags": "bbb ccc ddd", "string":"bbbbbbb","date":"2010-08-01"}, {"ID": 2, "key?": True, "tags": "ccc ddd eee", "string":"cccccccc","date":"2010-09-01"}, {"ID": 3, "key?": False, "tags": "ddd eee fff", "string":"dddddddd","date":"2010-10-01"}, {"ID": 4, "key?": True, "tags": "eee fff ggg", "string":"eeeeeeee","date":"2010-11-01"}] grid = DictionaryGrid(dictionaries=dicts, editable=True) grid.columns["tags"].set_title("modified title") grid.show() hints = {} filt = GridFilter(grid,hints) filt.show() vbox.pack_start(filt, False, False, 0) vbox.pack_end(grid, True, True, 0) delete_button = Gtk.Button("Delete Selected") delete_button.connect("clicked",__delete_test,grid) delete_button.show() vbox.pack_start(delete_button,False, False, 0) Gtk.main() quickly-widgets-12.03/quickly/widgets/dictionary_grid.py0000664000000000000000000004347111727674410020431 0ustar #!/usr/bin/env python # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """A Gtk.TreeView for Dictionaries Displays and persists data in a Gtk.TreeView. Handles the set up of the Gtk.TreeView, Gtk.ListModel, Gtk.TreeViewColumns, and Gtk.CellRenderers. Using #create a dictionary if you don't already have one dicts = [{"test?":True,"price":100,"foo count":100,"Key4":"1004"}, {"test?":True,"price":100,"foo count":100,"Key4":"1004"}, {"test?":True,"price":100,"foo count":100,"Key4":"1004"}] #create the DictionaryGrid dg = DictionaryGrid(dictionaries=dicts) Configuring #set UI to be editable dg.editable = True #Define columns to display keys=["price","test?"] dg = DictionaryGrid(dictionaries=dicts,keys=keys) #Define column types to use hints = {"price": StringColumn} dg = CouchGrid(dictionaries=dicts,keys=keys, type_hints = hints) #A CouchGrid is Gtk.TreeView, so you can use Gtk.TreeView members dg.get_column(0).set_title("Price") #Use the selection-changed signal and read from the DictionaryGrid dg.connect("selection-changed", __handle_selection_changed) def __handle_selection_changed(widget, dictionaries, data = None): for dictionary in dictionaries: print dictionary["price"] #Use the cell-edited signal to track changes dg.connect("cell-edited", __handle_edited_cells) def __handle_edited_cells(widget, cell, row, key, new_value, data=None): print new_value Extending To change what a DictionaryGrid does every time it builds itself override DictionaryGrid._refresh_treeview. Here you can read data form a data store, change the way the columns from quickly.widgetsgrid_column are built, etc... To change what a DictionaryGrid does every time a row of data is add, override "append_row". Here you can change add data to store with the dictionary being added, change the data itself, change how the data is being displayed, etc... """ import sys from gi.repository import GObject from gi.repository import Gtk import conventions from grid_column import StringColumn from grid_column import CheckColumn class DictionaryGrid(Gtk.TreeView): __gtype_name__ = "DictionaryGrid" def __init__(self, dictionaries=None, editable = False, keys=None, type_hints=None): """ Creates a new DictionaryGrid arguments: dictionaries - a list of dictionaries to initialize in the grid. keys - a list of strings specifying keys to use in the columns of the DictionaryGrid. The types for the columns will be inferred by the key based on some conventions. the key "id" is assumed to be an integer, as is any key ending in " count". A key ending in "?" is assumed to be a Boolean displayed with a checkbox. The key "price" is assumed to be currency, as is any key ending in "count". There may be others. Defaults can be overridden using type-hints. All other keys will be assumed to be strings. type-hints - a dictionary containing keys specificed for the TreeView and GridColumns. Used to override types inferred by convention, or for changing the type of a column from the default of a string to something else. """ Gtk.TreeView.__init__(self) self.list_store = None self.unfiltered_store = None self._keys = keys self._editable = editable if dictionaries is None: self._dictionaries = [] else: self._dictionaries = dictionaries if type_hints is None: self._type_hints = {} else: self._type_hints = type_hints self.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE) self._refresh_treeview() #signal handlers to track selection in the treeview #utlmiately these all emit the "selection_changed signal self.connect("cursor_changed", self.__selection_changed) self.connect("move-cursor", self.__cursor_moved) self.connect("select-all", self.__selection_all) self.connect("select-cursor-row", self.__selection_changed) self.connect("unselect-all", self.__selection_none) self.connect("toggle-cursor-row", self.__selection_changed) def __cursor_moved(self, grid, step, count, data=None): self.__selection_changed(self) def __selection_all(self, treeview, data=None): self.emit("selection-changed", self.rows) def __selection_none(self, treeview, data=None): self.emit("selection-changed", []) def __selection_changed(self, treeiew, data=None): self.emit("selection-changed", self.selected_rows) def __edited_toggled(self, cell, path, col): iter = self.get_model().get_iter(path) key = col.key active = not cell.get_active() self.__edited(cell, path, active, col) def __edited(self, cell, path, new_val, col): """ _edited - internal signal handler. Updates the database if a cell in the Treeview has been edited. """ iter = self.get_model().get_iter(path) row_dict = self.get_model().get_value(iter,len(self.keys)) key = col.key dictionary = self.get_model().get_value(iter,len(self.keys)) self.emit("cell-edited",cell, path, key, new_val, row_dict) @property def keys(self): """ keys - A list of strings to act as keys for the backing dictionaries and the default titles for the columns. Setting this property will cause the widget to reload. """ return self._keys @keys.setter def keys(self, keys): self._keys = keys self._refresh_treeview() @property def editable(self): """editable - bool value, True to make editable Setting this property will cause the widget to reload. """ return self._editable @editable.setter def editable(self, editable): #refresh the treeview if possible #self._refresh_treeview() # Refreshing the treeview has no benefits but many negative # side effects. Better to loop over the columns, setting the property # on each renderer. The columns should probably expose this property # themselves, but for now this works. for column in self.get_columns(): column.set_editable(editable) self._editable = editable @property def columns(self): """ columns - A dictionary of the GridColumns indexed by the keys for that column. This allows access to columns by the key, for example to change the title of a specific column: grid.columns["complete?"].set_title(_("Completed")) This property is read only. """ cols = {} for c in self.get_columns(): cols[c.key] = c return cols def set_column_titles(self, titles): """set_column_titles - sets the specified titles for the GridColumns in the DictionaryGrid. Use a dictionary of strings indexed by keys. For example: titles = {"complete?":_("Complete"),"id":_("ID")} grid.set_column_titles(titles) """ for t in titles: if t in self.columns: self.columns[t].set_title(titles[t]) def get_dictionaries_copy(self): """get_dictionaries_copy -returns a copy of the dictionaries in the dictionary grid. """ return self._dictionaries[:] def _infer_keys_from_dictionaries(self): """_infer_keys_from_dictionaries: an internal function to set _keys suitable for column titles from a set of dictionaries. _infer_keys_from_dictionaries is not typically called directly, but may be useful to override in subclasses. """ key_collector = [] for r in self._dictionaries: for k in r.keys(): if k not in key_collector and not k.startswith("__"): key_collector.append(k) self._keys = key_collector def _refresh_treeview(self): """ _refresh_treeview: internal function to handle rebuilding the Gtk.TreeView along with columns and cell renderers.. _refresh_treeview is not typically called directly, but may be useful to override in subclasses. """ #if keys are already set, set up titles and columns if self.keys is not None: self.__reset_model() #if keys aren't set, infer them from the collection if len(self._dictionaries) > 0 and self.keys is None: self._infer_keys_from_dictionaries() self.__reset_model() for dictionary in self._dictionaries: #lists have to match the list_store columns in length #so we have to make rows as long as the headerings #note that the last value is reserved for extra data self.append_row(dictionary) #apply the model to the Treeview if possible if self.list_store != None: self.unfiltered_store = self.list_store self.set_model(self.list_store) def append_row(self, dictionary): """append_row: add a row to the TreeView. If keys are already set up only the the keys in the dictionary matching the keys used for columns will be used. If no keys are set up, and this is the first row, keys will be inferred from the dictionary keys. arguments: dictionary - a dictionary to the TreeView. """ new_row = [] for i, k in enumerate(self.keys): if k in dictionary: display_val = self.__columns_map[k].display_val(dictionary[k]) real_val = self.__columns_map[k].real_val(dictionary[k]) #TODO: store a "real_val" instead of display val #that was "converted_val" dictionary[k] = real_val else: display_val = self.__columns_map[k].default_display_val() new_row.append(display_val) new_row.append(dictionary) self.list_store.append(new_row) @property def rows(self): """ rows - returns a list of dictionaries for each row in the grid. This property is read only. """ model = self.get_model() rows = [] #list of rows to return model.foreach(self.__append_dict, rows) return rows def __append_dict(self, model, path, iter, rows): """ __append_dict: internal function, do not call directly""" row = model.get_value(iter,len(self.keys)) rows.append(row) @property def selected_rows(self): """ selected_rows - returns a list of dictionaries for each row selected. This property is read only. """ #get the selected rows in the ListStore selection = self.get_selection() if selection is None: return [] model, model_rows = selection.get_selected_rows() rows = [] #list of rows to return for mr in model_rows: row = {} #a row to be added to the list of rows iter = model.get_iter(mr) row = model.get_value(iter,len(self.keys)) rows.append(row) return rows def remove_selected_rows(self): """ remove_selected_rows: removes the rows currently selected in the TreeView UI from the TreeView as well as the backing Gtk.ListStore. """ #get the selected rows, and return if nothing is selected model, rows = self.get_selection().get_selected_rows() if len(rows) == 0: return #store the last selected row to reselect after removal next_to_select = rows[-1].get_indices()[0] + 1 - len(rows) #loop through and remove if type(model) is not Gtk.ListStore: iters = [model.get_model().get_iter(path) for path in rows] store_iters = [] for i in iters: store_iters.append(model.get_model().convert_iter_to_child_iter(i)) for store_iter in store_iters: self.unfiltered_store.remove(store_iter) else: iters = [model.get_iter(path) for path in rows] for i in iters: model.remove(i) #select a row for the user, nicer that way rows_remaining = len(self.get_model()) #don't try to select anything if there are no rows left if rows_remaining < 1: return #select the next row down, unless it's out of range #in which case just select the last row if next_to_select < rows_remaining: self.get_selection().select_path(next_to_select) else: self.get_selection().select_path(rows_remaining - 1) def __reset_model(self): """ __reset_model - internal funciton, do not call directly. This function is typically called when the TreeView needs to be rebuilt. Creates new columns. """ #remove the current columns from the TreeView cols = self.get_columns() for c in cols: self.remove_column(c) #reinitialize the column variables col_count = len(self.keys) + 1 col_types = [] self.__columns_map = {} #create a column for each key for i, k in enumerate(self.keys): #use any supllied columns if k in self._type_hints: column = self._type_hints[k](k,i,len(self.keys)) else: #no column supplied, use conventions to get a column column = conventions.get_column(k,i,len(self.keys), self.editable) #add the created column, and remember it's key self.append_column(column) self.__columns_map[k] = column #store the into for creating the list store col_types.append(column.column_type) #create the liststore with the designated types #the last column is always for storing the backing dict col_types.append(GObject.TYPE_PYOBJECT) self.list_store = Gtk.ListStore(*col_types) for c in self.get_columns(): self.__last_sorted_col = None c.list_store = self.list_store #TODO: store and delete these, this is a leak c.connect("clicked",self.__remove_sort_icon) #connect to the edit events to rip it a if type(c) == CheckColumn: c.renderer.connect("toggled",self.__edited_toggled, c) else: c.renderer.connect("edited",self.__edited, c) def __remove_sort_icon(self, column): """__remove_sort_icon: internal function used in handling display of sort buttons. Do not call this function directly. """ if self.__last_sorted_col is not None: if self.__last_sorted_col is not column: self.__last_sorted_col.set_sort_indicator(False) self.__last_sorted_col = column __gsignals__ = {'cell-edited' : (GObject.SignalFlags.RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,GObject.TYPE_PYOBJECT,GObject.TYPE_PYOBJECT,GObject.TYPE_PYOBJECT,GObject.TYPE_PYOBJECT)), 'selection-changed' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)) } def __show_selected(widget, selected_rows, data=None): """handles displaying text for test app""" tv.get_buffer().set_text(str(selected_rows)) def __on_edited(widget, cell, row, key, new_value, row_dict, tv): """handles displaying text for test app""" string = "row: " + str(row) string += ", key: " + str(key) string += ", new value: " + str(new_value) string += "\n" + str(row_dict) tv.get_buffer().set_text(string) if __name__ == "__main__": """creates a test DictionaryGrid if called directly""" dicts = [{"key?": True, "price":0.00,"tags" : "aaa bbb ccc","_foo":"bar","bing count":20}, {"ID": 11, "key?": False, "price":2.00,"tags" : "bbb ccc ddd","_foo":"bar"}, {"key?": True, "price":33.00,"tags" : "ccc ddd eee","_foo":"bar","bing count":15}, {"ID": 3, "tags" : "ddd eee fff","_foo":"bar"}, {"ID": 4, "price":5.00,"_foo":"bar"}] #create and show a test windowp win = Gtk.Window() win.set_title("DictionaryGrid Test Window") win.connect("destroy",Gtk.main_quit) win.show() #create a top level container vbox = Gtk.VBox(False, False) vbox.show() win.add(vbox) #create a test widget with test database values grid = DictionaryGrid(dicts, editable=True)#, ["ID","tags","price","bing count","key?"]) #allow editing #grid.editable = True #show the control, add it to the window, and run the main loop grid.show() vbox.pack_start(grid, False, False, 0) #create a test display area hbox = Gtk.HBox(False, 5) hbox.show() tv = Gtk.TextView() tv.show() grid.connect("selection-changed",__show_selected, tv) grid.connect("cell-edited",__on_edited, tv) hbox.pack_start(tv, False, False, 0) vbox.pack_end(hbox, False, False, 0) #run the test app Gtk.main() quickly-widgets-12.03/quickly/widgets/web_cam_box.py0000664000000000000000000002351411727667117017526 0ustar #!/usr/bin/python # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """A VBox that tries to turn on and display the default webcam for the computer on which it is running. It is also capable of saving an image from the webcam to the user's Picture directory. Using #create the a WebCamBox cam = WebCamBox() #the camera should be playing before you try to do other #operations with it, such as taking a picture. cam.play() #to save a picture and save it to ~/Pictures cam.take_picture() #connect to the image-captured signal to do something automatically with a picture. cam.connect("image-captured", self.on_picture_captured) def on_picture_captured(self,widget, filename, data=None): #do something with the filename Configuring #You can set a string that prepends the default datestamp filenames #this will result in filenames such as "myapp_2010-09-04 09:37:32.957580.png" cam.filename_prefix = "myapp_" #If you want access to all the gstreamer knobs and dials, you can just #get a reference to the camerabin (see gstreamer documentation for details. cam.camerabin.set_property(property_name,value) #you can send the camerabin signals in this was, as well cam.camerbin.emit(signal_name) #You can add Widgets to the WebCamBox simply by packing them in cam.pack_start(my_widget, False, False) Extending A WebCamBox is Gtk.VBox A WebCamBox is a Gtk.VBox that contains a Gtk.DrawingArea for displaying webcam output, and a thin wrapper around a camerabin, which is a gstreamer pipleine sublcass that provides all the camera functionality. To add GUI elements simple, create them and pack them into WebCamBox, since it's just a Gtk.VBox Similarly, to add to or change the web cam functionality, modify properties on the camerabin. You may also want to overide _on_message and/or _on_sync_message to catch messages from the bus and add behavior. """ from gi.repository import Gtk from gi.repository import GdkX11 from gi.repository import GObject from gi.repository import Gst import sys import os import datetime import gettext from gettext import gettext as _ gettext.textdomain('quickly-widgets') class WebCamBox(Gtk.VBox): """WebCamBox - A VBox that tries to turn on and display the default webcam for the computer on which it is running. It is also capable of saving an image from the webcam to the user's Picture directory. """ def __init__(self): """Creates a WebCamBox, incuding initalizing the default camera. Note that this does not start the camera streaming. For that call play(). This function has no arguments """ Gtk.VBox.__init__(self, False, 5) self.video_window = Gtk.DrawingArea() self.video_window.connect("realize",self.__on_video_window_realized) self.pack_start(self.video_window, True, True, 0) self.video_window.show() self.connect("destroy", self.on_destroy) self.camerabin = Gst.ElementFactory.make("camerabin", "camera-source") bus = self.camerabin.get_bus() bus.add_signal_watch() bus.enable_sync_message_emission() bus.connect("message", self._on_message) bus.connect("sync-message::element", self._on_sync_message) #self.camerabin.set_property("image-encoder",Gst.ElementFactory.make("pngenc", "png_encoder")) self.filename_prefix = "" self.realized = False def play(self): """play - Start the camera streaming and display the output. It is necessary to start the camera playing before using most other functions. This function has no arguments """ if not self.realized: self._set_video_window_id() if not self.realized: print _("Cannot display web cam output. Ignoring play command") else: self.camerabin.set_state(Gst.State.PLAYING) def pause(self): """pause - Pause the camera output. It will cause the image to "freeze". Use play() to start the camera playng again. Note that calling pause before play may cause errors on certain camera. This function has no arguments """ self.camerabin.set_state(Gst.State.PAUSED) def take_picture(self): """take_picture - grab a frame from the web cam and save it to ~/Pictures/datestamp.png, where datestamp is the current datestamp. It's possible to add a prefix to the datestamp by setting the filename_prefix property. If play is not called before take_picture, an error may occur. If take_picture is called immediately after play, the camera may not be fully initialized, and an error may occur. Connect to the signal "image-captured" to be alerted when the picture is saved. This function has no arguments returns - a string of the filename used to save the image """ stamp = str(datetime.datetime.now()) extension = ".jpg" directory = os.environ["HOME"] + _("/Pictures/") self.filename = directory + self.filename_prefix + stamp + extension self.camerabin.set_property("filename", self.filename) self.camerabin.emit("capture-start") return self.filename def stop(self): """stop - Stop the camera streaming and display the output. This function has no arguments """ self.camerabin.set_state(Gst.State.NULL) def _on_message(self, bus, message): """ _on_message - internal signal handler for bus messages. May be useful to extend in a base class to handle messages produced from custom behaviors. arguments - bus: the bus from which the message was sent, typically self.bux message: the message sent """ if message is None: return t = message.type if t == Gst.MessageType.ELEMENT: if message.structure.get_name() == "image-captured": #work around to keep the camera working after lots #of pictures are taken self.camerabin.set_state(Gst.Sate.NULL) self.camerabin.set_state(Gst.State.PLAYING) self.emit("image-captured", self.filename) if t == Gst.MessageType.EOS: self.camerabin.set_state(Gst.State.NULL) elif t == Gst.MessageType.ERROR: err, debug = message.parse_error() print "Error: %s" % err, debug def _on_sync_message(self, bus, message): """ _on_sync_message - internal signal handler for bus messages. May be useful to extend in a base class to handle messages produced from custom behaviors. arguments - bus: the bus from which the message was sent, typically self.bux message: the message sent """ if message.structure is None: return message_name = message.structure.get_name() if message_name == "prepare-xwindow-id": imagesink = message.src imagesink.set_property("force-aspect-ratio", True) imagesink.set_xwindow_id(self.video_window.get_window().get_xid()) def __on_video_window_realized(self, widget, data=None): """__on_video_window_realized - internal signal handler, used to set up the xid for the drawing area in thread safe manner. Do not call directly. """ self._set_video_window_id() def _set_video_window_id(self): if not self.realized and self.video_window.get_window() is not None: x = self.video_window.get_window().get_xid() self.realized = True def on_destroy(self, widget, data=None): #clean up the camera before exiting self.camerabin.set_state(Gst.State.NULL) __gsignals__ = {'image-captured' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } def __image_captured(widget, data=None): """ __image_captured - internal function for testing callbacks from the test app. """ #quickly.prompts.info("WebCam Test",data) print data if __name__ == "__main__": """creates a test WebCamBox""" #import quickly.prompts Gst.init (sys.argv) #create and show a test window win = Gtk.Window() win.set_title("WebCam Test Window") win.connect("destroy",Gtk.main_quit) win.show() #create a top level container vbox = Gtk.VBox(False, 10) vbox.show() win.add(vbox) mb = WebCamBox() mb.video_frame_rate = 30 vbox.add(mb) mb.show() mb.play() mb.connect("image-captured", __image_captured) play_butt = Gtk.Button("Play") pause_butt = Gtk.Button("Pause") stop_butt = Gtk.Button("Stop") pic_butt = Gtk.Button("Picture") play_butt.connect("clicked", lambda x:mb.play()) play_butt.show() mb.pack_end(play_butt, False, False, 0) pause_butt.connect("clicked", lambda x:mb.pause()) pause_butt.show() mb.pack_end(pause_butt, False, False, 0) stop_butt.connect("clicked", lambda x:mb.stop()) stop_butt.show() mb.pack_end(stop_butt, False, False, 0) pic_butt.connect("clicked", lambda x:mb.take_picture()) pic_butt.show() mb.pack_end(pic_butt, False, False, 0) Gtk.main() quickly-widgets-12.03/quickly/widgets/media_player_box.py0000664000000000000000000004060211727666612020560 0ustar #!/usr/bin/python # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3, as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranties of # MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """A VBox that tries to play the media file as defined by it's URU property. It works for video and sound files. Using #create the a MediaPlayerBox and set the URI, and start it playing player = MediaPlayerBox() player.uri = "file:///home/user/Videos/a_video.avi" player.play() #You can seek to a specific place in the media file #This will jump to the 60th second in the file player.position = 60 #you can get the position and duration, for example for display position_string = str(player.position) duration_string = str(player.duration) label.set_text( position_string + "/" + duration_string ) #you can pause and stop the media as well player.pause() player.stop() Configuring #You can choose to create the MediaPlayerBox with or without #visible controls. The controls are not visible by default. #Set show_toolbar to True to create the controls with visible controls player = MediaPlayerBox(True) #You can change the visibile of the controls later by setting the #controls_visible property player.controls_visible = False #You can add Widgets to the MediaPlayerBox simply by packing them in player.pack_start(my_widget, False, False) #You can get a reference to the controls, which are a Gtk.Toolbar mybutton = Gtk.ToolButton() player.controls.insert(mybutton, 0) #You can access the playbutton, slider, or time label directly as well player.play_button.hide()#a Gtk.ToggleToolButton player.slider.hide()#a Gtk.HScale player.time_label.hide()#a Gtk.Label #If you want access to all the gstreamer knobs and dials, you can just #get a reference to the playbin (see gstreamer documentation for details. player.playbin.set_property(property_name, value) #you can send the playbin signals in this way, as well player.playbin.emit(signal_name) Extending A WebCamBox is Gtk.VBox A WebCamBox is a Gtk.VBox that contains a Gtk.DrawingArea for displaying video output, and a thin wrapper around a playbin, which is a gstreamer pipleine sublcass that provides all the media playing functionality. To add GUI elements simple, create them and pack them into MediaPlayerBox, since it's just a Gtk.VBox Similarly, to add to or change the media player functionality, modify properties on the playbin. You may also want to overide _on_message and/or _on_sync_message to catch messages from the bus and add behavior. """ import sys import os from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GdkX11 from gi.repository import GObject from gi.repository import Gst import datetime import gettext from gettext import gettext as _ gettext.textdomain('quickly-widgets') class MediaPlayerBox(Gtk.VBox): """MediaPlayerBox - A VBox that tries to play the media file as defined by it's URU property. It works for video and sound files. """ def __init__(self, show_controls = False): """Creates a MediaPlayerBox, Note that this does not start media. For that, set the uri property and then call play(). This function has no argumentsf """ Gtk.VBox.__init__(self, False, 5) self.video_window = Gtk.DrawingArea() self.video_window.connect("realize",self.__on_video_window_realized) # self.pack_start(self.video_window, True, True, 0) self.video_window.show() self.connect("destroy", self.on_destroy) self.playbin = Gst.ElementFactory.make("playbin2", "player") bus = self.playbin.get_bus() bus.add_signal_watch() bus.enable_sync_message_emission() bus.connect("message", self._on_message) bus.connect("sync-message::element", self._on_sync_message) self.__uri = "" self.realized = False self.controls = Gtk.Toolbar() if show_controls: self.controls.show() self.pack_start(self.controls, False, False, 0) self.pack_start(self.video_window, True, True, 0) self.play_button = Gtk.ToggleToolButton() self.play_button.set_stock_id(Gtk.STOCK_MEDIA_PLAY) self.play_button.show() self._play_button_toggled_handler = self.play_button.connect("toggled",self._play_button_toggled) self.controls.add(self.play_button) item = Gtk.ToolItem() item.show() self.slider = Gtk.HScale() self.slider_changed_handler = None self.slider.set_draw_value(False) self.slider.set_increments(10,60) self.slider.set_restrict_to_fill_level(False) self.slider.show() self.slider.set_size_request(300,-1) item.add(self.slider) self.controls.insert(item, -1) item2 = Gtk.ToolItem() item2.show() self.time_label = Gtk.Label("") self.time_label.show() item2.add(self.time_label) self.controls.insert(item2, -1) self._slider_changed_handler = None self._duration_time_str = "" def play(self): """play - Start the media paying. It is necessary to start the media playing before using most other functions. This function has no arguments """ if not self.realized: self._set_video_window_id() if not self.realized: print _("""WARNING: MediaPlayerBox window not realized. Will try to play anyway, but bad things could happen if there is video to play""") if self.__uri != "": self.playbin.set_property("uri", self.__uri) self.playbin.set_state(Gst.State.PLAYING) self.slider.set_sensitive(True) self._reformat_slider() self._start_slider_updates() self.play_button.set_stock_id(Gtk.STOCK_MEDIA_PAUSE) self._set_play_button_active(True) def pause(self): """pause - Pause the media. If the media is a video, it will cause the image to "freeze". Use play() to start the media again. Note that calling pause before play may cause errors. This function has no arguments """ self.playbin.set_state(Gst.State.PAUSED) self.slider.set_sensitive(True) self._reformat_slider() self.slider.set_sensitive(True) self.play_button.set_stock_id(Gtk.STOCK_MEDIA_PLAY) self._set_play_button_active(False) def stop(self): """stop - Stop the media playing. If the media contains video calling stop() will blank the video. This function has no arguments """ self.playbin.set_state(Gst.State.NULL) self.slider.set_sensitive(False) self.play_button.set_stock_id(Gtk.STOCK_MEDIA_PLAY) self._set_play_button_active(False) self.slider.set_value(0) @property def controls_visible(self): """controls_visible - A boolean representing whether the MediaBoxPlayers default controls are visible or not. This propery is read/write """ return self.controls.get_property("visible") @controls_visible.setter def controls_visible(self, visibility): self.controls.set_property("visible",visibility) @property def uri(self): """uri - a string of a well formed uri pointing to the media to play. If the media is local, it will typicall start in the form: file:///home/username/etc. Defaults to "", which MediaPlayerBox will not try to play. When set, the MediaPlayerBox will try to change to the new video, but maintain it's state of being paused, playing, or stopped. This property is read/write. """ return self.__uri @uri.setter def uri(self, uri): state = self.playbin.get_state(0) if state[0] == Gst.StateChangeReturn.SUCCESS: return_to_state = state[1] else: return_to_state = Gst.State.NULL self.stop() self.__uri = uri self.playbin.set_property("uri", self.__uri) self.playbin.set_state(return_to_state) if return_to_state != Gst.State.NULL: self._reformat_slider() self._start_slider_updates() @property def position(self): """position - the current position in the media in seconds. Trying to set the position past the duration of the media may cause errors. If the current position cannot be read, -1 will be returned. This property is read/write. """ try: return self.playbin.query_position(Gst.Format.TIME,None)[0] / Gst.SECOND except Exception, inst: return -1 @position.setter def position(self, seconds): self.playbin.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT, seconds * Gst.SECOND) @property def duration(self): """duration - the total duration of the media in seconds. If the duration cannot be read, -1 will be returned. This property is read only. """ try: return self.playbin.query_duration(Gst.Format.TIME,None)[0] / Gst.SECOND except Exception, inst: return -1 def _set_play_button_active(self, active): if self._play_button_toggled_handler is not None: self.play_button.disconnect(self._play_button_toggled_handler) self.play_button.set_active(active) self._play_button_toggled_handler = self.play_button.connect("toggled",self._play_button_toggled) def _play_button_toggled(self, widget, data=None): if widget.get_active(): self.play() else: self.pause() def _reformat_slider(self): if self.playbin.get_state(0)[1] == Gst.State.NULL: self.slider.set_range(0, 0) else: GObject.idle_add(self._set_slider_range) def _set_slider_range(self): dur = self.duration if dur < 0: return True else: self._duration_time_str = self._formatted_time(dur) Gdk.threads_enter() self.slider.set_range(0, dur) Gdk.threads_leave() return False def _start_slider_updates(self): if self.playbin.get_state(0)[1] == Gst.State.NULL: self.slide.set_value(0) else: GObject.timeout_add(1000, self._set_slider_position) def _set_slider_position(self): if self._slider_changed_handler is not None: self.slider.disconnect(self._slider_changed_handler) self.slider.set_value(self.position) self._slider_changed_handler = self.slider.connect("value-changed",self._seek) try: if self.position < 0 or self.duration < 0: self.time_label.set_text("") else: dur = self._duration_time_str pos = self._formatted_time(self.position, len(dur) > 5) self.time_label.set_text(pos + "/" + dur) except: self.time_label.set_text("") return self.playbin.get_state(0)[1] == Gst.State.PLAYING def _formatted_time(self, pos, always_include_hours = False): seconds = pos % 60 minutes = (pos % (60 * 60)) / 60 hours = pos / (60 * 60) if hours > 23: hours = hours % 24 t = datetime.time(hours, minutes, seconds) if t.hour > 0 or always_include_hours: format = "%H:%M:%S" else: format = "%M:%S" return t.strftime(format) def _seek(self, widget, data=None): self.position = widget.get_value() def _on_message(self, bus, message): """ _on_message - internal signal handler for bus messages. May be useful to extend in a base class to handle messages produced from custom behaviors. arguments - bus: the bus from which the message was sent, typically self.bux message: the message sent """ if message is None: return t = message.type if t == Gst.MessageType.EOS: self.playbin.set_state(Gst.State.NULL) self.emit("end-of-file", self.uri) elif t == Gst.MessageType.ERROR: err, debug = message.parse_error() print "Error: %s" % err, debug def _on_sync_message(self, bus, message): """ _on_sync_message - internal signal handler for bus messages. May be useful to extend in a base class to handle messages produced from custom behaviors. arguments - bus: the bus from which the message was sent, typically self.bux message: the message sent """ if message.structure is None: return message_name = message.structure.get_name() if message_name == "prepare-xwindow-id": imagesink = message.src imagesink.set_property("force-aspect-ratio", True) imagesink.set_xwindow_id(self.video_window.get_window().get_xid()) def __on_video_window_realized(self, widget, data=None): """__on_video_window_realized - internal signal handler, used to set up the xid for the drawing area in thread safe manner. Do not call directly. """ self._set_video_window_id() def _set_video_window_id(self): if not self.realized and self.video_window.get_window() is not None: x = self.video_window.get_window().get_xid() self.realized = True def on_destroy(self, widget, data=None): #clean up the camera before exiting self.playbin.set_state(Gst.State.NULL) __gsignals__ = {'end-of-file' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), } def __seek_func(sender, mb): """Function for testing purposes, do not use""" mb.position = 10 def __seek_time(data): """Function for testing purposes, do not use""" mb, label = data label.set_text(str(mb.position) + "/" + str(mb.duration)) return True def __set_uri(sender, data): """Function for testing purposes, do not use""" mb, entry = data mb.uri = entry.get_text() def __controls_func(sender, mb): mb.controls_visible = sender.get_active() def __on_media_ended(widget, uri): print uri if __name__ == "__main__": """creates a test WebCamBox""" Gst.init (sys.argv) #create and show a test window win = Gtk.Window() win.set_title("WebCam Test Window") win.connect("destroy",Gtk.main_quit) win.show() #create a top level container vbox = Gtk.VBox(False, 10) vbox.show() win.add(vbox) mb = MediaPlayerBox() mb.set_size_request(600,600) vbox.add(mb) mb.show() uri_entry = Gtk.Entry() play_butt = Gtk.Button("Play") pause_butt = Gtk.Button("Pause") stop_butt = Gtk.Button("Stop") seek_butt = Gtk.Button("Seek") controls_butt = Gtk.ToggleButton("Controls") time_label = Gtk.Label("") play_butt.connect("clicked", lambda x:mb.play()) play_butt.show() mb.pack_end(play_butt, False, False, 0) uri_entry.connect("activate", __set_uri, (mb, uri_entry)) uri_entry.set_text("file:///home/rick/Videos/VID00110.AVI") uri_entry.show() mb.pack_end(uri_entry, False, False, 0) pause_butt.connect("clicked", lambda x:mb.pause()) pause_butt.show() mb.pack_end(pause_butt, False, False, 0) stop_butt.connect("clicked", lambda x:mb.stop()) stop_butt.show() mb.pack_end(stop_butt, False, False, 0) seek_butt.connect("clicked", __seek_func, mb) seek_butt.show() mb.pack_end(seek_butt, False, False, 0) controls_butt.connect("clicked", __controls_func, mb) controls_butt.show() mb.pack_end(controls_butt, False, False, 0) mb.connect("end-of-file", __on_media_ended) time_label.show() mb.pack_end(time_label, False, False, 0) GObject.timeout_add(1000, __seek_time, (mb, time_label)) Gtk.main() quickly-widgets-12.03/quickly/widgets/grid_column.py0000664000000000000000000006755511727674520017574 0ustar # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """Specializations of Gtk.TreeViewColumns designer to work with DictionaryGrid and descendants. Using Grid columns are not normally created directly, but rather created automatically when a DictionaryGrid displays it's data. See the DictionaryGrid documentation for how to use type hints and conventions to control the type of column used for a key in a dictionary. Customizing The column types in this module are all descendants of Gtk.TreeView, so you can use all of the Gtk.TreeView methods and properties to control how a grid column looks or works. #Find a grid column and change the title for c in my_dictionary_grid.get_columns(): if c.key = my_key: c.set_title("New Title") Extending To display data in a column with a string, such as to display words and numbers, you should extend StringColumn. Otherwise, extend Gtk.TreeView directly. In either case, you will need to implement a set of functions. A Grid Column must track two different data, a "real" value, which is tracked in the dictionary for the row, and the "display" value, which is used to determine a value to display to users. For example, CheckColumn stores a real value of True, False, or None, but a display value of -1, 0, or 1, and uses the display value to set the checkbox in it's CellRenderer. Every new column must have the following function to support real and display values: display_val(self, val) - takes a real value and returns the cooresponding display value real_val(self, val) - takes a display value and returns the cooresponding real value default_display_val(self) - reutrn the value to display in the case where a row does not contain a key, value pair for the specified column. For example StringColumn returns an empty string ("") A new column type will often require a specially configured Gtk.CellRenderer. If you are deriving from StringColumn, but are using a custom renderer, you need to override the _initialize_renderer method, and set the columns renderer property to the renderer. You should also connect the CellRenderer's edit signal to a function that will update the underlying dictionary when the cell is edited. For instance, a CurrencyColumn has the following implemention for _initialize_renderer: def _initialize_renderer( self, editable, index ): self.renderer = Gtk.CellRendererSpin() adj = Gtk.Adjustment(0,-10000000000,10000000000,1) self.renderer.set_property("adjustment", adj) self.renderer.set_property("editable", editable) self.renderer.set_property("digits",2) self.renderer.connect("edited", self._cell_edited) You also need to define two class variable: 1. column_type, the gobject type for the column's display value. This is needed so that the DictionaryGrid can create a ListStore 2. default_filter, the grid_filter type to use in cases where a GridFilter is associate with the column. For example, CurrencyColumn defines the following class variables: column_type = gobject.TYPE_STRING default_filter = grid_filter.NumericFilterBox """ import sys import datetime import gettext from gettext import gettext as _ gettext.textdomain('quickly-widgets') import grid_filter from gi.repository import GObject from gi.repository import Gtk from gi.repository import Gdk class GridColumn( Gtk.TreeViewColumn ): """GridColumn - Base class that provides features that is important to all columns used in a DictionaryGrid or decendants. Currently it's useful only to StringColumn and CheckColumn, but should make it easier to make new "top-level" column types. """ def __init__(self, key, index, dictionary_index, renderer, editable=True, format_function = None ): Gtk.TreeViewColumn.__init__(self, key, renderer, text=index) self.set_clickable(True) self.set_resizable(True) self.index = index self.key = key self.dictionary_index = dictionary_index # Why should list_store be set to None? self.list_store = None self.connect('clicked', self.sort_rows) def sort_rows(self, widget): sort_order = widget.get_sort_order() rows = [tuple(r) + (i,) for i, r in enumerate(self.list_store)] # Sort opposite of last time if sort_order == Gtk.SortType.ASCENDING: sort_order = Gtk.SortType.DESCENDING else: sort_order = Gtk.SortType.ASCENDING self.set_sort_order(sort_order) self.set_sort_indicator(True) if sort_order == Gtk.SortType.ASCENDING: rows.sort(self._sort_ascending) else: rows.sort(self._sort_descending) # Where does self.list_store come from? self.list_store.set_sort_column_id(self.index, sort_order) def set_editable(self, editable): self.renderer.set_property("editable", editable) class StringColumn( GridColumn ): """StringColumn - Displays strings and tracks data as string. Uses a CellRendererText for display and editing. Not typically created directly in code, but rather created by a DictionaryGrid or descendant. Suitable as a base class for any column that needs to display a string. """ column_type = GObject.TYPE_STRING __sort_order = None default_filter = grid_filter.StringFilterBox def __init__(self, key, index, dictionary_index, editable=True, format_function = None ): """Creates a StringColumn Arguments: key - the key from the dict for the row. Also used as the title for the column by default. index - the position of the column in the grid. dictionary_index - the index in the ListStore where the dictionary for the row is stored. Typically len(dict). editable - False if the column does not allow the user to edit the values in the column. Defaults to True. format_function - and optional function to handle formatting of of the string to display. Defaults to None. """ self._initialize_renderer(editable, index) GridColumn.__init__( self, key, index, dictionary_index, self.renderer, editable, format_function) if format_function is not None: self.set_cell_data_func(self.renderer, self._on_format, format_function) def _sort_ascending(self, x, y): """_sort_ascending - internal sort function that sorts two values in the column from least value to greatest value. returns 1 if x > y, 0 if x = y, -1 if x < y arguments: x - the value being compared to y - the value being compared """ x = x[self.index] y = y[self.index] if x > y: return 1 elif x == y: return 0 elif x < y: return -1 def _sort_descending(self, x, y): """_sort_descending - internal sort function that sorts two values in the column from greatest value to least value. May need to be implimented or overriden in specialized columns. returns 1 if x < y, 0 if x = y, -1 if x > y arguments: x - the value being compared to y - the value being compared """ x = x[self.index] y = y[self.index] if x > y: return -1 elif x == y: return 0 elif x < y: return 1 def _on_format(self,column, cell_renderer, tree_model, iter, format_function): """on format - internal signal handler called when the column needs to reformat the display value. Typically called after editing or when a value is first inserted. arguments: column - the index of the column, not typically needed cell_renderer - a reference to the specific cell_renderer that is formatting the string tree_model - the Gtk.ListStore that is the backing data for the DictionaryGrid that contains the column. iter - an iterator that references the row of the the DictionaryGrid containing the cell that needs to be formatted. format_function - a function that takes the string and performs the actual formatting. """ string = format_function(tree_model.get_value(iter, self.index), cell_renderer) if string != None: cell_renderer.set_property('text', string) def _initialize_renderer( self, editable, index ): """_initialize_renderer - internal function called to set up the CellRenderer for the column. arguments: editable - True if the column should support user editing. index - the position of the column in the grid """ self.renderer = Gtk.CellRendererText() self.renderer.set_property("editable", editable) self.renderer.connect("edited", self._cell_edited) def _cell_edited(self, cellrenderertext, path, new_text, data=None): """ _cell_edited - internal signal handler called when a cell in the column is edited. arguments: cellrenderertext - the CellRenderer that was edited path - path to the row in the treeview new_text - the text was in the cell after the editing """ #get an iterator that points to the edited row if self.list_store is not None: iter = self.list_store.get_iter(path) #update the ListStore with the new text self.list_store.set_value(iter, self.index, self.display_val(new_text)) dictionary = self.list_store.get_value(iter,self.dictionary_index) dictionary[self.key] = self.real_val(new_text) def display_val(self, val): """display_val - takes a real value and returns the cooresponding display value arguments: val - the real value to convert """ if val == None: return self.default_display_val() else: return str(val) def real_val(self, val): """real_val - takes a display value and returns the cooresponding real value. arguments: val - the display value to convert """ #in a StringColumn, the backing data and the display data are the same return self.display_val(val) def default_display_val(self): """default_dislay_val - return the value to display in the case where there is no real value for the column for the row. """ #display an empty string if there is no string for the cell return "" class CurrencyColumn( StringColumn ): """CurrencyColumn - display data in currency format. Uses a Gtk.Spinner to display data and support editing if enabled. Store real values as float. Inherits from StringColumn. """ column_type = GObject.TYPE_STRING default_filter = grid_filter.NumericFilterBox def __init__(self, key, index,dictionary_index, editable=True ): """Creates a CurrencyColumn Arguments: key - the key from the dict for the row. Also used as the title for the column by default. index - the position of the column in the grid. dictionary_index - the index in the ListStore where the dictionary for the row is stored. Typically len(dict). editable - False if the column does not allow the user to edit the values in the column. Defaults to True. """ StringColumn.__init__( self, key, index, dictionary_index, editable, self._currency_format) def _initialize_renderer( self, editable, index ): """_initialize_renderer - internal function called to set up the CellRenderer for the column. arguments: editable - True if the column should support user editing. index - the position of the column in the grid """ self.renderer = Gtk.CellRendererSpin() adj = Gtk.Adjustment(0,-10000000000,10000000000,1) self.renderer.set_property("adjustment", adj) self.renderer.set_property("editable", editable) self.renderer.set_property("digits",2) self.renderer.connect("edited", self._cell_edited) #make sure the value was edited to something that can be #turned into an int try: float(new_text) except: return #get an iterator that points to the edited row if self.list_store is not None: iter = self.list_store.get_iter(path) #update the ListStore with the new text self.list_store.set_value(iter, self.index, self.display_val(new_text)) dictionary = self.list_store.get_value(iter,self.dictionary_index) dictionary[self.key] = self.real_val(new_text) def display_val(self, val): """display_val - takes a real value and returns the cooresponding display value arguments: val - the real value to convert """ try: return str(float(val)) except: return "" def real_val(self, val): """real_val - takes a display value and returns the cooresponding real value. arguments: val - the display value to convert """ try: return float(val) except: return 0.0 def default_display_val(self): """default_dislay_val - return the value to display in the case where there is no real value for the column for the row. """ return "" def _sort_ascending(self, x, y): x = x[self.index] y = y[self.index] if x == "" and y == "": return 0 if x == "" and y != "": return -1 if x != "" and y == "": return 1 x = float(x) y = float(y) if x > y: return 1 elif x == y: return 0 elif x < y: return -1 def _sort_descending(self, x, y): x = x[self.index] y = y[self.index] if x == "" and y == "": return 0 if x == "" and y != "": return 1 if x != "" and y == "": return -1 x = float(x) y = float(y) if x > y: return -1 elif x == y: return 0 elif x < y: return 1 def _currency_format(self, val, cell_renderer): try: return "%.2f" % float(val) except: return "" class TagsColumn( StringColumn ): """TagsColumn - A specialization of a StringColumn that differs only in that it uses a TagsFilterBox for filtering in any attached GridFilter. """ column_type = GObject.TYPE_STRING default_filter = grid_filter.TagsFilterBox class IntegerColumn( StringColumn ): """IntegerColumn - display data in Integer format. Uses a Gtk.Spinner to display data and support editing if enabled. Store real values as int. Inherits from StringColumn. """ column_type = GObject.TYPE_STRING default_filter = grid_filter.IntegerFilterBox def __init__(self, key, index, dictionary_index, editable=True ): """Creates an IntegerColumn Arguments: key - the key from the dict for the row. Also used as the title for the column by default. index - the position of the column in the grid. dictionary_index - the index in the ListStore where the dictionary for the row is stored. Typically len(dict). editable - False if the column does not allow the user to edit the values in the column. Defaults to True. """ StringColumn.__init__( self, key, index, dictionary_index, editable) def _initialize_renderer( self, editable, index ): self.renderer = Gtk.CellRendererSpin() adj = Gtk.Adjustment(0,-10000000000,10000000000,1) self.renderer.set_property("adjustment", adj) self.renderer.set_property("editable", editable) self.renderer.connect("edited", self._cell_edited) def _cell_edited(self, cellrenderertext, path, new_text, data=None): """ __edited - internal signal handler. Updates the dictionary if a cell in the Treeview has been edited. """ #make sure the value was edited to something that can be #turned into an int try: int(new_text) except: return #get an iterator that points to the edited row if self.list_store is not None: iter = self.list_store.get_iter(path) #update the ListStore with the new text self.list_store.set_value(iter, self.index, self.display_val(new_text)) dictionary = self.list_store.get_value(iter,self.dictionary_index) dictionary[self.key] = self.real_val(new_text) def display_val(self, val): """display_val - takes a real value and returns the cooresponding display value arguments: val - the real value to convert """ try: return str(int(val)) except: return "" def real_val(self, val): """real_val - takes a display value and returns the cooresponding real value. arguments: val - the display value to convert """ try: return int(val) except: return 0 def default_display_val(self): """default_dislay_val - return the value to display in the case where there is no real value for the column for the row. """ return "" def _sort_ascending(self, x, y): x = x[self.index] y = y[self.index] if x == "" and y == "": return 0 if x == "" and y != "": return -1 if x != "" and y == "": return 1 x = int(x) y = int(y) if x > y: return 1 elif x == y: return 0 elif x < y: return -1 def _sort_descending(self, x, y): x = x[self.index] y = y[self.index] if x == "" and y == "": return 0 if x == "" and y != "": return 1 if x != "" and y == "": return -1 x = int(x) y = int(y) if x > y: return -1 elif x == y: return 0 elif x < y: return 1 class CheckColumn( GridColumn ): """CheckColumn - display data as checkboxes. Store real values as bool. Inherits from Gtk.TreeViewColumn. """ column_type = GObject.TYPE_INT default_filter = grid_filter.CheckFilterBox def __init__(self, key, index, dictionary_index, editable=True, format_function = None ): """Creates a StringColumn Arguments: key - the key from the dict for the row. Also used as the title for the column by default. index - the position of the column in the grid. dictionary_index - the index in the ListStore where the dictionary for the row is stored. Typically len(dict). editable - False if the column does not allow the user to edit the values in the column. Defaults to True. format_function - and optional function to handle formatting of of the string to display. Defaults to None. """ # self.key is set in GridColumn, but needs to be set for tests to pass. Fix. self.key = key self._initialize_renderer(editable, index) GridColumn.__init__( self, key, index, dictionary_index, self.renderer, editable, format_function) self.set_cell_data_func(self.renderer, self._on_format) self.extra_format_function = format_function def _sort_ascending(self, x, y): x = x[self.index] y = y[self.index] return y - x def _sort_descending(self, x, y): x = x[self.index] y = y[self.index] return x - y def _on_format(self,column, cell_renderer, tree_model, iter, format_function): cell_val = tree_model.get_value(iter, self.index) cell_renderer.set_property('inconsistent', False) if cell_val == 1: cell_renderer.set_active(True) elif cell_val == 0: cell_renderer.set_active(False) else: cell_renderer.set_property('inconsistent', True) #TODO: show it checked, unchecked, inconsistent ... based (-1,0,1) if self.extra_format_function != None: self.extra_format_function() def _initialize_renderer( self, editable, index ): self.renderer = Gtk.CellRendererToggle() self.renderer.set_property("activatable", editable) col = Gtk.TreeViewColumn(self.key, self.renderer, active=index) self.renderer.connect("toggled", self.toggled) def toggled(self, cell, path, data=None): #get an iterator that points to the edited row new_val = not cell.get_active() if self.list_store is not None: iter = self.list_store.get_iter(path) #update the ListStore with the new text self.list_store.set_value(iter, self.index, new_val) dictionary = self.list_store.get_value(iter,self.dictionary_index) dictionary[self.key] = new_val def set_editable(self, editable): self.renderer.set_property("activatable", editable) def display_val(self, val): """display_val - takes a real value and returns the cooresponding display value arguments: val - the real value to convert """ if type(val) is bool: if val: return 1 else: return 0 elif type(val) is str: if val.lower() == _("yes"): return 1 else: return 0 elif type(val) is None: return self.default_display_val() else: return bool(val) def default_display_val(self): """default_dislay_val - return the value to display in the case where there is no real value for the column for the row. """ return -1 def real_val(self, val): """real_val - takes a display value and returns the cooresponding real value. arguments: val - the display value to convert """ if type(val) is type(True): return val elif type(val) is type("a"): if val.lower() == "yes": return True else: return False else: return bool(val) class DateColumn( StringColumn ): """DateColumn - display data in date format. Uses a Gtk.Calendar to display data and support editing if enabled. Store real values as tuple. Inherits from StringColumn. """ column_type = GObject.TYPE_STRING default_filter = grid_filter.DateFilterBox def __init__(self, key, index,dictionary_index, editable=True ): """Creates a Date Arguments: key - the key from the dict for the row. Also used as the title for the column by default. index - the position of the column in the grid. dictionary_index - the index in the ListStore where the dictionary for the row is stored. Typically len(dict). editable - False if the column does not allow the user to edit the values in the column. Defaults to True. """ self._editable = editable StringColumn.__init__( self, key, index, dictionary_index, editable) def _initialize_renderer( self, editable, index ): """_initialize_renderer - internal function called to set up the CellRenderer for the column. arguments: editable - True if the column should support user editing. index - the position of the column in the grid """ self.renderer = CellRendererDate() self.renderer.set_property('editable',self._editable) self.renderer.connect("edited", self._cell_edited) class CellRendererDate(Gtk.CellRendererText): def __init__(self): Gtk.CellRendererText.__init__(self) self.date_format = '%Y-%m-%d' self.calendar_window = None self.calendar = None def _create_calendar(self, treeview): self.calendar_window = Gtk.Dialog(parent=treeview.get_toplevel()) self.calendar_window.action_area.hide() self.calendar_window.set_decorated(False) self.calendar_window.set_property('skip-taskbar-hint', True) self.calendar = Gtk.Calendar() self.calendar.display_options(Gtk.CalendarDisplayOptions.SHOW_DAY_NAMES | Gtk.CalendarDisplayOptions.SHOW_HEADING) self.calendar.connect('day-selected-double-click', self._day_selected, None) self.calendar.connect('key-press-event', self._day_selected) self.calendar.connect('focus-out-event', self._selection_cancelled) self.calendar_window.set_transient_for(None) # cancel the modality of dialog self.calendar_window.vbox.pack_start(self.calendar, True, True, 0) # necessary for getting the (width, height) of calendar_window self.calendar.show() self.calendar_window.realize() def do_start_editing(self, event, treeview, path, background_area, cell_area, flags): if not self.get_property('editable'): return if not self.calendar_window: self._create_calendar(treeview) # select cell's previously stored date if any exists - or today if self.get_property('text'): date = datetime.datetime.strptime(self.get_property('text'), self.date_format) else: date = datetime.datetime.today() self.calendar.freeze() # prevent flicker (year, month, day) = (date.year, date.month - 1, date.day) # datetime's month starts from one self.calendar.select_month(int(month), int(year)) self.calendar.select_day(int(day)) self.calendar.thaw() # position the popup below the edited cell (and try hard to keep the popup within the toplevel window) (tree_x, tree_y) = treeview.get_bin_window().get_origin() (tree_w, tree_h) = treeview.window.get_geometry()[2:4] (calendar_w, calendar_h) = self.calendar_window.window.get_geometry()[2:4] x = tree_x + min(cell_area.x, tree_w - calendar_w + treeview.get_visible_rect().x) y = tree_y + min(cell_area.y, tree_h - calendar_h + treeview.get_visible_rect().y) self.calendar_window.move(x, y) response = self.calendar_window.run() self.calendar_window.hide() if response == Gtk.ResponseType.OK: (year, month, day) = self.calendar.get_date() date = datetime.date(year, month + 1, day).strftime(self.date_format) # Gtk.Calendar's month starts from zero self.emit('edited', path, date) return None # don't return any editable, our Gtk.Dialog did the work already def _day_selected(self, calendar, event): # event == None for day selected via doubleclick if not event or event.type == Gdk.EventType.KEY_PRESS and Gdk.keyval_name(event.keyval) == 'Return': self.calendar_window.response(Gtk.ResponseType.OK) return True def _selection_cancelled(self, calendar, event): self.calendar_window.response(Gtk.ResponseType.CANCEL) return True quickly-widgets-12.03/quickly/widgets/tests/0000775000000000000000000000000011727704224016033 5ustar quickly-widgets-12.03/quickly/widgets/tests/test_grid_filter.py0000664000000000000000000001413511623512000021722 0ustar # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """Tests for the DictionaryGrid""" from testtools import TestCase from quickly.widgets.dictionary_grid import DictionaryGrid from quickly.widgets.grid_filter import GridFilter class TestGridFilter(TestCase): """Test the CouchGrid functionality""" def setUp(self): TestCase.setUp(self) def tearDown(self): TestCase.tearDown(self) def test_create_a_grid(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid_filter = GridFilter(grid) self.assertEqual(len(grid.get_model()),5) def test_filter_a_row(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid_filter = GridFilter(grid) filter_row = grid_filter.rows[0] filter_combo = filter_row.get_children()[1].get_children()[0].get_children()[0] filter_combo.set_active(1) entry = filter_row.get_children()[1].get_children()[0].get_children()[1] entry.set_text("val5_1") self.assertEqual(len(grid.get_model()),4) def test_remove_selected_with_filter(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid_filter = GridFilter(grid) filter_row = grid_filter.rows[0] filter_combo = filter_row.get_children()[1].get_children()[0].get_children()[0] filter_combo.set_active(1) entry = filter_row.get_children()[1].get_children()[0].get_children()[1] entry.set_text("val5_1") selection = grid.get_selection() selection.select_path((1,)) selection.select_path((2,)) grid.remove_selected_rows() self.assertEqual(len(grid.get_model()),2) def test_add_row_while_filtered(self): dicts = [{"key1_1": "val1_1", "key?": True, "key1_3": "val1_3"}, {"key1_1": "val2_1", "key?": False, "key1_3": "val2_3"}, {"key1_1": "val3_1", "key?": True, "key1_3": "val3_3"}, {"key1_1": "val5_1", "key?": False, "key1_3": "val4_3"}, {"key1_1": "val5_1", "key?": True, "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid_filter = GridFilter(grid) filter_row = grid_filter.rows[0] filter_combo = filter_row.get_children()[1].get_children()[0].get_children()[0] entry = filter_row.get_children()[1].get_children()[0].get_children()[1] #test with string filters filter_combo.set_active(1) entry.set_text("val5_1") grid.append_row({}) entry.set_text("xxx") self.assertEqual(len(grid.get_model()),6) #test with check filters filter_combo.set_active(0) grid.append_row({}) filter_combo.set_active(1) entry = filter_row.get_children()[1].get_children()[0].get_children()[1] entry.set_text("xxx") self.assertEqual(len(grid.get_model()),7) def test_with_set_column_titles(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dictionaries = dicts, keys=["key1_1","key1_2","key1_3"]) titles = {"key1_1":"KEY1","key1_2":"KEY2","key1_3":"KEY3"} grid.set_column_titles(titles) grid_filter = GridFilter(grid) filter_row = grid_filter.rows[0] column_combo = filter_row.get_children()[0].get_children()[0] #make sure the correct titles are appearing itr = column_combo.get_model().get_iter(0) self.assertEqual(column_combo.get_model().get_value(itr,0),"KEY1") itr = column_combo.get_model().get_iter(1) self.assertEqual(column_combo.get_model().get_value(itr,0),"KEY2") itr = column_combo.get_model().get_iter(2) self.assertEqual(column_combo.get_model().get_value(itr,0),"KEY3") #make sure filtering still works filter_combo = filter_row.get_children()[1].get_children()[0].get_children()[0] filter_combo.set_active(1) entry = filter_row.get_children()[1].get_children()[0].get_children()[1] entry.set_text("val5_1") self.assertEqual(len(grid.get_model()),4) quickly-widgets-12.03/quickly/widgets/tests/test_dictionary_grid.py0000664000000000000000000002666011725471710022627 0ustar # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """Tests for the DictionaryGrid""" from testtools import TestCase from quickly.widgets.dictionary_grid import DictionaryGrid from gi.repository import GObject from quickly.widgets.grid_column import StringColumn, IntegerColumn, CurrencyColumn,CheckColumn, DateColumn class TestDictionaryGrid(TestCase): """Test the CouchGrid functionality""" def setUp(self): TestCase.setUp(self) def tearDown(self): TestCase.tearDown(self) def test_empty_construction(self): """Test a simple creating An AsynchTaskProgressBox and then adding keys and dictionaries after creation """ grid = DictionaryGrid() self.assertEqual((grid != None), True) grid.keys = ["key1","key2"] self.assertEqual(grid.get_model().get_n_columns(),3) grid.append_row({"key1":"val11","key2":"val12"}) self.assertEqual(len(grid.get_model()),1) def test_constructor_with_dicts(self): """test creating a grid with dictionaries in the contructor""" dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}] #build the CouchGrid grid = DictionaryGrid(dicts) self.assertEqual(grid.get_model().get_n_columns(),4) self.assertEqual(len(grid.get_model()),2) def test_constructor_with_dicts_and_keys(self): """test creating a grid with dictionaries in the contructor as well as keys in the contructor, with fewer keys than items in the dictionary """ dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}] keys = ["key1_1", "key1_3"] #build the CouchGrid grid = DictionaryGrid(dicts,keys) self.assertEqual(grid.get_model().get_n_columns(),4) self.assertEqual(len(grid.get_model()),2) def test_extra_data_from_selected(self): """Ensure that keys starting with _ are not displayed, but the valuesa retrievable. """ dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "__extra": ["boo","biz","baz"]}, {"key1_1": "val2_1", "key1_2": "val2_2", "__extra": self}] grid = DictionaryGrid(dicts) #make sure there are 2 columns self.assertEqual(len(grid.get_model()),2) #ensure that none of the columns are named _extra cols = grid.get_columns() for c in cols: self.assertEqual(c.get_title().startswith("key"), True) #select the first row selection = grid.get_selection() selection.select_path((0,)) selected_dict = grid.selected_rows[0] self.assertEqual(selected_dict["__extra"],["boo","biz","baz"]) def test_dicts_with_different_keys(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "__extra": ["boo","biz","baz"]}, {"key2_1": "val2_1", "key2_2": "val2_2", "__extra": self}] grid = DictionaryGrid(dicts) #make sure there are 5 columns self.assertEqual(grid.get_model().get_n_columns(),5) def test_remove_selected_rows(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) selection = grid.get_selection() grid.remove_selected_rows() #select the last row and remove it selection.select_path((4,)) grid.remove_selected_rows() #the last row should then be selected and there should be 4 rows now self.assertEqual(len(grid.get_model()),4) self.assertEqual(len(grid.selected_rows),1) self.assertEqual(grid.selected_rows[0]["key1_1"],"val4_1") #select the first and third rows and remove them selection = grid.get_selection() selection.unselect_all() selection.select_path((0,)) selection.select_path((2,)) grid.remove_selected_rows() #make sure the now last row is selected, and there are 2 rows left self.assertEqual(len(grid.get_model()),2) self.assertEqual(len(grid.selected_rows),1) self.assertEqual(grid.selected_rows[0]["key1_2"],"val4_2") def test_auto_set_col_types(self): """Ensure that collumn types are set properly""" data = [{"id":0,"price":1.00,"bool?":True, "sale price":.50, "count":50, "full count":100, "date":"2010-05-05","sale date":"2010-05-06"}] grid = DictionaryGrid(data) c_type = type(grid.columns["id"]) self.assertEqual(c_type,IntegerColumn) c_type = type(grid.columns["price"]) self.assertEqual(c_type,CurrencyColumn) c_type = type(grid.columns["bool?"]) self.assertEqual(c_type,CheckColumn) c_type = type(grid.columns["sale price"]) self.assertEqual(c_type,CurrencyColumn) c_type = type(grid.columns["count"]) self.assertEqual(c_type,IntegerColumn) c_type = type(grid.columns["full count"]) self.assertEqual(c_type,IntegerColumn) c_type = type(grid.columns["date"]) self.assertEqual(c_type,DateColumn) c_type = type(grid.columns["sale date"]) self.assertEqual(c_type,DateColumn) def test_NONE_values(self): keys = ["id","price","bool?","foo"] dicts = [{"price":None,"id":None,"bool?":None,"foo":None}] grid = DictionaryGrid(dicts) self.assertEqual(len(grid.get_model()),1) def test_use_custom_columns(self): """Ensure that type hins work so inferred types can be overridden and non-inferred type can be set. """ keys = ["id","price","bool?","foo"] hints = {"id":StringColumn, "price":IntegerColumn, "bool?":CurrencyColumn,"foo":CheckColumn} dicts = [{"price":100,"id":"asdfas","bool?":10.01,"foo":True}] grid = DictionaryGrid(dicts, keys=keys, type_hints=hints) for c in grid.get_columns(): key = c.key col_type = c.column_type if key == "id": self.assertEqual(col_type,GObject.TYPE_STRING) elif key == "price": self.assertEqual(col_type,GObject.TYPE_STRING) elif key == "bool?": self.assertEqual(col_type,GObject.TYPE_STRING) elif key == "foo": self.assertEqual(col_type,GObject.TYPE_INT) else: self.assertEqual("Extra key Found",False) def test_infer_boolean_values(self): """Ensure that inferring boolean values from strings works""" keys = ["a?","b?","c?","d?","e?","f?"] dicts = [{"a?":True,"b?":False,"c?":"Yes","d?":"No","e?":1.5,"f?":0}] grid = DictionaryGrid(dicts, keys) test_dict = grid.get_dictionaries_copy()[0] self.assertEqual(test_dict["a?"],True) self.assertEqual(test_dict["b?"],False) self.assertEqual(test_dict["c?"],True) self.assertEqual(test_dict["d?"],False) self.assertEqual(test_dict["e?"],True) self.assertEqual(test_dict["f?"],False) def test_mismatched_col_and_val_types(self): """Ensure robustness for strings passed in for non-str column types """ keys = ["id","price","bool?"] dicts = [{"price":"100.00","id":"50","bool?":"Yes"}] grid = DictionaryGrid(dicts, keys) test_dict = grid.get_dictionaries_copy()[0] self.assertEqual(test_dict["id"],50) self.assertEqual(test_dict["price"],100.00) self.assertEqual(test_dict["bool?"],True) def test_copy_dictionaries(self): """Testcase for LP: #497664""" dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}] #build the CouchGrid grid1 = DictionaryGrid(dicts) # added two dicts, so length should be 2 self.assertEqual(len(grid1.get_dictionaries_copy()), 2) #no dicts, so it should be 0 grid2 = DictionaryGrid() self.assertEqual(len(grid2.get_dictionaries_copy()), 0) def test_columns_property(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) self.assertTrue("key1_1" in grid.columns) self.assertTrue("key1_2" in grid.columns) self.assertTrue("key1_3" in grid.columns) def test_set_editable(self): keys = ["id","price","bool?"] dicts = [{"price":"100.00","id":"50","bool?":"Yes"}] grid = DictionaryGrid(dicts, keys) grid.editable = False ed1 = grid.columns["price"].get_cells()[0].get_property("editable") self.assertTrue(not ed1) ed2 = grid.columns["bool?"].get_cells()[0].get_property("activatable") self.assertTrue(not ed2) def test_set_a_column_title(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) grid.columns["key1_1"].set_title("KEY") for c in grid.get_columns(): if c.key == "key1_1": self.assertEqual(c.get_title(),"KEY") def test_set_multiple_column_titles(self): dicts = [{"key1_1": "val1_1", "key1_2": "val1_2", "key1_3": "val1_3"}, {"key1_1": "val2_1", "key1_2": "val2_2", "key1_3": "val2_3"}, {"key1_1": "val3_1", "key1_2": "val3_2", "key1_3": "val3_3"}, {"key1_1": "val4_1", "key1_2": "val4_2", "key1_3": "val4_3"}, {"key1_1": "val5_1", "key1_2": "val5_2", "key1_3": "val5_3"}] grid = DictionaryGrid(dicts) titles = {"key1_1":"KEY1","key1_2":"KEY2","key1_3":"KEY3"} grid.set_column_titles(titles) for c in grid.columns: self.assertTrue(grid.columns[c].get_title() in ("KEY1","KEY2","KEY3")) quickly-widgets-12.03/quickly/widgets/tests/_trial_temp/0000775000000000000000000000000011727704224020332 5ustar quickly-widgets-12.03/quickly/widgets/tests/_trial_temp/test.log0000664000000000000000000000005111623512000021770 0ustar 2009-12-05 10:30:22-0800 [-] Log opened. quickly-widgets-12.03/quickly/widgets/tests/__init__.py0000664000000000000000000000000011623512000020112 0ustar quickly-widgets-12.03/quickly/widgets/__init__.py0000664000000000000000000000000011623512000016750 0ustar quickly-widgets-12.03/quickly/widgets/url_fetch_progressbox.py0000664000000000000000000001156411725471710021661 0ustar ### BEGIN LICENSE # Copyright (C) 2010 Stuart Langridge stuart.langridge@canonical.com # Copyright (C) 2012 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE try: from gi.repository import GObject from gi.repository import Gtk from gi.repository import Gio from gi.repository import GLib import gettext from gettext import gettext as _ gettext.textdomain('quickly-widgets') except: print "couldn't load dependencies" class UrlFetchProgressBox(Gtk.HBox): """UrlFetchProgressBox: encapsulates a pulsating progressbar, a cancel button, and a URL that needs fetching. Use a UrlFetchProgressBox when you need to fetch a URL; the box will show while the URL is being fetched without blocking the UI for the user. By default, the box will automatically destroy itself once the URL is fetched; suppress this by passing destroy_after_fetching=False. Fires a "downloaded" signal once download is complete, passing the contents of the URL. Cancelling fires the "downloaded" signal with a value of None. """ __gsignals__ = {'downloaded' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)), 'download-error' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,))} def __init__(self, url, destroy_after_fetching=True, cancelable=True): """Create an UrlFetchProgressBox Keyword arguments: url -- the URL to fetch destroy_after_fetching -- should this widget destroy itself once the URL is fetched? Defaults to True. cancelable -- whether to show cancel button. Defaults to True. """ Gtk.HBox.__init__( self, False, 2) self.progressbar = Gtk.ProgressBar() GObject.timeout_add(10, self.__tick) self.running = True parts = [x for x in url.split("/") if x] self.progressbar.set_text(_("Downloading %s") % parts[-1]) self.progressbar.show() self.pack_start(self.progressbar, True, True, 0) self.destroy_after_fetching = destroy_after_fetching self.cancel_button = Gtk.Button(stock=Gtk.STOCK_CANCEL) if cancelable: self.cancel_button.show() self.cancel_button.set_sensitive(False) self.cancel_button.connect("clicked",self.__cancel) self.pack_end(self.cancel_button, False, False, 0) self.cancel_button.set_sensitive(True) self.__canceller = Gio.Cancellable() self.stream = Gio.file_new_for_uri(url) self.stream.load_contents_async(self.__canceller, self.__download_finished, None) def __tick(self): self.progressbar.pulse() return self.running def __download_finished(self, gdaemonfile, result, data=None): try: #GIO documentation says that the file is [0] in the tuple #but it is realy [1] content = self.stream.load_contents_finish(result)[1] except Exception, e: self.emit("download-error",e) else: self.emit("downloaded", content) self.__maybe_destroy() def __cancel(self, btn): self.__canceller.cancel() self.__maybe_destroy() def __maybe_destroy(self): self.running = False if self.destroy_after_fetching: self.destroy() class TestWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_title("UrlFetchProgressBox test") self.vbox = Gtk.VBox() btn = Gtk.Button(stock=Gtk.STOCK_EXECUTE) btn.connect("clicked", self.start_download) self.vbox.pack_end(btn, True, True, 0) self.add(self.vbox) self.set_size_request(300,200) self.connect("destroy", Gtk.main_quit) def start_download(self, btn): prog = UrlFetchProgressBox("http://www.ubuntu.com/desktop/get-ubuntu/download") prog.connect("downloaded", self.downloaded) prog.connect("download-error", self.errored) self.vbox.pack_start(prog, False, False, 0) prog.show() def errored(self, widget, e): print "encountered error: %s " % e.message def downloaded(self, widget, content): print "downloaded %s bytes of content" % len(content) if __name__ == "__main__": w = TestWindow() w.show_all() Gtk.main() quickly-widgets-12.03/quickly/tests/0000775000000000000000000000000011727704224014365 5ustar quickly-widgets-12.03/quickly/tests/test_prompts.py0000664000000000000000000000224411623512000017464 0ustar # -*- coding: utf-8 -*- ### BEGIN LICENSE # Copyright (C) 2010 Rick Spencer rick.spencer@canonical.com #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE """Tests for the DictionaryGrid""" from testtools import TestCase import quickly.prompts class TestDictionaryGrid(TestCase): """Test the CouchGrid functionality""" def setUp(self): pass def tearDown(self): pass def test_string_prompt(self): """Test a simple creating An AsynchTaskProgressBox and then adding keys and dictionaries after creation """ pass #response, val = quickly.prompts.string() quickly-widgets-12.03/quickly/tests/__init__.py0000664000000000000000000000000011623512000016444 0ustar quickly-widgets-12.03/.quickly0000664000000000000000000000007211623512000013203 0ustar project = quidgets template = python-library format = 0.3 quickly-widgets-12.03/LICENSE0000664000000000000000000010437411623512000012540 0ustar GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . quickly-widgets-12.03/setup.py0000664000000000000000000000327111623512000013237 0ustar #!/usr/bin/env python # -*- coding: utf-8 -*- ### BEGIN LICENSE #This program is free software: you can redistribute it and/or modify it #under the terms of the GNU General Public License version 3, as published #by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, but #WITHOUT ANY WARRANTY; without even the implied warranties of #MERCHANTABILITY, SATISFACTORY QUALITY, 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, see . ### END LICENSE ###################### DO NOT TOUCH THIS (HEAD TO THE SECOND PART) ###################### try: import DistUtilsExtra.auto except ImportError: import sys print >> sys.stderr, 'To build quidgets you need https://launchpad.net/python-distutils-extra' sys.exit(1) assert DistUtilsExtra.auto.__version__ >= '2.10', 'needs DistUtilsExtra.auto >= 2.10' import os ################################################################################## ###################### YOU SHOULD MODIFY ONLY WHAT IS BELOW ###################### ################################################################################## DistUtilsExtra.auto.setup( name='quickly-widgets', version='11.03.1', license='GPL-3', author='Rick Spencer', author_email='rick.spencer@canonical.com', description='Library for easing some PyGtk coding tasks', long_description='Library for easing some PyGtk coding tasks. Note that this is experimental, the API will change, there are bugs.', url='https://launchpad.net/quidgets', )