id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,100 | bpmn_converter.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/serializer/helpers/bpmn_converter.py | class BpmnConverter:
"""The base class for conversion of BPMN classes.
In general, most classes that extend this would simply take an existing registry as an argument
and supply the class along with the implementations of the conversion functions `to_dict` and
`from_dict`.
The operation of the converter is a little opaque, but hopefully makes sense with a little
explanation.
The registry is a `DictionaryConverter` that registers conversion methods by class. It can be
pre-populated with methods for custom data (though this is not required) and is passed into
subclasses of this one, which will consolidate conversions as classes are instantiated.
There is a lot of interdependence across the classes in spiff -- most of them need to know about
many of the other classes. Subclassing this is intended to consolidate the boiler plate required
to set up a global registry that is usable by any other registered class.
The goal is to be able to replace the conversion mechanism for a particular entity without
delving into the details of other things spiff knows about.
So for example, it is not necessary to re-implemnent any of the event-based task spec conversions
because, eg, the `MessageEventDefintion` was modified; the existing `MessageEventDefinitionConverter`
can be replaced with a customized one and it will automatically be used with any event-based task.
"""
def __init__(self, target_class, registry, typename=None):
"""Constructor for a dictionary converter for a BPMN class.
Arguemnts:
target_class: the type the subclass provides conversions for
registry (`DictionaryConverter`): a registry of conversions to which this one should be added
typename (str): the name of the class as it will appear in the serialization
"""
self.target_class = target_class
self.registry = registry
self.typename = typename if typename is not None else target_class.__name__
self.registry.register(target_class, self.to_dict, self.from_dict, self.typename)
def to_dict(self, spec):
"""This method should take an object and convert it to a dictionary that is JSON-serializable"""
raise NotImplementedError
def from_dict(self, dct):
"""This method take a dictionary and restore the original object"""
raise NotImplementedError
def mapping_to_dict(self, mapping, **kwargs):
"""Convert both the key and value of a dict with keys that can be converted to strings."""
return dict((str(k), self.registry.convert(v, **kwargs)) for k, v in mapping.items())
def mapping_from_dict(self, mapping, key_class=None, **kwargs):
"""Restore a mapping from a dictionary of strings -> objects."""
if key_class is None:
return dict((k, self.registry.restore(v, **kwargs)) for k, v in mapping.items())
else:
return dict((key_class(k), self.registry.restore(v, **kwargs)) for k, v in mapping.items())
| 3,070 | Python | .py | 45 | 60.755556 | 105 | 0.720305 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,101 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/serializer/helpers/__init__.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from .bpmn_converter import BpmnConverter
from .registry import DefaultRegistry
from .spec import TaskSpecConverter, EventDefinitionConverter, BpmnDataSpecificationConverter
| 981 | Python | .py | 21 | 45.666667 | 93 | 0.807091 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,102 | spec.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/serializer/helpers/spec.py | # Copyright (C) 2023 Elizabeth Esswein, Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from functools import partial
from SpiffWorkflow.operators import Attrib, PathAttrib
from SpiffWorkflow.bpmn.specs.mixins.bpmn_spec_mixin import BpmnSpecMixin
from SpiffWorkflow.bpmn.specs.event_definitions.message import CorrelationProperty
from .bpmn_converter import BpmnConverter
class BpmnDataSpecificationConverter(BpmnConverter):
"""This is the base Data Spec converter.
This is used for `DataObject` and `TaskDataReference`; it can be extended for other
types of data specs.
"""
def to_dict(self, data_spec):
"""Convert a data specification into a dictionary.
Arguments:
data_spec (`BpmnDataSpecification): a BPMN data specification
Returns:
dict: a dictionary representation of the data spec
"""
return { 'bpmn_id': data_spec.bpmn_id, 'bpmn_name': data_spec.bpmn_name }
def from_dict(self, dct):
"""Restores a data specification.
Arguments:
dct (dict): the dictionary representation
Returns:
an instance of the target class
"""
return self.target_class(**dct)
class EventDefinitionConverter(BpmnConverter):
"""This is the base Event Defintiion Converter.
It provides conversions for the great majority of BPMN events as-is, and contains
one custom method for serializing Correlation Properties (as Message Event Defintiions
are likely to the most commonly extended event definition spec).
"""
def to_dict(self, event_definition):
"""Convert an event definition into a dictionary.
Arguments:
event_definition: the event definition
Returns:
dict: a dictionary representation of the event definition
"""
dct = {
'description': event_definition.description,
'name': event_definition.name
}
return dct
def from_dict(self, dct):
"""Restores an event definition.
Arguments:
dct: the dictionary representation
Returns;
an instance of the target event definition
"""
event_definition = self.target_class(**dct)
return event_definition
def correlation_properties_to_dict(self, props):
"""Convert correlation properties to a dictionary representation.
Arguments:
list(`CorrelationProperty`): the correlation properties associated with a message
Returns:
list(dict): a list of dictionary representations of the correlation properties
"""
return [prop.__dict__ for prop in props]
def correlation_properties_from_dict(self, props):
"""Restore correlation properties from a dictionary representation
Arguments:
props (list(dict)): a list if dictionary representations of correlation properties
Returns:
a list of `CorrelationProperty` of a message
"""
return [CorrelationProperty(**prop) for prop in props]
class TaskSpecConverter(BpmnConverter):
"""Base Task Spec Converter.
It contains methods for parsing generic and BPMN task spec attributes.
If you have extended any of the the BPMN tasks with custom functionality, you'll need to
implement a converter for those task spec types. You'll need to implement the `to_dict` and
`from_dict` methods on any inheriting classes.
The default task spec converters are in the `default.task_spec` modules of this package; the
`camunda`,`dmn`, and `spiff` serialization packages contain other examples.
"""
def get_default_attributes(self, spec):
"""Extracts the default BPMN attributes from a task spec.
Arguments:
spec: the task spec to be converted
Returns:
dict: a dictionary of standard task spec attributes
"""
dct = {
'name': spec.name,
'description': spec.description,
'manual': spec.manual,
'lookahead': spec.lookahead,
'inputs': spec._inputs,
'outputs': spec._outputs,
'bpmn_id': spec.bpmn_id,
'bpmn_name': spec.bpmn_name,
'lane': spec.lane,
'documentation': spec.documentation,
'data_input_associations': self.registry.convert(spec.data_input_associations),
'data_output_associations': self.registry.convert(spec.data_output_associations),
'io_specification': self.registry.convert(spec.io_specification),
}
if hasattr(spec, 'extensions'):
dct['extensions'] = spec.extensions
return dct
def get_join_attributes(self, spec):
"""Extracts attributes for task specs that inherit from `Join`.
Arguments:
spec: the task spec to be converted
Returns:
dict: a dictionary of `Join` task spec attributes
"""
return {
'split_task': spec.split_task,
'threshold': spec.threshold,
'cancel': spec.cancel_remaining,
}
def get_subworkflow_attributes(self, spec):
"""Extracts attributes for task specs that inherit from `SubWorkflowTask`.
Arguments:
spec: the task spec to be converted
Returns:
dict: a dictionary of subworkflow task spec attributes
"""
return {'spec': spec.spec}
def get_standard_loop_attributes(self, spec):
"""Extracts attributes for standard loop tasks.
Arguments:
spec: the task spec to be converted
Returns:
dict: a dictionary of standard loop task spec attributes
"""
return {
'task_spec': spec.task_spec,
'maximum': spec.maximum,
'condition': spec.condition,
'test_before': spec.test_before,
}
def task_spec_from_dict(self, dct):
"""Creates a task spec based on the supplied dictionary.
It handles setting the default task spec attributes as well as attributes added by `BpmnSpecMixin`.
Arguments:
dct (dict): the dictionary to create the task spec from
Returns:
a restored task spec
"""
dct['data_input_associations'] = self.registry.restore(dct.pop('data_input_associations', []))
dct['data_output_associations'] = self.registry.restore(dct.pop('data_output_associations', []))
dct['io_specification'] = self.registry.restore(dct.pop('io_specification', None))
wf_spec = dct.pop('wf_spec')
name = dct.pop('name')
bpmn_id = dct.pop('bpmn_id')
spec = self.target_class(wf_spec, name, **dct)
if 'extensions' in dct:
spec.extensions = dct['extensions']
if issubclass(self.target_class, BpmnSpecMixin) and bpmn_id != name:
# This is a hack for multiinstance tasks :( At least it is simple.
# Ideally I'd fix it in the parser, but I'm afraid of quickly running into a wall there
spec.bpmn_id = bpmn_id
return spec
| 7,925 | Python | .py | 176 | 36.443182 | 107 | 0.662899 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,103 | dictionary.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/serializer/helpers/dictionary.py | # Copyright (C) 2023 Elizabeth Esswein, Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from functools import partial
class DictionaryConverter:
"""
This is a base class used to convert BPMN specs, workflows, tasks, and (optonally)
data to dictionaries of JSON-serializable objects. Actual serialization is done as the
very last step by other classes.
This class allows you to register `to_dict` and `from_dict` functions for non-JSON-
serializable objects.
When an object is passed into `convert`, it will call the supplied `to_dict`
function on any classes that have been registered. The supplied to_dict function
must return a dictionary. The object's `typename` will be added to this dictionary
by the converter.
The (unqualified) class name will be used as the `typename` if one is not supplied.
You can optionally supply our own names (you'll need to do this if you use identically
named classes in multiple packages).
When a dictionary is passed into `restore`, it will be checked for a `typename` key.
If a registered `typename` is found, the supplied `from_dict` function will be
called. Unrecognized objects will be returned as-is.
For a simple example of how to use this class, see `registry.DefaultRegistry`.
Attributes:
typenames (dict): a mapping class to typename
convert_to_dict (dict): a mapping of typename to function
convert_from_dct (dict): a mapping of typename to function
"""
def __init__(self):
self.convert_to_dict = { }
self.convert_from_dict = { }
self.typenames = { }
def register(self, cls, to_dict, from_dict, typename=None):
"""Register a conversion/restoration.
Arguments:
cls: the class that will be converted/restored
to_dict (function): a function that will be called with the object as an argument
from_dict (function): a function that restores the object from the dict
typename (str): an optional typename for identifying the converted object
Notes:
The `to_dict` function must return a dictionary; if no `typename` is given,
the unquallified class name will be used.
"""
typename = cls.__name__ if typename is None else typename
self.typenames[cls] = typename
self.convert_to_dict[typename] = partial(self._obj_to_dict, typename, to_dict)
self.convert_from_dict[typename] = partial(self._obj_from_dict, from_dict)
@staticmethod
def _obj_to_dict(typename, func, obj, **kwargs):
"""A method for automatically inserting the typename in the dictionary returned by to_dict."""
dct = func(obj, **kwargs)
dct.update({'typename': typename})
return dct
@staticmethod
def _obj_from_dict(func, dct, **kwargs):
"""A method for calling the from_dict function on recognized objects."""
return func(dct, **kwargs)
def convert(self, obj, **kwargs):
"""Convert a known object to a dictionary.
This is the public conversion method. It will be applied to dictionary
values, list items, and the object itself, applying the to_dict functions
of any registered type to the objects, or return the object unchanged if
it is not recognized.
Arguments:
obj: the object to be converter
Returns:
dict: the dictionary representation for registered objects or the original for unregistered objects
"""
typename = self.typenames.get(obj.__class__)
if typename in self.convert_to_dict:
to_dict = self.convert_to_dict.get(typename)
return to_dict(obj, **kwargs)
elif isinstance(obj, dict):
return dict((k, self.convert(v, **kwargs)) for k, v in obj.items())
elif isinstance(obj, (list, tuple, set)):
return obj.__class__([ self.convert(item, **kwargs) for item in obj ])
else:
return obj
def restore(self, val, **kwargs):
"""Restore a known object from a dictionary.
This is the public restoration method. It will be applied to dictionary
values, list items, and the value itself, checking for a `typename` key and
applying the from_dict function of any registered type, or return the value
unchanged if it is not recognized.
Arguments:
val: the value to be converted
Returns:
dict: the restored object for registered objects or the original for unregistered values
"""
if isinstance(val, dict) and 'typename' in val:
from_dict = self.convert_from_dict.get(val.pop('typename'))
return from_dict(val, **kwargs)
elif isinstance(val, dict):
return dict((k, self.restore(v, **kwargs)) for k, v in val.items())
if isinstance(val, (list, tuple, set)):
return val.__class__([ self.restore(item, **kwargs) for item in val ])
else:
return val
| 5,816 | Python | .py | 112 | 44.392857 | 111 | 0.680922 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,104 | registry.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/serializer/helpers/registry.py | # Copyright (C) 2023 Elizabeth Esswein, Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from uuid import UUID
from datetime import datetime, timedelta
from .dictionary import DictionaryConverter
class DefaultRegistry(DictionaryConverter):
"""This class forms the basis of serialization for BPMN workflows.
It contains serialization rules for a few python data types that are not JSON serializable by default which
are used internally by Spiff. It can be instantiated and customized to handle arbitrary task or workflow
data as well (see `dictionary.DictionaryConverter`).
"""
def __init__(self):
super().__init__()
self.register(UUID, lambda v: { 'value': str(v) }, lambda v: UUID(v['value']))
self.register(datetime, lambda v: { 'value': v.isoformat() }, lambda v: datetime.fromisoformat(v['value']))
self.register(timedelta, lambda v: { 'days': v.days, 'seconds': v.seconds }, lambda v: timedelta(**v))
def convert(self, obj):
"""Convert an object to a dictionary, with preprocessing.
Arguments:
obj: the object to preprocess and convert
Returns:
the result of `convert` conversion after preprocessing
"""
cleaned = self.clean(obj)
return super().convert(cleaned)
def clean(self, obj):
"""A method that can be used to preprocess an object before conversion to a dict.
It is used internally by Spiff to remove callables from task data before serialization.
Arguments:
obj: the object to preprocess
Returns:
the preprocessed object
"""
if isinstance(obj, dict):
return dict((k, v) for k, v in obj.items() if not callable(v))
else:
return obj
| 2,533 | Python | .py | 53 | 42.037736 | 116 | 0.705024 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,105 | feel_engine.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/script_engine/feel_engine.py | # Copyright (C) 2020 Kelly McDonald, 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import re
import datetime
import operator
import warnings
from datetime import timedelta
from decimal import Decimal
from .python_engine import PythonScriptEngine
def feelConvertTime(datestr,parsestr):
return datetime.datetime.strptime(datestr,parsestr)
class FeelInterval():
def __init__(self, begin, end, leftOpen=False, rightOpen=False):
# pesky thing with python floats and Decimal comparison
if isinstance(begin,float):
begin = Decimal("%0.5f"%begin)
if isinstance(end, float):
end = Decimal("%0.5f" % end)
self.startInterval = begin
self.endInterval = end
self.leftOpen = leftOpen
self.rightOpen = rightOpen
def __eq__(self, other):
if self.leftOpen:
lhs = other > self.startInterval
else:
lhs = other >= self.startInterval
if self.rightOpen:
rhs = other < self.endInterval
else:
rhs = other <= self.endInterval
return lhs and rhs
class FeelContains():
def __init__(self, testItem,invert=False ):
self.test = testItem
self.invert = invert
def __eq__(self, other):
has = False
if isinstance(other,dict):
has = self.test in list(other.keys())
else:
has = self.test in list(other)
if self.invert:
return not has
else:
return has
class FeelNot():
def __init__(self, testItem):
self.test = testItem
def __eq__(self, other):
if other == self.test:
return False
else:
return True
def feelConcatenate(*lst):
ilist = []
for list_item in lst:
ilist = ilist + list_item
return ilist
def feelAppend(lst,item):
newlist = lst[:] # get a copy
newlist.append(item)
return newlist
def feelNow():
return datetime.datetime.now()
def feelGregorianDOW(date):
# we assume date is either date in Y-m-d format
# or it is of datetime class
if isinstance(date,str):
date = datetime.datetime.strptime(date,'%Y-%m-%d')
return date.isoweekday()%7
def transformDuration(duration,td):
if duration:
return td * float(duration)
else:
return timedelta(seconds=0)
def lookupPart(code,base):
x= re.search("([0-9.]+)"+code,base)
if x:
return x.group(1)
else:
return None
def feelFilter(var,a,b,op,column=None):
"""
here we are trying to cover some of the basic test cases,
dict, list of dicts and list.
"""
opmap = {'=':operator.eq,
'<':operator.lt,
'>':operator.gt,
'<=':operator.le,
'>=':operator.ge,
'!=':operator.ne}
b = eval(b)
# if it is a list and we are referring to 'item' then we
# expect the variable to be a simple list
if (isinstance(var,list)) and a == 'item':
return [x for x in var if opmap[op](x,b)]
# if it is a dictionary, and the keys refer to dictionaries,
# then we convert it to a list of dictionaries with the elements
# all having {'key':key,<rest of dict>}
# if it is a dictionary and the key refers to a non-dict, then
# we convert to a dict having {'key':key,'value':value}
if (isinstance(var,dict)):
newvar = []
for key in var.keys():
if isinstance(var[key],dict):
newterm = var[key]
newterm.update({'key':key})
newvar.append(newterm)
else:
newvar.append({'key':key,'value':var[key]})
var = newvar
if column is not None:
return [x.get(column) for x in var if opmap[op](x.get(a), b)]
else:
return [x for x in var if opmap[op](x.get(a), b)]
def feelParseISODuration(input):
"""
Given an ISO duration designation
such as :
P0Y1M2DT3H2S
and convert it into a python timedelta
Abbreviations may be made as in :
PT30S
NB:
Months are defined as 30 days currently - as I am dreading getting into
Date arithmetic edge cases.
"""
if input[0] != 'P':
raise Exception("ISO Duration format must begin with the letter P")
input = input[1:]
days, time = input.split("T")
lookups = [("Y",days,timedelta(days=365)),
("M", days, timedelta(days=30)),
("W", days, timedelta(days=7)),
("D", days, timedelta(days=1)),
("H", time, timedelta(seconds=60*60)),
("M", time, timedelta(seconds=60)),
("S", time, timedelta(seconds=1)),
]
totaltime = [transformDuration(lookupPart(x[0],x[1]),x[2]) for x in lookups]
return sum(totaltime,timedelta(seconds=0))
# Order Matters!!
fixes = [(r'string\s+length\((.+?)\)','len(\\1)'),
(r'count\((.+?)\)','len(\1)'),
(r'concatenate\((.+?)\)','feelConcatenate(\\1)'),
(r'append\((.+?),(.+?)\)','feelAppend(\\1,\\2)'), # again will not work with literal list
(r'list\s+contains\((.+?),(.+?)\)','\\2 in \\1'), # list contains(['a','b','stupid,','c'],'stupid,') will break
(r'contains\((.+?),(.+?)\)','\\2 in \\1'), # contains('my stupid, stupid comment','stupid') will break
(r'not\s+?contains\((.+?)\)','FeelContains(\\1,invert=True)'), # not contains('something')
(r'not\((.+?)\)','FeelNot(\\1)'), # not('x')
(r'now\(\)','feelNow()'),
(r'contains\((.+?)\)', 'FeelContains(\\1)'), # contains('x')
# date and time (<datestr>)
(r'date\s+?and\s+?time\s*\((.+?)\)', 'feelConvertTime(\\1,"%Y-%m-%dT%H:%M:%S")'),
(r'date\s*\((.+?)\)', 'feelConvertTime(\\1,"%Y-%m-%d)'), # date (<datestring>)
(r'day\s+of\s+\week\((.+?)\)','feelGregorianDOW(\\1)'),
(r'\[([^\[\]]+?)[.]{2}([^\[\]]+?)\]','FeelInterval(\\1,\\2)'), # closed interval on both sides
(r'[\]\(]([^\[\]\(\)]+?)[.]{2}([^\[\]\)\(]+?)\]','FeelInterval(\\1,\\2,leftOpen=True)'), # open lhs
(r'\[([^\[\]\(\)]+?)[.]{2}([^\[\]\(\)]+?)[\[\)]','FeelInterval(\\1,\\2,rightOpen=True)'), # open rhs
# I was having problems with this matching a "P" somewhere in another expression
# so I added a bunch of different cases that should isolate this.
(r'^(P(([0-9.]+Y)?([0-9.]+M)?([0-9.]+W)?([0-9.]+D)?)?(T([0-9.]+H)?([0-9.]+M)?([0-9.]+S)?)?)$',
'feelParseISODuration("\\1")'), ## Parse ISO Duration convert to timedelta - standalone
(r'^(P(([0-9.]+Y)?([0-9.]+M)?([0-9.]+W)?([0-9.]+D)?)?(T([0-9.]+H)?([0-9.]+M)?([0-9.]+S)?)?)\s',
'feelParseISODuration("\\1") '), ## Parse ISO Duration convert to timedelta beginning
(r'\s(P(([0-9.]+Y)?([0-9.]+M)?([0-9.]+W)?([0-9.]+D)?)?(T([0-9.]+H)?([0-9.]+M)?([0-9.]+S)?)?)\s',
' feelParseISODuration("\\1") '), ## Parse ISO Duration convert to timedelta in context
(r'\s(P(([0-9.]+Y)?([0-9.]+M)?([0-9.]+W)?([0-9.]+D)?)?(T([0-9.]+H)?([0-9.]+M)?([0-9.]+S)?)?)$',
' feelParseISODuration("\\1")'), ## Parse ISO Duration convert to timedelta end
(r'(.+)\[(\S+)?(<=)(.+)]\.(\S+)', 'feelFilter(\\1,"\\2","\\4","\\3","\\5")'), # implement a simple filter
(r'(.+)\[(\S+)?(>=)(.+)]\.(\S+)', 'feelFilter(\\1,"\\2","\\4","\\3","\\5")'), # implement a simple filter
(r'(.+)\[(\S+)?(!=)(.+)]\.(\S+)', 'feelFilter(\\1,"\\2","\\4","\\3","\\5")'), # implement a simple filter
(r'(.+)\[(\S+)?([=<>])(.+)]\.(\S+)', 'feelFilter(\\1,"\\2",\\4,"\\3","\\5")'), # implement a simple filter
(r'(.+)\[(\S+)?(<=)(.+)]', 'feelFilter(\\1,"\\2","\\4","\\3")'), # implement a simple filter
(r'(.+)\[(\S+)?(>=)(.+)]', 'feelFilter(\\1,"\\2","\\4","\\3")'), # implement a simple filter
(r'(.+)\[(\S+)?(!=)(.+)]', 'feelFilter(\\1,"\\2","\\4","\\3")'), # implement a simple filter
(r'(.+)\[(\S+)?([=<>])(.+)]','feelFilter(\\1,"\\2","\\4","\\3")'), # implement a simple filter
(r'[\]\(]([^\[\]\(\)]+?)[.]{2}([^\[\]\(\)]+?)[\[\)]',
'FeelInterval(\\1,\\2,rightOpen=True,leftOpen=True)'), # open both
# parse dot.dict for several different edge cases
# make sure that it begins with a letter character - otherwise we
# may get float numbers.
# will not work for cases where we do something like:
# x contains(this.dotdict.item)
# and it may be difficult, because we do not want to replace for the case of
# somedict.keys() - because that is actually in the tests.
# however, it would be fixed by doing:
# x contains( this.dotdict.item )
('true','True'),
('false','False')
]
externalFuncs = {
'feelConvertTime':feelConvertTime,
'FeelInterval':FeelInterval,
'FeelNot':FeelNot,
'Decimal':Decimal,
'feelConcatenate': feelConcatenate,
'feelAppend': feelAppend,
'feelFilter': feelFilter,
'feelNow': feelNow,
'FeelContains': FeelContains,
'datetime':datetime,
'feelParseISODuration': feelParseISODuration,
'feelGregorianDOW':feelGregorianDOW,
}
class FeelLikeScriptEngine(PythonScriptEngine):
"""
This should serve as a base for all scripting & expression evaluation
operations that are done within both BPMN and BMN. Eventually it will also
serve as a base for FEEL expressions as well
If you are uncomfortable with the use of eval() and exec, then you should
provide a specialised subclass that parses and executes the scripts /
expressions in a mini-language of your own.
"""
def __init__(self, environment=None):
warnings.warn(
'The FEEL script engine is deprecated and will be removed in the next release',
DeprecationWarning,
stacklevel=2,
)
super().__init__(environment=environment)
def validate(self, expression):
super().validate(self.patch_expression(expression))
def patch_expression(self, invalid_python, lhs=''):
if invalid_python is None:
return None
proposed_python = invalid_python
for transformation in fixes:
if isinstance(transformation[1], str):
proposed_python = re.sub(transformation[0], transformation[1], proposed_python)
else:
for x in re.findall(transformation[0], proposed_python):
if '.' in(x):
proposed_python = proposed_python.replace(x, transformation[1](x))
if lhs is not None:
proposed_python = lhs + proposed_python
return proposed_python
def evaluate(self, task, expression, external_context=None):
if external_context is None:
external_context = {}
return self._evaluate(expression, task.data, external_context=external_context)
def execute(self, task, script, data, external_context=None):
"""
Execute the script, within the context of the specified task
"""
if external_context is None:
external_context = {}
external_context.update(externalFuncs)
return super().execute(task, script, external_context)
def _evaluate(self, expression, context, task=None, external_context=None):
"""
Evaluate the given expression, within the context of the given task and
return the result.
"""
if external_context is None:
external_context = {}
external_context.update(externalFuncs)
revised = self.patch_expression(expression)
return self.environment.evaluate(revised, context, external_context=external_context)
| 12,566 | Python | .py | 277 | 37.509025 | 120 | 0.577658 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,106 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/script_engine/__init__.py | # Copyright (C) 2012 Matthew Hampton, 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from .python_engine import PythonScriptEngine, TaskDataEnvironment
from .python_environment import BasePythonScriptEngineEnvironment | 962 | Python | .py | 20 | 47.1 | 69 | 0.803609 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,107 | python_engine.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/script_engine/python_engine.py | # Copyright (C) 2020 Kelly McDonald, 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import ast
import sys
import traceback
import warnings
from SpiffWorkflow.exceptions import SpiffWorkflowException
from SpiffWorkflow.bpmn.exceptions import WorkflowTaskException
from .python_environment import TaskDataEnvironment
class PythonScriptEngine(object):
"""
This should serve as a base for all scripting & expression evaluation
operations that are done within both BPMN and BMN. Eventually it will also
serve as a base for FEEL expressions as well
If you are uncomfortable with the use of eval() and exec, then you should
provide a specialised subclass that parses and executes the scripts /
expressions in a different way.
"""
def __init__(self, environment=None):
self.environment = environment or TaskDataEnvironment()
def validate(self, expression):
ast.parse(expression)
def evaluate(self, task, expression, external_context=None):
"""
Evaluate the given expression, within the context of the given task and
return the result.
"""
try:
return self.environment.evaluate(expression, task.data, external_context)
except SpiffWorkflowException as se:
se.add_note(f"Error evaluating expression '{expression}'")
raise se
except Exception as e:
raise WorkflowTaskException(f"Error evaluating expression '{expression}'", task=task, exception=e)
def execute(self, task, script, external_context=None):
"""Execute the script, within the context of the specified task."""
try:
return self.environment.execute(script, task.data, external_context or {})
except Exception as err:
wte = self.create_task_exec_exception(task, script, err)
raise wte
def call_service(self, operation_name, operation_params, task_data):
"""Override to control how external services are called from service tasks."""
warnings.warn(
'In the next release, implementation of this method will be moved to the scripting environment',
DeprecationWarning,
stacklevel=2,
)
# Ideally, this method would look like call_service(self, task, operation_name, operation_params)
return self.environment.call_service(operation_name, operation_params, task_data)
def create_task_exec_exception(self, task, script, err):
line_number, error_line = self.get_error_line_number_and_content(script, err)
if isinstance(err, SpiffWorkflowException):
err.line_number = line_number
err.error_line = error_line
err.add_note(f"Python script error on line {line_number}: '{error_line}'")
return err
detail = err.__class__.__name__
if len(err.args) > 0:
detail += ":" + err.args[0]
return WorkflowTaskException(detail, task=task, exception=err, line_number=line_number, error_line=error_line)
def get_error_line_number_and_content(self, script, err):
line_number = 0
error_line = ''
if isinstance(err, SyntaxError):
line_number = err.lineno
else:
cl, exc, tb = sys.exc_info()
# Loop back through the stack trace to find the file called
# 'string' - which is the script we are executing, then use that
# to parse and pull out the offending line.
for frame_summary in traceback.extract_tb(tb):
if frame_summary.filename == '<string>':
line_number = frame_summary.lineno
if line_number > 0:
error_line = script.splitlines()[line_number - 1]
return line_number, error_line
| 4,540 | Python | .py | 93 | 41.408602 | 118 | 0.690643 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,108 | python_environment.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/script_engine/python_environment.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import copy
class BasePythonScriptEngineEnvironment:
def __init__(self, environment_globals=None):
self.globals = environment_globals or {}
def evaluate(self, expression, context, external_context=None):
raise NotImplementedError("Subclass must implement this method")
def execute(self, script, context, external_context=None):
raise NotImplementedError("Subclass must implement this method")
def call_service(self, operation_name, operation_params, task_data):
raise NotImplementedError("To call external services override the script engine and implement `call_service`.")
class TaskDataEnvironment(BasePythonScriptEngineEnvironment):
def evaluate(self, expression, context, external_context=None):
my_globals = copy.copy(self.globals) # else we pollute all later evals.
self._prepare_context(context)
my_globals.update(external_context or {})
my_globals.update(context)
return eval(expression, my_globals)
def execute(self, script, context, external_context=None):
self.check_for_overwrite(context, external_context or {})
my_globals = copy.copy(self.globals)
self._prepare_context(context)
my_globals.update(external_context or {})
context.update(my_globals)
try:
exec(script, context)
finally:
self._remove_globals_and_functions_from_context(context, external_context)
return True
def _prepare_context(self, context):
pass
def _remove_globals_and_functions_from_context(self, context, external_context=None):
"""When executing a script, don't leave the globals, functions
and external methods in the context that we have modified."""
for k in list(context):
if k == "__builtins__" or \
hasattr(context[k], '__call__') or \
k in self.globals or \
external_context and k in external_context:
context.pop(k)
def check_for_overwrite(self, context, external_context):
"""It's possible that someone will define a variable with the
same name as a pre-defined script, rendering the script un-callable.
This results in a nearly indecipherable error. Better to fail
fast with a sensible error message."""
func_overwrites = set(self.globals).intersection(context)
func_overwrites.update(set(external_context).intersection(context))
if len(func_overwrites) > 0:
msg = f"You have task data that overwrites a predefined " \
f"function(s). Please change the following variable or " \
f"field name(s) to something else: {func_overwrites}"
raise ValueError(msg)
| 3,602 | Python | .py | 69 | 44.753623 | 119 | 0.699432 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,109 | event.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/util/event.py | class BpmnEvent:
def __init__(self, event_definition, payload=None, correlations=None, target=None):
self.event_definition = event_definition
self.payload = payload
self.correlations = correlations or {}
self.target = target
class PendingBpmnEvent:
def __init__(self, name, event_type, value=None):
self.name = name
self.event_type = event_type
self.value = value | 429 | Python | .py | 11 | 32.090909 | 87 | 0.664269 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,110 | subworkflow.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/util/subworkflow.py | # Copyright (C) 2012 Matthew Hampton, 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow import Workflow
from SpiffWorkflow.exceptions import TaskNotFoundException
from .task import BpmnTaskIterator
class BpmnBaseWorkflow(Workflow):
def __init__(self, spec, **kwargs):
super().__init__(spec, **kwargs)
if len(spec.data_objects) > 0:
self.data['data_objects'] = {}
@property
def data_objects(self):
return self.data.get('data_objects', {})
def get_tasks_iterator(self, first_task=None, **kwargs):
return BpmnTaskIterator(first_task or self.task_tree, **kwargs)
class BpmnSubWorkflow(BpmnBaseWorkflow):
def __init__(self, spec, parent_task_id, top_workflow, **kwargs):
self.parent_task_id = parent_task_id
self.top_workflow = top_workflow
self.correlations = {}
self.depth = self._calculate_depth()
super().__init__(spec, **kwargs)
@property
def script_engine(self):
return self.top_workflow.script_engine
@property
def parent_workflow(self):
task = self.top_workflow.get_task_from_id(self.parent_task_id)
return task.workflow
def _calculate_depth(self):
current, depth = self, 0
while current.parent_workflow is not None:
depth += 1
current = current.parent_workflow
return depth
def get_task_from_id(self, task_id):
return self.tasks.get(task_id)
| 2,229 | Python | .py | 53 | 36.830189 | 71 | 0.707407 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,111 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/util/__init__.py | # Copyright (C) 2012 Matthew Hampton, 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from .event import BpmnEvent, PendingBpmnEvent | 875 | Python | .py | 19 | 45.052632 | 69 | 0.792056 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,112 | task.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/util/task.py | # Copyright (C) 2012 Matthew Hampton, 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.util.task import TaskFilter, TaskIterator, TaskState
from SpiffWorkflow.bpmn.specs.mixins.events.event_types import CatchingEvent
class BpmnTaskFilter(TaskFilter):
def __init__(self, catches_event=None, lane=None, **kwargs):
super().__init__(**kwargs)
self.catches_event = catches_event
self.lane = lane
def matches(self, task):
def _catches_event(task):
return isinstance(task.task_spec, CatchingEvent) and task.task_spec.catches(task, self.catches_event)
if not super().matches(task):
return False
if not (self.catches_event is None or _catches_event(task)):
return False
if not (self.lane is None or task.task_spec.lane == self.lane):
return False
return True
class BpmnTaskIterator(TaskIterator):
def __init__(self, task, end_at_spec=None, max_depth=1000, depth_first=True, skip_subprocesses=False, task_filter=None, **kwargs):
task_filter = task_filter or BpmnTaskFilter(**kwargs)
super().__init__(task, end_at_spec, max_depth, depth_first, task_filter)
self.skip_subprocesses = skip_subprocesses
def _next(self):
if not self.task_list:
raise StopIteration()
task = self.task_list.pop(0)
subprocess = task.workflow.top_workflow.subprocesses.get(task.id)
if (task._children or subprocess is not None) and \
(task.state >= self.min_state or subprocess is not None) and \
self.depth < self.max_depth and \
task.task_spec.name != self.end_at_spec:
# Do not descend into a completed subprocess to look for unfinished tasks.
if (
subprocess is None
or self.skip_subprocesses
or (task.state >= TaskState.FINISHED_MASK and self.task_filter.state <= TaskState.FINISHED_MASK)
):
subprocess_tasks = []
else:
subprocess_tasks = [subprocess.task_tree]
if self.depth_first:
next_tasks = subprocess_tasks + task.children
self.task_list = next_tasks + self.task_list
else:
next_tasks = task.children + subprocess_tasks
self.task_list.extend(next_tasks)
self._update_depth(task)
elif self.depth_first and self.task_list:
self._handle_leaf_depth(task)
return task
| 3,320 | Python | .py | 68 | 40.147059 | 134 | 0.665631 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,113 | diff.py | sartography_SpiffWorkflow/SpiffWorkflow/bpmn/util/diff.py | from SpiffWorkflow import TaskState
from SpiffWorkflow.bpmn.specs.mixins.multiinstance_task import LoopTask
from .task import BpmnTaskFilter
class SpecDiff:
"""This class is used to hold results for comparisions between two workflow specs.
Attributes:
added (list(`TaskSpec`)): task specs from the new version that cannot be aligned
alignment (dict): a mapping of old task spec to new
comparisons (dict): a mapping of old task spec to changed attributes
Properties:
removed (list of `TaskSpec`: specs from the original that cannot be aligned
changed (dict): a filtered version of comparisons that contains only changed items
The chief basis for alignment is `TaskSpec.name` (ie, the BPMN ID of the spec): if the IDs are identical,
it is assumed the task specs correspond. If a spec in the old version does not have an ID in the new,
some attempt to match based on inputs and outputs is made.
The general procdedure is to attempt to align as many tasks based on ID as possible first, and then
attempt to match by other means while backing out of the traversal.
Updates are organized primarily by the specs from the original version.
"""
def __init__(self, registry, original, new):
"""Constructor for a spec diff.
Args:
registry (`DictionaryConverter`): a serislizer registry
original (`BpmnProcessSpec`): the original spec
new (`BpmnProcessSpec`): the spec to compare
Aligns specs from the original with specs from the new workflow and checks each aligned pair
for chames.
"""
self.added = [spec for spec in new.task_specs.values() if spec.name not in original.task_specs]
self.alignment = {}
self.comparisons = {}
self._registry = registry
self._align(original.start, original, new)
@property
def removed(self):
"""Task specs from the old version that were removed from the new"""
return [orig for orig, new in self.alignment.items() if new is None]
@property
def changed(self):
"""Task specs with updated attributes"""
return dict((ts, changes) for ts, changes in self.comparisons.items() if changes)
def _align(self, spec, original, new):
candidate = new.task_specs.get(spec.name)
self.alignment[spec] = candidate
if candidate is not None:
self.comparisons[spec] = self._compare_task_specs(spec, candidate)
# Traverse the spec, prioritizing matching by name
# Without this starting point, alignment would be way too difficult
for output in spec.outputs:
if output not in self.alignment:
self._align(output, original, new)
# If name matching fails, attempt to align by structure
if candidate is None:
self._search_unmatched(spec)
# Multiinstance task specs aren't reachable via task outputs
if isinstance(spec, LoopTask):
original_child = original.task_specs.get(spec.task_spec)
self.alignment[original_child] = new.task_specs.get(original_child.name)
if self.alignment[original_child] is None:
aligned = self.alignment[spec]
if aligned is not None and isinstance(aligned, LoopTask):
self.alignment[original_child] = new.task_specs.get(aligned.task_spec)
if self.alignment[original_child] is not None:
self.comparisons[original_child] = self._compare_task_specs(original_child, self.alignment[original_child])
def _search_unmatched(self, spec):
# If any outputs were matched, we can use its unmatched inputs as candidates
for match in self._substitutions(spec.outputs):
for parent in [ts for ts in match.inputs if ts in self.added]:
if self._aligned(spec.outputs, parent.outputs):
path = [parent] # We may need to check ancestor inputs as well as this spec's inputs
searched = [] # We have to keep track of what we've looked at in case of loops
self._find_ancestor(spec, path, searched)
def _find_ancestor(self, spec, path, searched):
if path[-1] not in searched:
searched.append(path[-1])
# Stop if we reach a previously matched spec or if an ancestor's inputs match
if path[-1] not in self.added or self._aligned(spec.inputs, path[-1].inputs):
self.alignment[spec] = path[0]
if path[0] in self.added:
self.added.remove(path[0])
self.comparisons[spec] = self._compare_task_specs(spec, path[0])
else:
for parent in [ts for ts in path[-1].inputs if ts not in searched]:
self._find_ancestor(spec, path + [parent], searched)
def _substitutions(self, spec_list, skip_unaligned=True):
subs = [self.alignment.get(ts) for ts in spec_list]
return [ts for ts in subs if ts is not None] if skip_unaligned else subs
def _aligned(self, original, candidates):
subs = self._substitutions(original, skip_unaligned=False)
return len(subs) == len(candidates) and \
all(first is not None and first.name == second.name for first, second in zip(subs, candidates))
def _compare_task_specs(self, spec, candidate):
s1 = self._registry.convert(spec)
s2 = self._registry.convert(candidate)
if s1.get('typename') != s2.get('typename'):
return ['typename']
else:
return [key for key, value in s1.items() if s2.get(key) != value]
class WorkflowDiff:
"""This class is used to determine which tasks in a workflow are affected by updates
to its WorkflowSpec.
Attributes
removed (list(`Task`)): a list of tasks whose specs do not exist in the new version
changed (list(`Task`)): a list of tasks with aligned specs where attributes have changed
alignment (dict): a mapping of old task spec to new task spec
"""
def __init__(self, workflow, spec_diff):
self.removed = []
self.changed = []
self.alignment = {}
self._align(workflow, spec_diff)
def _align(self, workflow, spec_diff):
for task in workflow.get_tasks(skip_subprocesses=True):
if task.task_spec in spec_diff.changed:
self.changed.append(task)
if task.task_spec in spec_diff.removed:
self.removed.append(task)
else:
self.alignment[task] = spec_diff.alignment[task.task_spec]
def diff_dependencies(registry, original, new):
"""Helper method for comparing sets of spec dependencies.
Args:
registry (`DictionaryConverter`): a serislizer registry
original (dict): the name -> `BpmnProcessSpec` mapping for the original spec
new (dict): the name -> `BpmnProcessSpec` mapping for the updated spec
Returns:
a tuple of:
mapping from name -> `SpecDiff` (or None) for each original dependency
list of names of specs in the new dependencies that did not previously exist
"""
result = {}
subprocesses = {}
for name, spec in original.items():
if name in new:
result[name] = SpecDiff(registry, spec, new[name])
else:
result[name] = None
return result, [name for name in new if name not in original]
def diff_workflow(registry, workflow, new_spec, new_dependencies):
"""Helper method to handle diffing a workflow and all its dependencies at once.
Args:
registry (`DictionaryConverter`): a serislizer registry
workflow (`BpmnWorkflow`): a workflow instance
new_spec (`BpmnProcessSpec`): the new top level spec
new_depedencies (dict): a dictionary of name -> `BpmnProcessSpec`
Returns:
tuple of `WorkflowDiff` and mapping of subworkflow id -> `WorkflowDiff`
This method checks the top level workflow against the new spec as well as any
existing subprocesses for missing or updated specs.
"""
spec_diff = SpecDiff(registry, workflow.spec, new_spec)
top_diff = WorkflowDiff(workflow, spec_diff)
sp_diffs = {}
for sp_id, sp in workflow.subprocesses.items():
if sp.spec.name in new_dependencies:
dep_diff = SpecDiff(registry, sp.spec, new_dependencies[sp.spec.name])
sp_diffs[sp_id] = WorkflowDiff(sp, dep_diff)
else:
sp_diffs[sp_id] = None
return top_diff, sp_diffs
def filter_tasks(tasks, **kwargs):
"""Applies task filtering arguments to a list of tasks.
Args:
tasks (list(`Task`)): a list of of tasks
Keyword Args:
any keyword arg that may be passed to `BpmnTaskFilter`
Returns:
a list containing tasks matching the filter
"""
task_filter = BpmnTaskFilter(**kwargs)
return [t for t in tasks if task_filter.matches(t)]
def migrate_workflow(diff, workflow, spec, reset_mask=None):
"""Update the spec for workflow.
Args:
diff (`WorkflowDiff`): the diff of this workflow and spec
workflow (`BpmnWorkflow` or `BpmnSubWorkflow`): the workflow
spec (`BpmnProcessSpec`): the new spec
Keyword Args:
reset_mask (`TaskState`): reset and repredict tasks in this state
Returns
a list of deleted `Task`
The default rest_mask is TaskState.READY|TaskState.WAITING but can be overridden.
"""
workflow.spec = spec
for task in workflow.tasks.values():
if diff.alignment.get(task) is not None:
task.task_spec = diff.alignment.get(task)
default_mask = TaskState.READY|TaskState.WAITING
removed_tasks = []
for task in list(workflow.get_tasks(state=reset_mask or default_mask, skip_subprocesses=True)):
# In some cases, completed tasks with ready or waiting children could get removed
# (for example, in cycle timer). If a task has already been removed from the tree, ignore it.
if task.id in workflow.tasks:
removed_tasks.extend(task.reset_branch(None))
if workflow.last_task not in workflow.tasks:
workflow.last_task = None
return removed_tasks | 10,291 | Python | .py | 197 | 43.401015 | 123 | 0.664343 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,114 | deep_merge.py | sartography_SpiffWorkflow/SpiffWorkflow/util/deep_merge.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
class DeepMerge(object):
# Merges two deeply nested json-like dictionaries,
# useful for updating things like task data.
# I know in my heart, that this isn't completely correct.
# But I don't want to create a dependency, and this is passing
# all the failure points I've found so far. So I'll just
# keep plugging away at it.
# This will merge all updates from b into a, but it does not
# remove items from a that are not in b. Passing a prune of
# true, and it WILL remove items in a that are not in b.
@staticmethod
def merge(a, b, path=None):
"merges b into a"
if path is None:
path = []
for key in b:
if key in a:
if a[key] == b[key]:
continue
elif isinstance(a[key], dict) and isinstance(b[key], dict):
DeepMerge.merge(a[key], b[key], path + [str(key)])
elif isinstance(a[key], list) and isinstance(b[key], list):
DeepMerge.merge_array(a[key], b[key], path + [str(key)])
else:
a[key] = b[key] # Just overwrite the value in a.
else:
a[key] = b[key]
return a
@staticmethod
def merge_array(a, b, path=None):
for idx, val in enumerate(b):
if isinstance(b[idx], dict): # Recurse back on dictionaries.
# If lists of dictionaries get out of order, this might
# cause us some pain.
if len(a) > idx:
a[idx] = DeepMerge.merge(a[idx], b[idx], path + [str(idx)])
else:
a.append(b[idx])
else: # Just merge whatever it is back in.
a.extend(x for x in b if x not in a)
# Trim a back to the length of b. In the end, the two arrays should match
del a[len(b):]
| 2,713 | Python | .py | 60 | 36.666667 | 82 | 0.617447 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,115 | levenshtein.py | sartography_SpiffWorkflow/SpiffWorkflow/util/levenshtein.py | # This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from difflib import ndiff
def distance(str1, str2):
counter = {"+": 0, "-": 0}
distance = 0
for edit_code, *_ in ndiff(str1, str2):
if edit_code == " ":
distance += max(counter.values())
counter = {"+": 0, "-": 0}
else:
counter[edit_code] += 1
distance += max(counter.values())
return distance
def most_similar(value, item_list, limit):
distances = [(key, distance(value, key)) for key in item_list]
distances.sort(key=lambda x: x[1])
return [x[0] for x in distances[:limit]]
| 1,337 | Python | .py | 32 | 37.96875 | 69 | 0.700539 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,116 | event.py | sartography_SpiffWorkflow/SpiffWorkflow/util/event.py | # Copyright (C) 2007-2010 Samuel Abels.
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# DO NOT EDIT THIS FILE.
# THIS CODE IS TAKE FROM Exscript.util:
# https://github.com/knipknap/exscript/tree/master/src/Exscript/util
#
"""
A simple signal/event mechanism.
"""
from threading import Lock
from . import weakmethod
class Event(object):
"""
A simple signal/event mechanism, to be used like this::
def mycallback(arg, **kwargs):
print arg, kwargs['foo']
myevent = Event()
myevent.connect(mycallback)
myevent.emit('test', foo = 'bar')
# Or just: myevent('test', foo = 'bar')
"""
def __init__(self):
"""
Constructor.
"""
# To save memory, we do NOT init the subscriber attributes with
# lists. Unfortunately this makes a lot of the code in this class
# more messy than it should be, but events are used so widely in
# Exscript that this change makes a huge difference to the memory
# footprint.
self.lock = None
self.weak_subscribers = None
self.hard_subscribers = None
def __call__(self, *args, **kwargs):
"""
Like emit().
"""
return self.emit(*args, **kwargs)
def connect(self, callback, *args, **kwargs):
"""
Connects the event with the given callback.
When the signal is emitted, the callback is invoked.
.. note::
The signal handler is stored with a hard reference, so you
need to make sure to call :class:`disconnect()` if you want the
handler
to be garbage collected.
:type callback: object
:param callback: The callback function.
:type args: tuple
:param args: Optional arguments passed to the callback.
:type kwargs: dict
:param kwargs: Optional keyword arguments passed to the callback.
"""
if self.is_connected(callback):
raise AttributeError('callback is already connected')
if self.hard_subscribers is None:
self.hard_subscribers = []
self.hard_subscribers.append((callback, args, kwargs))
def listen(self, callback, *args, **kwargs):
"""
Like :class:`connect()`, but uses a weak reference instead of a
normal reference.
The signal is automatically disconnected as soon as the handler
is garbage collected.
.. note::
Storing signal handlers as weak references means that if
your handler is a local function, it may be garbage collected. To
prevent this, use :class:`connect()` instead.
:type callback: object
:param callback: The callback function.
:type args: tuple
:param args: Optional arguments passed to the callback.
:type kwargs: dict
:param kwargs: Optional keyword arguments passed to the callback.
:rtype: :class:`Exscript.util.weakmethod.WeakMethod`
:returns: The newly created weak reference to the callback.
"""
if self.lock is None:
self.lock = Lock()
with self.lock:
if self.is_connected(callback):
raise AttributeError('callback is already connected')
if self.weak_subscribers is None:
self.weak_subscribers = []
ref = weakmethod.ref(callback, self._try_disconnect)
self.weak_subscribers.append((ref, args, kwargs))
return ref
def n_subscribers(self):
"""
Returns the number of connected subscribers.
:rtype: int
:returns: The number of subscribers.
"""
hard = self.hard_subscribers and len(self.hard_subscribers) or 0
weak = self.weak_subscribers and len(self.weak_subscribers) or 0
return hard + weak
def _hard_callbacks(self):
return [s[0] for s in self.hard_subscribers]
def _weakly_connected_index(self, callback):
if self.weak_subscribers is None:
return None
weak = [s[0].get_function() for s in self.weak_subscribers]
try:
return weak.index(callback)
except ValueError:
return None
def is_connected(self, callback):
"""
Returns True if the event is connected to the given function.
:type callback: object
:param callback: The callback function.
:rtype: bool
:returns: Whether the signal is connected to the given function.
"""
index = self._weakly_connected_index(callback)
if index is not None:
return True
if self.hard_subscribers is None:
return False
return callback in self._hard_callbacks()
def emit(self, *args, **kwargs):
"""
Emits the signal, passing the given arguments to the callbacks.
If one of the callbacks returns a value other than None, no further
callbacks are invoked and the return value of the callback is
returned to the caller of emit().
:type args: tuple
:param args: Optional arguments passed to the callbacks.
:type kwargs: dict
:param kwargs: Optional keyword arguments passed to the callbacks.
:rtype: object
:returns: Returns None if all callbacks returned None. Returns
the return value of the last invoked callback otherwise.
"""
if self.hard_subscribers is not None:
for callback, user_args, user_kwargs in self.hard_subscribers:
kwargs.update(user_kwargs)
result = callback(*args + user_args, **kwargs)
if result is not None:
return result
if self.weak_subscribers is not None:
for callback, user_args, user_kwargs in self.weak_subscribers:
kwargs.update(user_kwargs)
# Even though WeakMethod notifies us when the underlying
# function is destroyed, and we remove the item from the
# the list of subscribers, there is no guarantee that
# this notification has already happened because the garbage
# collector may run while this loop is executed.
# Disabling the garbage collector temporarily also does
# not work, because other threads may be trying to do
# the same, causing yet another race condition.
# So the only solution is to skip such functions.
cb_func = callback.get_function()
if cb_func is None:
continue
result = cb_func(*args + user_args, **kwargs)
if result is not None:
return result
def _try_disconnect(self, ref):
"""
Called by the weak reference when its target dies.
In other words, we can assert that self.weak_subscribers is not
None at this time.
"""
with self.lock:
weak = [s[0] for s in self.weak_subscribers]
try:
index = weak.index(ref)
except ValueError:
# subscriber was already removed by a call to disconnect()
pass
else:
self.weak_subscribers.pop(index)
def disconnect(self, callback):
"""
Disconnects the signal from the given function.
:type callback: object
:param callback: The callback function.
"""
if self.weak_subscribers is not None:
with self.lock:
index = self._weakly_connected_index(callback)
if index is not None:
self.weak_subscribers.pop(index)[0]
if self.hard_subscribers is not None:
try:
index = self._hard_callbacks().index(callback)
except ValueError:
pass
else:
self.hard_subscribers.pop(index)
def disconnect_all(self):
"""
Disconnects all connected functions from all signals.
"""
self.hard_subscribers = None
self.weak_subscribers = None
| 8,966 | Python | .py | 215 | 32.055814 | 77 | 0.619768 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,117 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/util/__init__.py | # This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA | 770 | Python | .py | 16 | 47.1875 | 69 | 0.788079 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,118 | weakmethod.py | sartography_SpiffWorkflow/SpiffWorkflow/util/weakmethod.py | # Copyright (C) 2007-2010 Samuel Abels.
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
#
# DO NOT EDIT THIS FILE.
# THIS CODE IS TAKE FROM Exscript.util:
# https://github.com/knipknap/exscript/tree/master/src/Exscript/util
#
"""
Weak references to bound and unbound methods.
"""
import weakref
class DeadMethodCalled(Exception):
"""
Raised by :class:`WeakMethod` if it is called when the referenced object
is already dead.
"""
pass
class WeakMethod(object):
"""
Do not create this class directly; use :class:`ref()` instead.
"""
__slots__ = 'name', 'callback'
def __init__(self, name, callback):
"""
Constructor. Do not use directly, use :class:`ref()` instead.
"""
self.name = name
self.callback = callback
def _dead(self, ref):
if self.callback is not None:
self.callback(self)
def get_function(self):
"""
Returns the referenced method/function if it is still alive.
Returns None otherwise.
:rtype: callable|None
:returns: The referenced function if it is still alive.
"""
raise NotImplementedError()
def isalive(self):
"""
Returns True if the referenced function is still alive, False
otherwise.
:rtype: bool
:returns: Whether the referenced function is still alive.
"""
return self.get_function() is not None
def __call__(self, *args, **kwargs):
"""
Proxied to the underlying function or method. Raises
:class:`DeadMethodCalled` if the referenced function is dead.
:rtype: object :returns: Whatever the referenced function returned.
"""
method = self.get_function()
if method is None:
raise DeadMethodCalled('method called on dead object ' + self.name)
method(*args, **kwargs)
class _WeakMethodBound(WeakMethod):
__slots__ = 'name', 'callback', 'f', 'c'
def __init__(self, f, callback):
name = f.__self__.__class__.__name__ + '.' + f.__func__.__name__
WeakMethod.__init__(self, name, callback)
self.f = f.__func__
self.c = weakref.ref(f.__self__, self._dead)
def get_function(self):
cls = self.c()
if cls is None:
return None
return getattr(cls, self.f.__name__)
class _WeakMethodFree(WeakMethod):
__slots__ = 'name', 'callback', 'f'
def __init__(self, f, callback):
WeakMethod.__init__(self, f.__class__.__name__, callback)
self.f = weakref.ref(f, self._dead)
def get_function(self):
return self.f()
def ref(function, callback=None):
"""
Returns a weak reference to the given method or function.
If the callback argument is not None, it is called as soon
as the referenced function is garbage deleted.
:type function: callable
:param function: The function to reference.
:type callback: callable
:param callback: Called when the function dies.
"""
try:
function.__func__
except AttributeError:
return _WeakMethodFree(function, callback)
return _WeakMethodBound(function, callback)
| 3,930 | Python | .py | 107 | 30.953271 | 79 | 0.657798 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,119 | task.py | sartography_SpiffWorkflow/SpiffWorkflow/util/task.py | # Copyright (C) 2007 Samuel Abels, 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from functools import reduce
class TaskState:
"""Int values corresponding to `Task` states.
The following states may exist:
- LIKELY: The task is a descendant of the default branch of a Choice task.
- MAYBE: The task is a descendant of a conditional branch of a Choice task.
- FUTURE: The task will definitely be reached in the future, regardless of
which choices the user makes within the workflow.
- WAITING: The task has been reached but the conditions for running this
task have not been met. For example, a Join task will be WAITING until
all predecessors are completed.
- READY: The conditions for running the task are now satisfied. All
predecessors have completed and the task may now be run using `Task.run`.
- STARTED: `Task.run` has been called, but the task returned
before finishing. SpiffWorkflow does not track tasks in this state, as
it is currently unused by any of the included task specs.
- COMPLETED: The task was regularily completed.
- ERROR: The task did not complete because an error occurred when it was run.
- CANCELLED: The task was cancelled.
Notes:
- LIKELY and MAYBE tasks are merely predicted/guessed, so those tasks may be
removed from the tree at runtime later.
- The STARTED state will eventually be used by SpiffWorkflow. The intention
is that this state would be used if a time-consuming and/or resource intensive
operation was being carried out external to the workflow. The task could
return immediately and its branch would not proceed until the workflow application
called `Task.complete`, but without blocking other branches that were ready to
execute.
"""
MAYBE = 1
LIKELY = 2
FUTURE = 4
WAITING = 8
READY = 16
STARTED = 32
COMPLETED = 64
ERROR = 128
CANCELLED = 256
FINISHED_MASK = CANCELLED | ERROR | COMPLETED
DEFINITE_MASK = FUTURE | WAITING | READY | STARTED
PREDICTED_MASK = LIKELY | MAYBE
NOT_FINISHED_MASK = PREDICTED_MASK | DEFINITE_MASK
ANY_MASK = FINISHED_MASK | NOT_FINISHED_MASK
_names = ['MAYBE', 'LIKELY', 'FUTURE', 'WAITING', 'READY', 'STARTED', 'COMPLETED', 'ERROR', 'CANCELLED']
_values = [1, 2, 4, 8, 16, 32, 64, 128, 256]
@classmethod
def get_name(cls, state):
"""Get the name of the state or mask from the value.
Args:
state (int): a `TaskState` value
Returns:
str: the name of the state
"""
names = dict(zip(cls._values, cls._names))
names.update({
TaskState.FINISHED_MASK: 'FINISHED_MASK',
TaskState.DEFINITE_MASK: 'DEFINITE_MASK',
TaskState.PREDICTED_MASK: 'PREDICTED_MASK',
TaskState.NOT_FINISHED_MASK: 'NOT_FINISHED_MASK',
TaskState.ANY_MASK: 'ANY_MASK',
})
return names.get(state) or '|'.join([ names.get(v) for v in cls._values if v & state ])
@classmethod
def get_value(cls, name):
"""Get the value for the state name (case insensitive).
Args:
name (str): the state name
Returns:
int: the value of the state
"""
values = dict(zip(cls._names, cls._values))
values.update({
'FINISHED_MASK': TaskState.FINISHED_MASK,
'DEFINITE_MASK': TaskState.DEFINITE_MASK,
'PREDICTED_MASK': TaskState.PREDICTED_MASK,
'NOT_FINISHED_MASK': TaskState.NOT_FINISHED_MASK,
'ANY_MASK': TaskState.ANY_MASK,
})
names = name.upper().split('|')
if len(names) == 1:
return values.get(name.upper(), 0)
else:
return reduce(lambda x, y: x | y, [TaskState.get_value(v) for v in name.upper().split('|')])
class TaskFilter:
"""This is the default class for filtering during task iteration.
Note:
All filter values must match. Default filter values match any task.
"""
def __init__(self, state=TaskState.ANY_MASK, updated_ts=0, manual=None, spec_name=None, spec_class=None):
"""
Parameters:
state (`TaskState`): limit results to state or mask
updated_ts (float): limit results to tasks updated at or after this timestamp
manual (bool): match the value of the `TaskSpec`'s manual attribute
spec_name (str): match the value of the `TaskSpec`'s name
spec_class (`TaskSpec`): match the value of the `TaskSpec`'s class
"""
self.state = state
self.updated_ts = updated_ts
self.manual = manual
self.spec_name = spec_name
self.spec_class = spec_class
def matches(self, task):
"""Check if the task matches this filter.
Args:
task (`Task`): the task to check
Returns:
bool: indicates whether the task matches
"""
if not task.has_state(self.state):
return False
if not task.last_state_change >= self.updated_ts:
return False
if not (self.manual is None or task.task_spec.manual == self.manual):
return False
if not (self.spec_name is None or task.task_spec.name == self.spec_name):
return False
if not (self.spec_class is None or isinstance(task.task_spec, self.spec_class)):
return False
return True
class TaskIterator:
"""Default task iteration class."""
def __init__(self, task, end_at_spec=None, max_depth=1000, depth_first=True, task_filter=None, **kwargs):
"""Iterate over the task tree and return the tasks matching the filter parameters.
Args:
task (`Task`): the task to start from
Keyword Args:
end_at (str):stop when a task spec with this name is reached
max_depth (int): stop when this depth is reached
depth_first (bool): return results in depth first order
task_filter (`TaskFilter`): return only tasks matching this filter
Notes:
Keyword args not used by this class will be passed into `TaskFilter` if no `task_filter` is provided.
This is for convenience (filter values can be used directly from `Workflow.get_tasks`) as well as
backwards compatilibity for queries about `TaskState`.
"""
self.task_filter = task_filter or TaskFilter(**kwargs)
self.end_at_spec = end_at_spec
self.max_depth = max_depth
self.depth_first = depth_first
self.task_list = [task]
self.depth = 0
# Figure out which states need to be traversed.
# Predicted tasks can follow definite tasks but not vice versa; definite tasks can follow finished tasks but not vice versa
# The dream is for a child task to always have a lower task state than its parent; currently we have parents that wait for
# their children
if self.task_filter.state & TaskState.PREDICTED_MASK:
self.min_state = TaskState.MAYBE
elif self.task_filter.state & TaskState.DEFINITE_MASK:
self.min_state = TaskState.FUTURE
else:
self.min_state = TaskState.COMPLETED
def __iter__(self):
return self
def __next__(self):
task = self._next()
while not self.task_filter.matches(task):
task = self._next()
return task
def _next(self):
if not self.task_list:
raise StopIteration()
task = self.task_list.pop(0)
if task._children and \
task.state >= self.min_state and \
self.depth < self.max_depth and \
task.task_spec.name != self.end_at_spec:
if self.depth_first:
self.task_list = task.children + self.task_list
else:
self.task_list.extend(task.children)
self._update_depth(task)
elif self.depth_first and self.task_list:
self._handle_leaf_depth(task)
return task
def _update_depth(self, task):
if self.depth_first:
# Since we visit the children before siblings, we always increment depth when adding children
self.depth += 1
else:
# In this case, we have to check for a common ancestor at the same depth
first, second = task, self.task_list[0]
for i in range(self.depth):
first = first.parent if first is not None else None
second = second.parent if second is not None else None
if first != second:
self.depth += 1
def _handle_leaf_depth(self, task):
ancestor = self.task_list[0].parent
current = task.parent
while current is not None and current != ancestor:
current = current.parent
self.depth -= 1
| 9,885 | Python | .py | 211 | 37.540284 | 131 | 0.639908 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,120 | compat.py | sartography_SpiffWorkflow/SpiffWorkflow/util/compat.py | # This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from threading import Lock
class mutex(object):
def __init__(self):
self.lock = Lock()
def lock(self):
raise NotImplementedError
def test(self):
has = self.lock.acquire(blocking=False)
if has:
self.lock.release()
return has
def testandset(self):
return self.lock.acquire(blocking=False)
def unlock(self):
self.lock.release()
| 1,192 | Python | .py | 31 | 34.354839 | 69 | 0.730269 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,121 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/__init__.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA | 805 | Python | .py | 18 | 43.777778 | 69 | 0.786802 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,122 | event_parsers.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/parser/event_parsers.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.bpmn.parser.event_parsers import (
EventDefinitionParser,
StartEventParser,
EndEventParser,
IntermediateCatchEventParser,
IntermediateThrowEventParser,
BoundaryEventParser
)
from SpiffWorkflow.camunda.specs.event_definitions import MessageEventDefinition
from SpiffWorkflow.bpmn.parser.util import one
class CamundaEventDefinitionParser(EventDefinitionParser):
def parse_message_event(self, message_event):
"""Parse a Camunda message event node."""
message_ref = message_event.get('messageRef')
if message_ref:
message = one(self.doc_xpath('.//bpmn:message[@id="%s"]' % message_ref))
name = message.get('name')
correlations = self.get_message_correlations(message_ref)
else:
name = message_event.getparent().get('name')
correlations = {}
payload = self.attribute('expression', 'camunda', message_event)
result_var = self.attribute('resultVariable', 'camunda', message_event)
return MessageEventDefinition(name, correlations, payload, result_var)
# This really sucks, but it's still better than copy-pasting a bunch of code a million times
# The parser "design" makes it impossible to do anything sensible of intuitive here
class CamundaStartEventParser(CamundaEventDefinitionParser, StartEventParser):
def create_task(self):
return StartEventParser.create_task(self)
class CamundaEndEventParser(CamundaEventDefinitionParser, EndEventParser):
def create_task(self):
return EndEventParser.create_task(self)
class CamundaIntermediateCatchEventParser(CamundaEventDefinitionParser, IntermediateCatchEventParser):
def create_task(self):
return IntermediateCatchEventParser.create_task(self)
class CamundaIntermediateThrowEventParser(CamundaEventDefinitionParser, IntermediateThrowEventParser):
def create_task(self):
return IntermediateThrowEventParser.create_task(self)
class CamundaBoundaryEventParser(CamundaEventDefinitionParser, BoundaryEventParser):
def create_task(self):
return BoundaryEventParser.create_task(self)
| 2,960 | Python | .py | 59 | 45.491525 | 102 | 0.773199 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,123 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/parser/__init__.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from .CamundaParser import CamundaParser | 847 | Python | .py | 19 | 43.578947 | 69 | 0.792271 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,124 | task_spec.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/parser/task_spec.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.bpmn.specs.data_spec import TaskDataReference
from SpiffWorkflow.bpmn.parser.util import one
from SpiffWorkflow.bpmn.parser.ValidationException import ValidationException
from SpiffWorkflow.bpmn.parser.TaskParser import TaskParser
from SpiffWorkflow.bpmn.parser.task_parsers import SubprocessParser
from SpiffWorkflow.camunda.specs.business_rule_task import BusinessRuleTask
from SpiffWorkflow.camunda.specs.multiinstance_task import SequentialMultiInstanceTask, ParallelMultiInstanceTask
from SpiffWorkflow.camunda.specs.user_task import Form, FormField, EnumFormField
CAMUNDA_MODEL_NS = 'http://camunda.org/schema/1.0/bpmn'
class CamundaTaskParser(TaskParser):
def parse_extensions(self, node=None):
extensions = {}
extension_nodes = self.xpath('.//bpmn:extensionElements/camunda:properties/camunda:property')
for ex_node in extension_nodes:
extensions[ex_node.get('name')] = ex_node.get('value')
return extensions
def _add_multiinstance_task(self, loop_characteristics):
sequential = loop_characteristics.get('isSequential') == 'true'
prefix = 'bpmn:multiInstanceLoopCharacteristics'
cardinality = self.xpath(f'./{prefix}/bpmn:loopCardinality')
cardinality = cardinality[0].text if len(cardinality) > 0 else None
collection = self.attribute('collection', 'camunda', loop_characteristics)
if cardinality is None and collection is None:
self.raise_validation_exception('A multiinstance task must specify a cardinality or a collection')
element_var = self.attribute('elementVariable', 'camunda', loop_characteristics)
condition = self.xpath(f'./{prefix}/bpmn:completionCondition')
condition = condition[0].text if len(condition) > 0 else None
original = self.spec.task_specs.pop(self.task.name)
# We won't include the data input, because sometimes it is the collection, and other times it
# is the cardinality. The old MI task evaluated the cardinality at run time and treated it like
# a cardinality if it evaluated to an int, and as the data input if if evaluated to a collection
# I highly doubt that this is the way Camunda worked then, and I know that's not how it works
# now, and I think we should ultimately replace this with something that corresponds to how
# Camunda actually handles things; however, for the time being, I am just going to try to
# replicate the old behavior as closely as possible.
# In our subclassed MI task, we'll update the BPMN multiinstance attributes when the task starts.
params = {
'task_spec': '',
'cardinality': cardinality,
'data_output': TaskDataReference(collection) if collection is not None else None,
'output_item': TaskDataReference(element_var) if element_var is not None else None,
'condition': condition,
}
if sequential:
self.task = SequentialMultiInstanceTask(self.spec, original.name, **params)
else:
self.task = ParallelMultiInstanceTask(self.spec, original.name, **params)
self._copy_task_attrs(original, loop_characteristics)
class BusinessRuleTaskParser(CamundaTaskParser):
dmn_debug = None
def create_task(self):
decision_ref = self.get_decision_ref(self.node)
return BusinessRuleTask(self.spec, self.bpmn_id,
dmnEngine=self.process_parser.parser.get_engine(decision_ref, self.node),
**self.bpmn_attributes)
@staticmethod
def get_decision_ref(node):
return node.attrib['{' + CAMUNDA_MODEL_NS + '}decisionRef']
class UserTaskParser(CamundaTaskParser):
"""Base class for parsing User Tasks"""
def create_task(self):
form = self.get_form()
return self.spec_class(self.spec, self.bpmn_id, form=form, **self.bpmn_attributes)
def get_form(self):
"""Camunda provides a simple form builder, this will extract the
details from that form and construct a form model from it. """
form = Form()
try:
form.key = self.attribute('formKey', 'camunda')
except KeyError:
return form
for xml_field in self.xpath('.//camunda:formData/camunda:formField'):
if xml_field.get('type') == 'enum':
field = self.get_enum_field(xml_field)
else:
field = FormField()
field.id = xml_field.get('id')
field.type = xml_field.get('type')
field.label = xml_field.get('label')
field.default_value = xml_field.get('defaultValue')
prefix = '{' + self.nsmap.get('camunda') + '}'
for child in xml_field:
if child.tag == f'{prefix}properties':
for p in child:
field.add_property(p.get('id'), p.get('value'))
if child.tag == f'{prefix}validation':
for v in child:
field.add_validation(v.get('name'), v.get('config'))
form.add_field(field)
return form
def get_enum_field(self, xml_field):
field = EnumFormField()
for child in xml_field:
if child.tag == '{' + self.nsmap.get('camunda') + '}value':
field.add_option(child.get('id'), child.get('name'))
return field
# These classes need to be able to use the overriden _add_multiinstance_task method
# so they have to inherit from CamundaTaskParser. Therefore, the parsers have to just
# be copied, because both they and the CamundaTaskParser inherit from the base task
# parser. I am looking forward to the day when I can replaced all of this with
# something sane and sensible.
class SubWorkflowParser(CamundaTaskParser):
def create_task(self):
subworkflow_spec = SubprocessParser.get_subprocess_spec(self)
return self.spec_class(self.spec, self.bpmn_id, subworkflow_spec=subworkflow_spec, **self.bpmn_attributes)
class CallActivityParser(CamundaTaskParser):
"""Parses a CallActivity node."""
def create_task(self):
subworkflow_spec = SubprocessParser.get_call_activity_spec(self)
return self.spec_class(self.spec, self.bpmn_id, subworkflow_spec=subworkflow_spec, **self.bpmn_attributes)
class ScriptTaskParser(TaskParser):
"""
Parses a script task
"""
def create_task(self):
script = self.get_script()
return self.spec_class(self.spec, self.bpmn_id, script=script, **self.bpmn_attributes)
def get_script(self):
"""
Gets the script content from the node. A subclass can override this
method, if the script needs to be pre-parsed. The result of this call
will be passed to the Script Engine for execution.
"""
try:
return one(self.xpath('.//bpmn:script')).text
except AssertionError as ae:
raise ValidationException(
"Invalid Script Task. No Script Provided. " + str(ae),
node=self.node, file_name=self.filename)
| 7,994 | Python | .py | 147 | 45.952381 | 114 | 0.683995 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,125 | CamundaParser.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/parser/CamundaParser.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.dmn.parser.BpmnDmnParser import BpmnDmnParser
from SpiffWorkflow.bpmn.parser.BpmnParser import full_tag, DEFAULT_NSMAP
from SpiffWorkflow.bpmn.specs.defaults import (
ManualTask,
NoneTask,
ScriptTask,
CallActivity,
TransactionSubprocess,
StartEvent,
EndEvent,
IntermediateThrowEvent,
IntermediateCatchEvent,
BoundaryEvent
)
from SpiffWorkflow.camunda.specs.business_rule_task import BusinessRuleTask
from SpiffWorkflow.camunda.specs.user_task import UserTask
from SpiffWorkflow.camunda.parser.task_spec import (
CamundaTaskParser,
BusinessRuleTaskParser,
UserTaskParser,
CallActivityParser,
SubWorkflowParser,
ScriptTaskParser,
CAMUNDA_MODEL_NS
)
from .event_parsers import (
CamundaStartEventParser,
CamundaEndEventParser,
CamundaIntermediateCatchEventParser,
CamundaIntermediateThrowEventParser,
CamundaBoundaryEventParser,
)
NSMAP = DEFAULT_NSMAP.copy()
NSMAP['camunda'] = CAMUNDA_MODEL_NS
class CamundaParser(BpmnDmnParser):
OVERRIDE_PARSER_CLASSES = {
full_tag('userTask'): (UserTaskParser, UserTask),
full_tag('startEvent'): (CamundaStartEventParser, StartEvent),
full_tag('endEvent'): (CamundaEndEventParser, EndEvent),
full_tag('intermediateCatchEvent'): (CamundaIntermediateCatchEventParser, IntermediateCatchEvent),
full_tag('intermediateThrowEvent'): (CamundaIntermediateThrowEventParser, IntermediateThrowEvent),
full_tag('boundaryEvent'): (CamundaBoundaryEventParser, BoundaryEvent),
full_tag('businessRuleTask'): (BusinessRuleTaskParser, BusinessRuleTask),
full_tag('task'): (CamundaTaskParser, NoneTask),
full_tag('manualTask'): (CamundaTaskParser, ManualTask),
full_tag('scriptTask'): (ScriptTaskParser, ScriptTask),
full_tag('subProcess'): (SubWorkflowParser, CallActivity),
full_tag('callActivity'): (CallActivityParser, CallActivity),
full_tag('transaction'): (SubWorkflowParser, TransactionSubprocess),
}
def __init__(self, namespaces=None, validator=None):
super().__init__(namespaces=namespaces or NSMAP, validator=validator) | 2,992 | Python | .py | 70 | 38.614286 | 106 | 0.770497 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,126 | user_task.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/specs/user_task.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.bpmn.specs.defaults import UserTask as DefaultUserTask
class UserTask(DefaultUserTask):
"""Task Spec for a bpmn:userTask node with Camunda forms."""
def __init__(self, wf_spec, name, form, **kwargs):
"""
Constructor.
:param form: the information that needs to be provided by the user,
as parsed from the camunda xml file's form details.
"""
super(UserTask, self).__init__(wf_spec, name, **kwargs)
self.form = form
class FormField(object):
def __init__(self, form_type="text"):
self.id = ""
self.type = form_type
self.label = ""
self.default_value = ""
self.properties = []
self.validation = []
def add_property(self, property_id, value):
self.properties.append(FormFieldProperty(property_id, value))
def add_validation(self, name, config):
self.validation.append(FormFieldValidation(name, config))
def get_property(self, property_id):
for prop in self.properties:
if prop.id == property_id:
return prop.value
def has_property(self, property_id):
return self.get_property(property_id) is not None
def get_validation(self, name):
for v in self.validation:
if v.name == name:
return v.config
def has_validation(self, name):
return self.get_validation(name) is not None
class EnumFormField(FormField):
def __init__(self):
super(EnumFormField, self).__init__("enum")
self.options = []
def add_option(self, option_id, name):
self.options.append(EnumFormFieldOption(option_id, name))
class EnumFormFieldOption:
def __init__(self, option_id, name):
self.id = option_id
self.name = name
class FormFieldProperty:
def __init__(self, property_id, value):
self.id = property_id
self.value = value
class FormFieldValidation:
def __init__(self, name, config):
self.name = name
self.config = config
class Form:
def __init__(self,init=None):
self.key = ""
self.fields = []
if init:
self.from_dict(init)
def add_field(self, field):
self.fields.append(field)
def from_dict(self,formdict):
self.key = formdict['key']
for field in formdict['fields']:
if field['type'] == 'enum':
newfield = EnumFormField()
for option in field['options']:
newfield.add_option(option['id'], option['name'])
else:
newfield = FormField()
newfield.id = field['id']
newfield.default_value = field['default_value']
newfield.label = field['label']
newfield.type = field['type']
for prop in field['properties']:
newfield.add_property(prop['id'],prop['value'])
for validation in field['validation']:
newfield.add_validation(validation['name'],validation['config'])
self.add_field(newfield)
| 3,911 | Python | .py | 97 | 32.680412 | 80 | 0.64131 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,127 | multiinstance_task.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/specs/multiinstance_task.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.util.task import TaskState
from SpiffWorkflow.bpmn.specs.mixins import BpmnSpecMixin
from SpiffWorkflow.bpmn.specs.data_spec import TaskDataReference
from SpiffWorkflow.bpmn.specs.defaults import (
SequentialMultiInstanceTask as BpmnSequentialMITask,
ParallelMultiInstanceTask as BpmnParallelMITask,
)
# This is an abomination, but I don't see any other way replicating the older MI functionality
def update_task_spec(my_task):
task_spec = my_task.task_spec
if my_task.state != TaskState.WAITING:
# We have to fix up our state before we can run the parent update, but we still need
# to inherit our parent data.
BpmnSpecMixin._update_hook(task_spec, my_task)
my_task._set_state(TaskState.WAITING)
if task_spec.cardinality is None:
# Use the same collection for input and output
task_spec.data_input = TaskDataReference(task_spec.data_output.bpmn_id)
task_spec.input_item = TaskDataReference(task_spec.output_item.bpmn_id)
else:
cardinality = my_task.workflow.script_engine.evaluate(my_task, task_spec.cardinality)
if not isinstance(cardinality, int):
# The input data was supplied via "cardinality"
# We'll use the same reference for input and output item
task_spec.data_input = TaskDataReference(task_spec.cardinality)
task_spec.input_item = TaskDataReference(task_spec.output_item.bpmn_id) if task_spec.output_item is not None else None
task_spec.cardinality = None
else:
# This will be the index
task_spec.input_item = TaskDataReference(task_spec.output_item.bpmn_id) if task_spec.output_item is not None else None
class SequentialMultiInstanceTask(BpmnSequentialMITask):
def _update_hook(self, my_task):
update_task_spec(my_task)
return super()._update_hook(my_task)
class ParallelMultiInstanceTask(BpmnParallelMITask):
def _update_hook(self, my_task):
update_task_spec(my_task)
return super()._update_hook(my_task) | 2,885 | Python | .py | 56 | 46.232143 | 130 | 0.74379 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,128 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/specs/__init__.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from .business_rule_task import BusinessRuleTask
from .multiinstance_task import SequentialMultiInstanceTask, ParallelMultiInstanceTask
from .user_task import UserTask | 974 | Python | .py | 21 | 45.380952 | 86 | 0.804827 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,129 | event_definitions.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/specs/event_definitions.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.bpmn import BpmnEvent
from SpiffWorkflow.bpmn.specs.event_definitions import MessageEventDefinition
class MessageEventDefinition(MessageEventDefinition):
"""
Message Events have both a name and a payload.
"""
# It is not entirely clear how the payload is supposed to be handled, so I have
# deviated from what the earlier code did as little as possible, but I believe
# this should be revisited: for one thing, we're relying on some Camunda-specific
# properties.
def __init__(self, name, correlation_properties=None, expression=None, result_var=None, **kwargs):
super(MessageEventDefinition, self).__init__(name, correlation_properties, **kwargs)
self.expression = expression
self.result_var = result_var
def throw(self, my_task):
result = my_task.workflow.script_engine.evaluate(my_task, self.expression)
payload = {
'payload': result,
'result_var': self.result_var
}
event = BpmnEvent(self, payload=payload)
my_task.workflow.top_workflow.catch(event)
def update_internal_data(self, my_task, event):
if event.payload.get('result_var') is None:
event.payload['result_var'] = f'{my_task.task_spec.name}_Response'
my_task.internal_data[self.name] = event.payload
def update_task_data(self, my_task):
event_data = my_task.internal_data.get(self.name)
my_task.data[event_data['result_var']] = event_data['payload']
def reset(self, my_task):
my_task.internal_data.pop('result_var', None)
super(MessageEventDefinition, self).reset(my_task)
| 2,465 | Python | .py | 50 | 44.2 | 102 | 0.722361 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,130 | business_rule_task.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/specs/business_rule_task.py | from SpiffWorkflow.dmn.specs import BusinessRuleTaskMixin
from SpiffWorkflow.bpmn.specs.mixins import BpmnSpecMixin
class BusinessRuleTask(BusinessRuleTaskMixin, BpmnSpecMixin):
pass | 187 | Python | .py | 4 | 44.75 | 61 | 0.885246 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,131 | event_definition.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/serializer/event_definition.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.bpmn.serializer.helpers.spec import EventDefinitionConverter
from ..specs.event_definitions import MessageEventDefinition
class MessageEventDefinitionConverter(EventDefinitionConverter):
def to_dict(self, event_definition):
dct = super().to_dict(event_definition)
dct['correlation_properties'] = self.correlation_properties_to_dict(event_definition.correlation_properties)
dct['expression'] = event_definition.expression
dct['result_var'] = event_definition.result_var
return dct
def from_dict(self, dct):
dct['correlation_properties'] = self.correlation_properties_from_dict(dct['correlation_properties'])
event_definition = super().from_dict(dct)
return event_definition
| 1,575 | Python | .py | 31 | 47.322581 | 116 | 0.77128 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,132 | config.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/serializer/config.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from copy import deepcopy
from SpiffWorkflow.bpmn.serializer import DEFAULT_CONFIG
from SpiffWorkflow.bpmn.serializer.config import (
UserTask as DefaultUserTask,
ParallelMultiInstanceTask as DefaultParallelMITask,
SequentialMultiInstanceTask as DefaultSequentialMITask,
MessageEventDefinition as DefaultMessageEventDefinition,
)
from SpiffWorkflow.camunda.specs.user_task import UserTask
from SpiffWorkflow.camunda.specs.multiinstance_task import ParallelMultiInstanceTask, SequentialMultiInstanceTask
from SpiffWorkflow.camunda.specs.business_rule_task import BusinessRuleTask
from SpiffWorkflow.camunda.specs.event_definitions import MessageEventDefinition
from SpiffWorkflow.bpmn.serializer.default.task_spec import MultiInstanceTaskConverter
from SpiffWorkflow.dmn.serializer.task_spec import BaseBusinessRuleTaskConverter
from .task_spec import UserTaskConverter
from .event_definition import MessageEventDefinitionConverter
CAMUNDA_CONFIG = deepcopy(DEFAULT_CONFIG)
CAMUNDA_CONFIG.pop(DefaultUserTask)
CAMUNDA_CONFIG.pop(DefaultParallelMITask)
CAMUNDA_CONFIG.pop(DefaultSequentialMITask)
CAMUNDA_CONFIG.pop(DefaultMessageEventDefinition)
CAMUNDA_CONFIG[UserTask] = UserTaskConverter
CAMUNDA_CONFIG[ParallelMultiInstanceTask] = MultiInstanceTaskConverter
CAMUNDA_CONFIG[SequentialMultiInstanceTask] = MultiInstanceTaskConverter
CAMUNDA_CONFIG[BusinessRuleTask] = BaseBusinessRuleTaskConverter
CAMUNDA_CONFIG[MessageEventDefinition] = MessageEventDefinitionConverter
| 2,303 | Python | .py | 44 | 50.772727 | 113 | 0.856889 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,133 | __init__.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/serializer/__init__.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from .config import CAMUNDA_CONFIG as DEFAULT_CONFIG | 859 | Python | .py | 19 | 44.210526 | 69 | 0.790476 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,134 | task_spec.py | sartography_SpiffWorkflow/SpiffWorkflow/camunda/serializer/task_spec.py | # Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
from SpiffWorkflow.bpmn.serializer.helpers.spec import TaskSpecConverter
from SpiffWorkflow.camunda.specs.user_task import UserTask, Form
class UserTaskConverter(TaskSpecConverter):
def to_dict(self, spec):
dct = self.get_default_attributes(spec)
dct['form'] = self.form_to_dict(spec.form)
return dct
def from_dict(self, dct):
dct['form'] = Form(init=dct['form'])
return self.task_spec_from_dict(dct)
def form_to_dict(self, form):
dct = {'key': form.key, 'fields': []}
for field in form.fields:
new = {
'id': field.id,
'default_value': field.default_value,
'label': field.label,
'type': field.type,
'properties': [ prop.__dict__ for prop in field.properties ],
'validation': [ val.__dict__ for val in field.validation ],
}
if field.type == "enum":
new['options'] = [ opt.__dict__ for opt in field.options ]
dct['fields'].append(new)
return dct
| 1,893 | Python | .py | 43 | 37.372093 | 77 | 0.664135 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,135 | test_times.py | sartography_SpiffWorkflow/scripts/test_times.py | #!/usr/bin/env python
# Copyright (C) 2023 Sartography
#
# This file is part of SpiffWorkflow.
#
# SpiffWorkflow is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
#
# SpiffWorkflow is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import re
import sys
def regex_line_parser(pattern, handler):
regex = re.compile(pattern)
def parser(line):
match = regex.match(line)
if match:
return handler(match)
return None
return parser
def rstripped(match):
return match.group(0).rstrip()
def tupled(match):
return (match.group(1), match.group(2))
def parse(lines):
test_file = None
timing = None
test_file_timings = []
test_file_line_parser = regex_line_parser('.*?Test.py', rstripped)
timing_line_parser = regex_line_parser('Ran (.*) tests? in (.*)', tupled)
for line in lines:
if test_file is None:
test_file = test_file_line_parser(line)
elif timing is None:
timing = timing_line_parser(line)
if test_file is not None and timing is not None:
test_file_timings.append((test_file, timing))
test_file = None
timing = None
return test_file_timings
def report(parsed_data):
lines = [
'| Method | Time | Tests Ran |',
'|----|----|----|',
]
sorted_data = sorted(parsed_data, key=lambda d: d[1][1], reverse=True)
for d in sorted_data:
lines.append(f'| {d[0]} | {d[1][1]} | {d[1][0]} |')
print('\n'.join(lines))
if __name__ == '__main__':
data = sys.stdin.readlines()
parsed_data = parse(data)
report(parsed_data)
| 2,232 | Python | .py | 62 | 31.145161 | 77 | 0.666821 | sartography/SpiffWorkflow | 1,663 | 310 | 6 | LGPL-3.0 | 9/5/2024, 5:08:37 PM (Europe/Amsterdam) |
1,136 | setup.py | urwid_urwid/setup.py | # Urwid setup.py exports the useful bits
# Copyright (C) 2004-2014 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
from __future__ import annotations
from setuptools import setup
setup(
name="urwid",
url="https://urwid.org/",
python_requires=">3.7",
setup_requires=[
"setuptools >= 61.0.0",
"setuptools_scm[toml]>=7.0",
"wheel",
],
)
| 1,143 | Python | .py | 30 | 35.533333 | 78 | 0.70991 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,137 | edit.py | urwid_urwid/examples/edit.py | #!/usr/bin/env python
#
# Urwid example lazy text editor suitable for tabbed and format=flowed text
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example lazy text editor suitable for tabbed and flowing text
Features:
- custom list walker for lazily loading text file
Usage:
edit.py <filename>
"""
from __future__ import annotations
import sys
import typing
import urwid
class LineWalker(urwid.ListWalker):
"""ListWalker-compatible class for lazily reading file contents."""
def __init__(self, name: str) -> None:
# do not overcomplicate example
self.file = open(name, encoding="utf-8") # noqa: SIM115 # pylint: disable=consider-using-with
self.lines = []
self.focus = 0
def __del__(self) -> None:
self.file.close()
def get_focus(self):
return self._get_at_pos(self.focus)
def set_focus(self, focus) -> None:
self.focus = focus
self._modified()
def get_next(self, position: int) -> tuple[urwid.Edit, int] | tuple[None, None]:
return self._get_at_pos(position + 1)
def get_prev(self, position: int) -> tuple[urwid.Edit, int] | tuple[None, None]:
return self._get_at_pos(position - 1)
def read_next_line(self) -> str:
"""Read another line from the file."""
next_line = self.file.readline()
if not next_line or next_line[-1:] != "\n":
# no newline on last line of file
self.file = None
else:
# trim newline characters
next_line = next_line[:-1]
expanded = next_line.expandtabs()
edit = urwid.Edit("", expanded, allow_tab=True)
edit.edit_pos = 0
edit.original_text = next_line
self.lines.append(edit)
return next_line
def _get_at_pos(self, pos: int) -> tuple[urwid.Edit, int] | tuple[None, None]:
"""Return a widget for the line number passed."""
if pos < 0:
# line 0 is the start of the file, no more above
return None, None
if len(self.lines) > pos:
# we have that line so return it
return self.lines[pos], pos
if self.file is None:
# file is closed, so there are no more lines
return None, None
assert pos == len(self.lines), "out of order request?" # noqa: S101 # "assert" is ok in examples
self.read_next_line()
return self.lines[-1], pos
def split_focus(self) -> None:
"""Divide the focus edit widget at the cursor location."""
focus = self.lines[self.focus]
pos = focus.edit_pos
edit = urwid.Edit("", focus.edit_text[pos:], allow_tab=True)
edit.original_text = ""
focus.set_edit_text(focus.edit_text[:pos])
edit.edit_pos = 0
self.lines.insert(self.focus + 1, edit)
def combine_focus_with_prev(self) -> None:
"""Combine the focus edit widget with the one above."""
above, _ = self.get_prev(self.focus)
if above is None:
# already at the top
return
focus = self.lines[self.focus]
above.set_edit_pos(len(above.edit_text))
above.set_edit_text(above.edit_text + focus.edit_text)
del self.lines[self.focus]
self.focus -= 1
def combine_focus_with_next(self) -> None:
"""Combine the focus edit widget with the one below."""
below, _ = self.get_next(self.focus)
if below is None:
# already at bottom
return
focus = self.lines[self.focus]
focus.set_edit_text(focus.edit_text + below.edit_text)
del self.lines[self.focus + 1]
class EditDisplay:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "default", "default"),
("foot", "dark cyan", "dark blue", "bold"),
("key", "light cyan", "dark blue", "underline"),
]
footer_text = (
"foot",
[
"Text Editor ",
("key", "F5"),
" save ",
("key", "F8"),
" quit",
],
)
def __init__(self, name: str) -> None:
self.save_name = name
self.walker = LineWalker(name)
self.listbox = urwid.ListBox(self.walker)
self.footer = urwid.AttrMap(urwid.Text(self.footer_text), "foot")
self.view = urwid.Frame(urwid.AttrMap(self.listbox, "body"), footer=self.footer)
def main(self) -> None:
self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_keypress)
self.loop.run()
def unhandled_keypress(self, k: str | tuple[str, int, int, int]) -> bool | None:
"""Last resort for keypresses."""
if k == "f5":
self.save_file()
elif k == "f8":
raise urwid.ExitMainLoop()
elif k == "delete":
# delete at end of line
self.walker.combine_focus_with_next()
elif k == "backspace":
# backspace at beginning of line
self.walker.combine_focus_with_prev()
elif k == "enter":
# start new line
self.walker.split_focus()
# move the cursor to the new line and reset pref_col
self.loop.process_input(["down", "home"])
elif k == "right":
w, pos = self.walker.get_focus()
w, pos = self.walker.get_next(pos)
if w:
self.listbox.set_focus(pos, "above")
self.loop.process_input(["home"])
elif k == "left":
w, pos = self.walker.get_focus()
w, pos = self.walker.get_prev(pos)
if w:
self.listbox.set_focus(pos, "below")
self.loop.process_input(["end"])
else:
return None
return True
def save_file(self) -> None:
"""Write the file out to disk."""
lines = []
walk = self.walker
for edit in walk.lines:
# collect the text already stored in edit widgets
if edit.original_text.expandtabs() == edit.edit_text:
lines.append(edit.original_text)
else:
lines.append(re_tab(edit.edit_text))
# then the rest
while walk.file is not None:
lines.append(walk.read_next_line())
# write back to disk
with open(self.save_name, "w", encoding="utf-8") as outfile:
prefix = ""
for line in lines:
outfile.write(prefix + line)
prefix = "\n"
def re_tab(s) -> str:
"""Return a tabbed string from an expanded one."""
line = []
p = 0
for i in range(8, len(s), 8):
if s[i - 2 : i] == " ":
# collapse two or more spaces into a tab
line.append(f"{s[p:i].rstrip()}\t")
p = i
if p == 0:
return s
line.append(s[p:])
return "".join(line)
def main() -> None:
try:
name = sys.argv[1]
# do not overcomplicate example
assert open(name, "ab") # noqa: SIM115,S101 # pylint: disable=consider-using-with
except OSError:
sys.stderr.write(__doc__)
return
EditDisplay(name).main()
if __name__ == "__main__":
main()
| 8,054 | Python | .py | 207 | 30.454106 | 106 | 0.584189 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,138 | browse.py | urwid_urwid/examples/browse.py | #!/usr/bin/env python
#
# Urwid example lazy directory browser / tree view
# Copyright (C) 2004-2011 Ian Ward
# Copyright (C) 2010 Kirk McDonald
# Copyright (C) 2010 Rob Lanphier
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example lazy directory browser / tree view
Features:
- custom selectable widgets for files and directories
- custom message widgets to identify access errors and empty directories
- custom list walker for displaying widgets in a tree fashion
- outputs a quoted list of files and directories "selected" on exit
"""
from __future__ import annotations
import itertools
import os
import re
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Hashable
class FlagFileWidget(urwid.TreeWidget):
# apply an attribute to the expand/unexpand icons
unexpanded_icon = urwid.AttrMap(urwid.TreeWidget.unexpanded_icon, "dirmark")
expanded_icon = urwid.AttrMap(urwid.TreeWidget.expanded_icon, "dirmark")
def __init__(self, node: urwid.TreeNode) -> None:
super().__init__(node)
# insert an extra AttrWrap for our own use
self._w = urwid.AttrMap(self._w, None)
self.flagged = False
self.update_w()
def selectable(self) -> bool:
return True
def keypress(self, size, key: str) -> str | None:
"""allow subclasses to intercept keystrokes"""
key = super().keypress(size, key)
if key:
key = self.unhandled_keys(size, key)
return key
def unhandled_keys(self, size, key: str) -> str | None:
"""
Override this method to intercept keystrokes in subclasses.
Default behavior: Toggle flagged on space, ignore other keys.
"""
if key == " ":
self.flagged = not self.flagged
self.update_w()
return None
return key
def update_w(self) -> None:
"""Update the attributes of self.widget based on self.flagged."""
if self.flagged:
self._w.attr_map = {None: "flagged"}
self._w.focus_map = {None: "flagged focus"}
else:
self._w.attr_map = {None: "body"}
self._w.focus_map = {None: "focus"}
class FileTreeWidget(FlagFileWidget):
"""Widget for individual files."""
def __init__(self, node: FileNode) -> None:
super().__init__(node)
path = node.get_value()
add_widget(path, self)
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
return self.get_node().get_key()
class EmptyWidget(urwid.TreeWidget):
"""A marker for expanded directories with no contents."""
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
return ("flag", "(empty directory)")
class ErrorWidget(urwid.TreeWidget):
"""A marker for errors reading directories."""
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
return ("error", "(error/permission denied)")
class DirectoryWidget(FlagFileWidget):
"""Widget for a directory."""
def __init__(self, node: DirectoryNode) -> None:
super().__init__(node)
path = node.get_value()
add_widget(path, self)
self.expanded = starts_expanded(path)
self.update_expanded_icon()
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
node = self.get_node()
if node.get_depth() == 0:
return "/"
return node.get_key()
class FileNode(urwid.TreeNode):
"""Metadata storage for individual files"""
def __init__(self, path: str, parent: urwid.ParentNode | None = None) -> None:
depth = path.count(dir_sep())
key = os.path.basename(path)
super().__init__(path, key=key, parent=parent, depth=depth)
def load_parent(self) -> DirectoryNode:
parentname, _myname = os.path.split(self.get_value())
parent = DirectoryNode(parentname)
parent.set_child_node(self.get_key(), self)
return parent
def load_widget(self) -> FileTreeWidget:
return FileTreeWidget(self)
class EmptyNode(urwid.TreeNode):
def load_widget(self) -> EmptyWidget:
return EmptyWidget(self)
class ErrorNode(urwid.TreeNode):
def load_widget(self) -> ErrorWidget:
return ErrorWidget(self)
class DirectoryNode(urwid.ParentNode):
"""Metadata storage for directories"""
def __init__(self, path: str, parent: urwid.ParentNode | None = None) -> None:
if path == dir_sep():
depth = 0
key = None
else:
depth = path.count(dir_sep())
key = os.path.basename(path)
super().__init__(path, key=key, parent=parent, depth=depth)
def load_parent(self) -> DirectoryNode:
parentname, _myname = os.path.split(self.get_value())
parent = DirectoryNode(parentname)
parent.set_child_node(self.get_key(), self)
return parent
def load_child_keys(self):
dirs = []
files = []
try:
path = self.get_value()
# separate dirs and files
for a in os.listdir(path):
if os.path.isdir(os.path.join(path, a)):
dirs.append(a)
else:
files.append(a)
except OSError:
depth = self.get_depth() + 1
self._children[None] = ErrorNode(self, parent=self, key=None, depth=depth)
return [None]
# sort dirs and files
dirs.sort(key=alphabetize)
files.sort(key=alphabetize)
# store where the first file starts
self.dir_count = len(dirs)
# collect dirs and files together again
keys = dirs + files
if len(keys) == 0:
depth = self.get_depth() + 1
self._children[None] = EmptyNode(self, parent=self, key=None, depth=depth)
keys = [None]
return keys
def load_child_node(self, key) -> EmptyNode | DirectoryNode | FileNode:
"""Return either a FileNode or DirectoryNode"""
index = self.get_child_index(key)
if key is None:
return EmptyNode(None)
path = os.path.join(self.get_value(), key)
if index < self.dir_count:
return DirectoryNode(path, parent=self)
path = os.path.join(self.get_value(), key)
return FileNode(path, parent=self)
def load_widget(self) -> DirectoryWidget:
return DirectoryWidget(self)
class DirectoryBrowser:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "black", "light gray"),
("flagged", "black", "dark green", ("bold", "underline")),
("focus", "light gray", "dark blue", "standout"),
("flagged focus", "yellow", "dark cyan", ("bold", "standout", "underline")),
("head", "yellow", "black", "standout"),
("foot", "light gray", "black"),
("key", "light cyan", "black", "underline"),
("title", "white", "black", "bold"),
("dirmark", "black", "dark cyan", "bold"),
("flag", "dark gray", "light gray"),
("error", "dark red", "light gray"),
]
footer_text: typing.ClassVar[list[tuple[str, str] | str]] = [
("title", "Directory Browser"),
" ",
("key", "UP"),
",",
("key", "DOWN"),
",",
("key", "PAGE UP"),
",",
("key", "PAGE DOWN"),
" ",
("key", "SPACE"),
" ",
("key", "+"),
",",
("key", "-"),
" ",
("key", "LEFT"),
" ",
("key", "HOME"),
" ",
("key", "END"),
" ",
("key", "Q"),
]
def __init__(self) -> None:
cwd = os.getcwd()
store_initial_cwd(cwd)
self.header = urwid.Text("")
self.listbox = urwid.TreeListBox(urwid.TreeWalker(DirectoryNode(cwd)))
self.listbox.offset_rows = 1
self.footer = urwid.AttrMap(urwid.Text(self.footer_text), "foot")
self.view = urwid.Frame(
urwid.AttrMap(
urwid.ScrollBar(
self.listbox,
thumb_char=urwid.ScrollBar.Symbols.FULL_BLOCK,
trough_char=urwid.ScrollBar.Symbols.LITE_SHADE,
),
"body",
),
header=urwid.AttrMap(self.header, "head"),
footer=self.footer,
)
def main(self) -> None:
"""Run the program."""
self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input)
self.loop.run()
# on exit, write the flagged filenames to the console
names = [escape_filename_sh(x) for x in get_flagged_names()]
print(" ".join(names))
def unhandled_input(self, k: str | tuple[str, int, int, int]) -> None:
# update display of focus directory
if k in {"q", "Q"}:
raise urwid.ExitMainLoop()
def main():
DirectoryBrowser().main()
#######
# global cache of widgets
_widget_cache = {}
def add_widget(path, widget):
"""Add the widget for a given path"""
_widget_cache[path] = widget
def get_flagged_names() -> list[str]:
"""Return a list of all filenames marked as flagged."""
names = [w.get_node().get_value() for w in _widget_cache.values() if w.flagged]
return names
######
# store path components of initial current working directory
_initial_cwd = []
def store_initial_cwd(name: str) -> None:
"""Store the initial current working directory path components."""
_initial_cwd.clear()
_initial_cwd.extend(name.split(dir_sep()))
def starts_expanded(name: str) -> bool:
"""Return True if directory is a parent of initial cwd."""
if name == "/":
return True
path_elements = name.split(dir_sep())
if len(path_elements) > len(_initial_cwd):
return False
return path_elements == _initial_cwd[: len(path_elements)]
def escape_filename_sh(name: str) -> str:
"""Return a hopefully safe shell-escaped version of a filename."""
# check whether we have unprintable characters
for ch in name:
if ord(ch) < 32:
# found one so use the ansi-c escaping
return escape_filename_sh_ansic(name)
# all printable characters, so return a double-quoted version
name = name.replace("\\", "\\\\").replace('"', '\\"').replace("`", "\\`").replace("$", "\\$")
return f'"{name}"'
def escape_filename_sh_ansic(name: str) -> str:
"""Return an ansi-c shell-escaped version of a filename."""
out = []
# gather the escaped characters into a list
for ch in name:
if ord(ch) < 32:
out.append(f"\\x{ord(ch):02x}")
elif ch == "\\":
out.append("\\\\")
else:
out.append(ch)
# slap them back together in an ansi-c quote $'...'
return f"$'{''.join(out)}'"
SPLIT_RE = re.compile(r"[a-zA-Z]+|\d+")
def alphabetize(s: str) -> list[str]:
L = []
for isdigit, group in itertools.groupby(SPLIT_RE.findall(s), key=str.isdigit):
if isdigit:
L.extend(("", int(n)) for n in group)
else:
L.append(("".join(group).lower(), 0))
return L
def dir_sep() -> str:
"""Return the separator used in this os."""
return getattr(os.path, "sep", "/")
if __name__ == "__main__":
main()
| 12,258 | Python | .py | 309 | 32.142395 | 97 | 0.60113 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,139 | dialog.py | urwid_urwid/examples/dialog.py | #!/usr/bin/env python
#
# Urwid example similar to dialog(1) program
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example similar to dialog(1) program
"""
from __future__ import annotations
import sys
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Hashable
class DialogExit(Exception):
pass
class DialogDisplay:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "black", "light gray", "standout"),
("border", "black", "dark blue"),
("shadow", "white", "black"),
("selectable", "black", "dark cyan"),
("focus", "white", "dark blue", "bold"),
("focustext", "light gray", "dark blue"),
]
def __init__(self, text, height: int | str, width: int | str, body=None) -> None:
width = int(width)
if width <= 0:
width = (urwid.RELATIVE, 80)
height = int(height)
if height <= 0:
height = (urwid.RELATIVE, 80)
self.body = body
if body is None:
# fill space with nothing
body = urwid.Filler(urwid.Divider(), urwid.TOP)
self.frame = urwid.Frame(body, focus_part="footer")
if text is not None:
self.frame.header = urwid.Pile([urwid.Text(text), urwid.Divider()])
w = self.frame
# pad area around listbox
w = urwid.Padding(w, urwid.LEFT, left=2, right=2)
w = urwid.Filler(w, urwid.TOP, urwid.RELATIVE_100, top=1, bottom=1)
w = urwid.AttrMap(w, "body")
# "shadow" effect
w = urwid.Columns([w, (2, urwid.AttrMap(urwid.Filler(urwid.Text(("border", " ")), urwid.TOP), "shadow"))])
w = urwid.Frame(w, footer=urwid.AttrMap(urwid.Text(("border", " ")), "shadow"))
# outermost border area
w = urwid.Padding(w, urwid.CENTER, width)
w = urwid.Filler(w, urwid.MIDDLE, height)
w = urwid.AttrMap(w, "border")
self.view = w
def add_buttons(self, buttons) -> None:
lines = []
for name, exitcode in buttons:
b = urwid.Button(name, self.button_press)
b.exitcode = exitcode
b = urwid.AttrMap(b, "selectable", "focus")
lines.append(b)
self.buttons = urwid.GridFlow(lines, 10, 3, 1, urwid.CENTER)
self.frame.footer = urwid.Pile([urwid.Divider(), self.buttons], focus_item=1)
def button_press(self, button) -> typing.NoReturn:
raise DialogExit(button.exitcode)
def main(self) -> tuple[int, str]:
self.loop = urwid.MainLoop(self.view, self.palette)
try:
self.loop.run()
except DialogExit as e:
return self.on_exit(e.args[0])
def on_exit(self, exitcode: int) -> tuple[int, str]:
return exitcode, ""
class InputDialogDisplay(DialogDisplay):
def __init__(self, text, height: int | str, width: int | str) -> None:
self.edit = urwid.Edit()
body = urwid.ListBox(urwid.SimpleListWalker([self.edit]))
body = urwid.AttrMap(body, "selectable", "focustext")
super().__init__(text, height, width, body)
self.frame.focus_position = "body"
def unhandled_key(self, size, k: str) -> None:
if k in {"up", "page up"}:
self.frame.focus_position = "body"
if k in {"down", "page down"}:
self.frame.focus_position = "footer"
if k == "enter":
# pass enter to the "ok" button
self.frame.focus_position = "footer"
self.view.keypress(size, k)
def on_exit(self, exitcode: int) -> tuple[int, str]:
return exitcode, self.edit.get_edit_text()
class TextDialogDisplay(DialogDisplay):
def __init__(self, file: str, height: int | str, width: int | str) -> None:
with open(file, encoding="utf-8") as f:
lines = [urwid.Text(line.rstrip()) for line in f]
# read the whole file (being slow, not lazy this time)
body = urwid.ListBox(urwid.SimpleListWalker(lines))
body = urwid.AttrMap(body, "selectable", "focustext")
super().__init__(None, height, width, body)
def unhandled_key(self, size, k: str) -> None:
if k in {"up", "page up", "down", "page down"}:
self.frame.focus_position = "body"
self.view.keypress(size, k)
self.frame.focus_position = "footer"
class ListDialogDisplay(DialogDisplay):
def __init__(
self,
text,
height: int | str,
width: int | str,
constr,
items,
has_default: bool,
) -> None:
j = []
if has_default:
k, tail = 3, ()
else:
k, tail = 2, ("no",)
while items:
j.append(items[:k] + tail)
items = items[k:]
lines = []
self.items = []
for tag, item, default in j:
w = constr(tag, default == "on")
self.items.append(w)
w = urwid.Columns([(12, w), urwid.Text(item)], 2)
w = urwid.AttrMap(w, "selectable", "focus")
lines.append(w)
lb = urwid.ListBox(urwid.SimpleListWalker(lines))
lb = urwid.AttrMap(lb, "selectable")
super().__init__(text, height, width, lb)
self.frame.focus_position = "body"
def unhandled_key(self, size, k: str) -> None:
if k in {"up", "page up"}:
self.frame.focus_position = "body"
if k in {"down", "page down"}:
self.frame.focus_position = "footer"
if k == "enter":
# pass enter to the "ok" button
self.frame.focus_position = "footer"
self.buttons.focus_position = 0
self.view.keypress(size, k)
def on_exit(self, exitcode: int) -> tuple[int, str]:
"""Print the tag of the item selected."""
if exitcode != 0:
return exitcode, ""
s = ""
for i in self.items:
if i.get_state():
s = i.get_label()
break
return exitcode, s
class CheckListDialogDisplay(ListDialogDisplay):
def on_exit(self, exitcode: int) -> tuple[int, str]:
"""
Mimic dialog(1)'s --checklist exit.
Put each checked item in double quotes with a trailing space.
"""
if exitcode != 0:
return exitcode, ""
labels = [i.get_label() for i in self.items if i.get_state()]
return exitcode, "".join(f'"{tag}" ' for tag in labels)
class MenuItem(urwid.Text):
"""A custom widget for the --menu option"""
def __init__(self, label: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None:
super().__init__(label)
self.state = False
def selectable(self) -> bool:
return True
def keypress(self, size: tuple[int] | tuple[()], key: str) -> str | None:
if key == "enter":
self.state = True
raise DialogExit(0)
return key
def mouse_event(
self,
size: tuple[int] | tuple[()],
event: str,
button: int,
col: int,
row: int,
focus: bool,
) -> bool | None:
if event == "mouse release":
self.state = True
raise DialogExit(0)
return False
def get_state(self) -> bool:
return self.state
def get_label(self) -> str:
"""Just alias to text."""
return self.text
def do_checklist(
text,
height: int,
width: int,
list_height: int,
*items,
) -> CheckListDialogDisplay:
def constr(tag, state: bool) -> urwid.CheckBox:
return urwid.CheckBox(tag, state)
d = CheckListDialogDisplay(text, height, width, constr, items, True)
d.add_buttons([("OK", 0), ("Cancel", 1)])
return d
def do_inputbox(text, height: int, width: int) -> InputDialogDisplay:
d = InputDialogDisplay(text, height, width)
d.add_buttons([("Exit", 0)])
return d
def do_menu(
text,
height: int,
width: int,
menu_height: int,
*items,
) -> ListDialogDisplay:
def constr(tag, state: bool) -> MenuItem:
return MenuItem(tag)
d = ListDialogDisplay(text, height, width, constr, items, False)
d.add_buttons([("OK", 0), ("Cancel", 1)])
return d
def do_msgbox(text, height: int, width: int) -> DialogDisplay:
d = DialogDisplay(text, height, width)
d.add_buttons([("OK", 0)])
return d
def do_radiolist(
text,
height: int,
width: int,
list_height: int,
*items,
) -> ListDialogDisplay:
radiolist = []
def constr( # pylint: disable=dangerous-default-value
tag,
state: bool,
radiolist: list[urwid.RadioButton] = radiolist,
) -> urwid.RadioButton:
return urwid.RadioButton(radiolist, tag, state)
d = ListDialogDisplay(text, height, width, constr, items, True)
d.add_buttons([("OK", 0), ("Cancel", 1)])
return d
def do_textbox(file: str, height: int, width: int) -> TextDialogDisplay:
d = TextDialogDisplay(file, height, width)
d.add_buttons([("Exit", 0)])
return d
def do_yesno(text, height: int, width: int) -> DialogDisplay:
d = DialogDisplay(text, height, width)
d.add_buttons([("Yes", 0), ("No", 1)])
return d
MODES = { # pylint: disable=consider-using-namedtuple-or-dataclass # made before argparse in stdlib
"--checklist": (do_checklist, "text height width list-height [ tag item status ] ..."),
"--inputbox": (do_inputbox, "text height width"),
"--menu": (do_menu, "text height width menu-height [ tag item ] ..."),
"--msgbox": (do_msgbox, "text height width"),
"--radiolist": (do_radiolist, "text height width list-height [ tag item status ] ..."),
"--textbox": (do_textbox, "file height width"),
"--yesno": (do_yesno, "text height width"),
}
def show_usage():
"""
Display a helpful usage message.
"""
modelist = sorted((mode, help_mode) for (mode, (fn, help_mode)) in MODES.items())
sys.stdout.write(
__doc__
+ "\n".join([f"{mode:<15} {help_mode}" for (mode, help_mode) in modelist])
+ """
height and width may be set to 0 to auto-size.
list-height and menu-height are currently ignored.
status may be either on or off.
"""
)
def main() -> None:
if len(sys.argv) < 2 or sys.argv[1] not in MODES:
show_usage()
return
# Create a DialogDisplay instance
fn, _help_mode = MODES[sys.argv[1]]
d = fn(*sys.argv[2:])
# Run it
exitcode, exitstring = d.main()
# Exit
if exitstring:
sys.stderr.write(f"{exitstring}\n")
sys.exit(exitcode)
if __name__ == "__main__":
main()
| 11,462 | Python | .py | 302 | 30.708609 | 115 | 0.594692 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,140 | terminal.py | urwid_urwid/examples/terminal.py | #!/usr/bin/env python
#
# Urwid terminal emulation widget example app
# Copyright (C) 2010 aszlig
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
from __future__ import annotations
import typing
from contextlib import suppress
import urwid
def main() -> None:
urwid.set_encoding("utf8")
term = urwid.Terminal(None, encoding="utf-8")
size_widget = urwid.Text("")
mainframe = urwid.LineBox(
urwid.Pile(
[
(urwid.WEIGHT, 70, term),
(1, urwid.Filler(size_widget)),
(1, urwid.Filler(urwid.Edit("focus test edit: "))),
]
),
)
def set_title(widget, title: str) -> None:
mainframe.set_title(title)
def execute_quit(*args, **kwargs) -> typing.NoReturn:
raise urwid.ExitMainLoop()
def handle_key(key: str | tuple[str, int, int, int]) -> None:
if key in {"q", "Q"}:
execute_quit()
def handle_resize(widget, size: tuple[int, int]) -> None:
size_widget.set_text(f"Terminal size: [{size[0]}, {size[1]}]")
urwid.connect_signal(term, "title", set_title)
urwid.connect_signal(term, "closed", execute_quit)
with suppress(NameError):
urwid.connect_signal(term, "resize", handle_resize)
# if using a version of Urwid library where vterm doesn't support
# resize, don't register the signal handler.
try:
# create Screen with bracketed paste mode support enabled
bpm_screen = urwid.display.raw.Screen(bracketed_paste_mode=True) # pylint: disable=unexpected-keyword-arg
except TypeError:
# if using a version of Urwid library that doesn't support
# bracketed paste mode, do without it.
bpm_screen = urwid.display.raw.Screen()
loop = urwid.MainLoop(mainframe, handle_mouse=False, screen=bpm_screen, unhandled_input=handle_key)
term.main_loop = loop
loop.run()
if __name__ == "__main__":
main()
| 2,710 | Python | .py | 64 | 36.875 | 114 | 0.670852 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,141 | calc.py | urwid_urwid/examples/calc.py | #!/usr/bin/env python
#
# Urwid advanced example column calculator application
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid advanced example column calculator application
Features:
- multiple separate list boxes within columns
- custom edit widget for editing calculator cells
- custom parent widget for links to other columns
- custom list walker to show and hide cell results as required
- custom wrap and align modes for editing right-1 aligned numbers
- outputs commands that may be used to recreate expression on exit
"""
from __future__ import annotations
import operator
import string
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Hashable
# use appropriate Screen class
if urwid.display.web.is_web_request():
Screen = urwid.display.web.Screen
else:
Screen = urwid.display.raw.Screen
def div_or_none(a, b):
"""Divide a by b. Return result or None on divide by zero."""
if b == 0:
return None
return a / b
# operators supported and the functions used to calculate a result
OPERATORS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": div_or_none,
}
# the uppercase versions of keys used to switch columns
COLUMN_KEYS = list("?ABCDEF")
# these lists are used to determine when to display errors
EDIT_KEYS = list(OPERATORS.keys()) + COLUMN_KEYS + ["backspace", "delete"]
MOVEMENT_KEYS = ["up", "down", "left", "right", "page up", "page down"]
# Event text
E_no_such_column = "Column %s does not exist."
E_no_more_columns = "Maxumum number of columns reached."
E_new_col_cell_not_empty = "Column must be started from an empty cell."
E_invalid_key = "Invalid key '%s'."
E_no_parent_column = "There is no parent column to return to."
E_cant_combine = "Cannot combine cells with sub-expressions."
E_invalid_in_parent_cell = "Cannot enter numbers into parent cell."
E_invalid_in_help_col = [
"Help Column is in focus. Press ",
("key", COLUMN_KEYS[1]),
"-",
("key", COLUMN_KEYS[-1]),
" to select another column.",
]
# Shared layout object
CALC_LAYOUT = None
class CalcEvent(Exception):
"""Events triggered by user input."""
attr = "event"
def __init__(self, message: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]) -> None:
self.message = message
def widget(self):
"""Return a widget containing event information"""
text = urwid.Text(self.message, urwid.CENTER)
return urwid.AttrMap(text, self.attr)
class ColumnDeleteEvent(CalcEvent):
"""Sent when user wants to delete a column"""
attr = "confirm"
def __init__(self, letter: str, from_parent=0) -> None:
super().__init__(["Press ", ("key", "BACKSPACE"), " again to confirm column removal."])
self.letter = letter
class UpdateParentEvent(Exception):
"""Sent when parent columns may need to be updated."""
class Cell:
def __init__(self, op) -> None:
self.op = op
self.is_top = op is None
self.child = None
self.setup_edit()
self.result = urwid.Text("", layout=CALC_LAYOUT)
def show_result(self, next_cell) -> bool:
"""Return whether this widget should display its result.
next_cell -- the cell following self or None"""
if self.is_top:
return False
if next_cell is None:
return True
return not (self.op == next_cell.op == "+")
def setup_edit(self) -> None:
"""Create the standard edit widget for this cell."""
self.edit = urwid.IntEdit()
if not self.is_top:
self.edit.set_caption(f"{self.op} ")
self.edit.set_layout(None, None, CALC_LAYOUT)
def get_value(self) -> int | None:
"""Return the numeric value of the cell."""
if self.child is not None:
return self.child.get_result()
return int(f"0{self.edit.edit_text}")
def get_result(self) -> int | None:
"""Return the numeric result of this cell's operation."""
if self.is_top:
return self.get_value()
if not self.result.text:
return None
return int(self.result.text)
def set_result(self, result: int | None):
"""Set the numeric result for this cell."""
if result is None:
self.result.set_text("")
else:
self.result.set_text(f"{result:d}")
def become_parent(self, column, letter: str) -> None:
"""Change the edit widget to a parent cell widget."""
self.child = column
self.edit = ParentEdit(self.op, letter)
def remove_child(self) -> None:
"""Change the edit widget back to a standard edit widget."""
self.child = None
self.setup_edit()
def is_empty(self) -> bool:
"""Return True if the cell is "empty"."""
return self.child is None and not self.result.text
class ParentEdit(urwid.Edit):
"""Edit widget modified to link to a child column"""
def __init__(self, op, letter: str) -> None:
"""Use the operator and letter of the child column as caption
op -- operator or None
letter -- letter of child column
remove_fn -- function to call when user wants to remove child
function takes no parameters
"""
super().__init__(layout=CALC_LAYOUT)
self.op = op
self.set_letter(letter)
def set_letter(self, letter: str) -> None:
"""Set the letter of the child column for display."""
self.letter = letter
caption = f"({letter})"
if self.op is not None:
caption = f"{self.op} {caption}"
self.set_caption(caption)
def keypress(self, size, key: str) -> str | None:
"""Disable usual editing, allow only removing of child"""
if key == "backspace":
raise ColumnDeleteEvent(self.letter, from_parent=True)
if key in string.digits:
raise CalcEvent(E_invalid_in_parent_cell)
return key
class CellWalker(urwid.ListWalker):
def __init__(self, content):
self.content = urwid.MonitoredList(content)
self.content.modified = self._modified
self.focus = (0, 0)
# everyone can share the same divider widget
self.div = urwid.Divider("-")
def get_cell(self, i):
if i < 0 or i >= len(self.content):
return None
return self.content[i]
def _get_at_pos(self, pos):
i, sub = pos
assert sub in {0, 1, 2} # noqa: S101 # for examples "assert" is acceptable
if i < 0 or i >= len(self.content):
return None, None
if sub == 0:
edit = self.content[i].edit
return urwid.AttrMap(edit, "edit", "editfocus"), pos
if sub == 1:
return self.div, pos
return self.content[i].result, pos
def get_focus(self):
return self._get_at_pos(self.focus)
def set_focus(self, focus) -> None:
self.focus = focus
def get_next(self, position):
i, sub = position
assert sub in {0, 1, 2} # noqa: S101 # for examples "assert" is acceptable
if sub == 0:
show_result = self.content[i].show_result(self.get_cell(i + 1))
if show_result:
return self._get_at_pos((i, 1))
return self._get_at_pos((i + 1, 0))
if sub == 1:
return self._get_at_pos((i, 2))
return self._get_at_pos((i + 1, 0))
def get_prev(self, position):
i, sub = position
assert sub in {0, 1, 2} # noqa: S101 # for examples "assert" is acceptable
if sub == 0:
if i == 0:
return None, None
show_result = self.content[i - 1].show_result(self.content[i])
if show_result:
return self._get_at_pos((i - 1, 2))
return self._get_at_pos((i - 1, 0))
if sub == 1:
return self._get_at_pos((i, 0))
return self._get_at_pos((i, 1))
class CellColumn(urwid.WidgetWrap):
def __init__(self, letter: str) -> None:
self.walker = CellWalker([Cell(None)])
self.content = self.walker.content
self.listbox = urwid.ListBox(self.walker)
self.set_letter(letter)
super().__init__(self.frame)
def set_letter(self, letter: str) -> None:
"""Set the column header with letter."""
self.letter = letter
header = urwid.AttrMap(urwid.Text(["Column ", ("key", letter)], layout=CALC_LAYOUT), "colhead")
self.frame = urwid.Frame(self.listbox, header)
def keypress(self, size, key: str) -> str | None:
key = self.frame.keypress(size, key)
if key is None:
changed = self.update_results()
if changed:
raise UpdateParentEvent()
return None
_f, (i, sub) = self.walker.get_focus()
if sub != 0:
# f is not an edit widget
return key
if key in OPERATORS:
# move trailing text to new cell below
edit = self.walker.get_cell(i).edit
cursor_pos = edit.edit_pos
tail = edit.edit_text[cursor_pos:]
edit.set_edit_text(edit.edit_text[:cursor_pos])
new_cell = Cell(key)
new_cell.edit.edit_text = tail
self.content[i + 1 : i + 1] = [new_cell]
changed = self.update_results()
self.move_focus_next(size)
self.content[i + 1].edit.set_edit_pos(0)
if changed:
raise UpdateParentEvent()
return None
if key == "backspace":
# unhandled backspace, we're at beginning of number
# append current number to cell above, removing operator
above = self.walker.get_cell(i - 1)
if above is None:
# we're the first cell
raise ColumnDeleteEvent(self.letter, from_parent=False)
edit = self.walker.get_cell(i).edit
# check that we can combine
if above.child is not None:
# cell above is parent
if edit.edit_text:
# ..and current not empty, no good
raise CalcEvent(E_cant_combine)
above_pos = 0
else:
# above is normal number cell
above_pos = len(above.edit.edit_text)
above.edit.set_edit_text(above.edit.edit_text + edit.edit_text)
self.move_focus_prev(size)
self.content[i - 1].edit.set_edit_pos(above_pos)
del self.content[i]
changed = self.update_results()
if changed:
raise UpdateParentEvent()
return None
if key == "delete":
# pull text from next cell into current
cell = self.walker.get_cell(i)
below = self.walker.get_cell(i + 1)
if cell.child is not None:
# this cell is a parent
raise CalcEvent(E_cant_combine)
if below is None:
# nothing below
return key
if below.child is not None:
# cell below is a parent
raise CalcEvent(E_cant_combine)
edit = self.walker.get_cell(i).edit
edit.set_edit_text(edit.edit_text + below.edit.edit_text)
del self.content[i + 1]
changed = self.update_results()
if changed:
raise UpdateParentEvent()
return None
return key
def move_focus_next(self, size) -> None:
_f, (i, _sub) = self.walker.get_focus()
assert i < len(self.content) - 1 # noqa: S101 # for examples "assert" is acceptable
ni = i
while ni == i:
self.frame.keypress(size, "down")
_nf, (ni, _nsub) = self.walker.get_focus()
def move_focus_prev(self, size) -> None:
_f, (i, _sub) = self.walker.get_focus()
assert i > 0 # noqa: S101 # for examples "assert" is acceptable
ni = i
while ni == i:
self.frame.keypress(size, "up")
_nf, (ni, _nsub) = self.walker.get_focus()
def update_results(self, start_from=None) -> bool:
"""Update column. Return True if final result changed.
start_from -- Cell to start updating from or None to start from
the current focus (default None)
"""
if start_from is None:
_f, (i, _sub) = self.walker.get_focus()
else:
i = self.content.index(start_from)
if i is None:
return False
focus_cell = self.walker.get_cell(i)
if focus_cell.is_top:
x = focus_cell.get_value()
else:
last_cell = self.walker.get_cell(i - 1)
x = last_cell.get_result()
if x is not None and focus_cell.op is not None:
x = OPERATORS[focus_cell.op](x, focus_cell.get_value())
focus_cell.set_result(x)
for cell in self.content[i + 1 :]:
if cell.op is None:
x = None
if x is not None:
x = OPERATORS[cell.op](x, cell.get_value())
if cell.get_result() == x:
return False
cell.set_result(x)
return True
def create_child(self, letter):
"""Return (parent cell,child column) or None,None on failure."""
_f, (i, sub) = self.walker.get_focus()
if sub != 0:
# f is not an edit widget
return None, None
cell = self.walker.get_cell(i)
if cell.child is not None:
raise CalcEvent(E_new_col_cell_not_empty)
if cell.edit.edit_text:
raise CalcEvent(E_new_col_cell_not_empty)
child = CellColumn(letter)
cell.become_parent(child, letter)
return cell, child
def is_empty(self) -> bool:
"""Return True if this column is empty."""
return len(self.content) == 1 and self.content[0].is_empty()
def get_expression(self) -> str:
"""Return the expression as a printable string."""
lines = []
for c in self.content:
if c.op is not None: # only applies to first cell
lines.append(c.op)
if c.child is not None:
lines.append(f"({c.child.get_expression()})")
else:
lines.append(f"{c.get_value():d}")
return "".join(lines)
def get_result(self):
"""Return the result of the last cell in the column."""
return self.content[-1].get_result()
class HelpColumn(urwid.Widget):
_selectable = True
_sizing = frozenset((urwid.BOX,))
help_text = [ # noqa: RUF012 # text layout typing is too complex
("title", "Column Calculator"),
"",
["Numbers: ", ("key", "0"), "-", ("key", "9")],
"",
["Operators: ", ("key", "+"), ", ", ("key", "-"), ", ", ("key", "*"), " and ", ("key", "/")],
"",
["Editing: ", ("key", "BACKSPACE"), " and ", ("key", "DELETE")],
"",
[
"Movement: ",
("key", "UP"),
", ",
("key", "DOWN"),
", ",
("key", "LEFT"),
", ",
("key", "RIGHT"),
", ",
("key", "PAGE UP"),
" and ",
("key", "PAGE DOWN"),
],
"",
["Sub-expressions: ", ("key", "("), " and ", ("key", ")")],
"",
["Columns: ", ("key", COLUMN_KEYS[0]), " and ", ("key", COLUMN_KEYS[1]), "-", ("key", COLUMN_KEYS[-1])],
"",
["Exit: ", ("key", "Q")],
"",
"",
[
"Column Calculator does operations in the order they are ",
"typed, not by following usual precedence rules. ",
"If you want to calculate ",
("key", "12 - 2 * 3"),
" with the multiplication happening before the ",
"subtraction you must type ",
("key", "12 - (2 * 3)"),
" instead.",
],
]
def __init__(self) -> None:
super().__init__()
self.head = urwid.AttrMap(urwid.Text(["Help Column ", ("key", "?")], layout=CALC_LAYOUT), "help")
self.foot = urwid.AttrMap(urwid.Text(["[text continues.. press ", ("key", "?"), " then scroll]"]), "helpnote")
self.items = [urwid.Text(x) for x in self.help_text]
self.listbox = urwid.ListBox(urwid.SimpleListWalker(self.items))
self.body = urwid.AttrMap(self.listbox, "help")
self.frame = urwid.Frame(self.body, header=self.head)
def render(self, size, focus: bool = False) -> urwid.Canvas:
maxcol, maxrow = size
head_rows = self.head.rows((maxcol,))
if "bottom" in self.listbox.ends_visible((maxcol, maxrow - head_rows)):
self.frame.footer = None
else:
self.frame.footer = self.foot
return self.frame.render((maxcol, maxrow), focus)
def keypress(self, size, key: str) -> str | None:
return self.frame.keypress(size, key)
class CalcDisplay:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "white", "dark blue"),
("edit", "yellow", "dark blue"),
("editfocus", "yellow", "dark cyan", "bold"),
("key", "dark cyan", "light gray", ("standout", "underline")),
("title", "white", "light gray", ("bold", "standout")),
("help", "black", "light gray", "standout"),
("helpnote", "dark green", "light gray"),
("colhead", "black", "light gray", "standout"),
("event", "light red", "black", "standout"),
("confirm", "yellow", "black", "bold"),
]
def __init__(self) -> None:
self.columns = urwid.Columns([HelpColumn(), CellColumn("A")], 1)
self.columns.focus_position = 1
view = urwid.AttrMap(self.columns, "body")
self.view = urwid.Frame(view) # for showing messages
self.col_link = {}
def main(self) -> None:
self.loop = urwid.MainLoop(self.view, self.palette, screen=Screen(), input_filter=self.input_filter)
self.loop.run()
# on exit write the formula and the result to the console
expression, result = self.get_expression_result()
print("Paste this expression into a new Column Calculator session to continue editing:")
print(expression)
print("Result:", result)
def input_filter(self, data, raw_input):
if "q" in data or "Q" in data:
raise urwid.ExitMainLoop()
# handle other keystrokes
for k in data:
try:
self.wrap_keypress(k)
self.event = None
self.view.footer = None
except CalcEvent as e: # noqa: PERF203
# display any message
self.event = e
self.view.footer = e.widget()
# remove all input from further processing by MainLoop
return []
def wrap_keypress(self, key: str) -> None:
"""Handle confirmation and throw event on bad input."""
try:
key = self.keypress(key)
except ColumnDeleteEvent as e:
if e.letter == COLUMN_KEYS[1]:
# cannot delete the first column, ignore key
return
if not self.column_empty(e.letter) and not isinstance(self.event, ColumnDeleteEvent):
# need to get two in a row, so check last event ask for confirmation
raise
self.delete_column(e.letter)
except UpdateParentEvent:
self.update_parent_columns()
return
if key is None:
return
if self.columns.focus_position == 0 and key not in {"up", "down", "page up", "page down"}:
raise CalcEvent(E_invalid_in_help_col)
if key not in EDIT_KEYS and key not in MOVEMENT_KEYS:
raise CalcEvent(E_invalid_key % key.upper())
def keypress(self, key: str) -> str | None:
"""Handle a keystroke."""
self.loop.process_input([key])
if isinstance(key, tuple):
# ignore mouse events
return None
if key.upper() in COLUMN_KEYS:
# column switch
i = COLUMN_KEYS.index(key.upper())
if i >= len(self.columns):
raise CalcEvent(E_no_such_column % key.upper())
self.columns.focus_position = i
return None
if key == "(":
# open a new column
if len(self.columns) >= len(COLUMN_KEYS):
raise CalcEvent(E_no_more_columns)
i = self.columns.focus_position
if i == 0:
# makes no sense in help column
return key
col = self.columns.contents[i][0]
new_letter = COLUMN_KEYS[len(self.columns)]
parent, child = col.create_child(new_letter)
if child is None:
# something invalid in focus
return key
self.columns.contents.append((child, (urwid.WEIGHT, 1, False)))
self.set_link(parent, col, child)
self.columns.focus_position = len(self.columns) - 1
return None
if key == ")":
i = self.columns.focus_position
if i == 0:
# makes no sense in help column
return key
col = self.columns.contents[i][0]
parent, pcol = self.get_parent(col)
if parent is None:
# column has no parent
raise CalcEvent(E_no_parent_column)
new_i = next(iter(idx for idx, (w, _) in enumerate(self.columns.contents) if w == pcol))
self.columns.focus_position = new_i
return None
return key
def set_link(self, parent, pcol, child):
"""Store the link between a parent cell and child column.
parent -- parent Cell object
pcol -- CellColumn where parent resides
child -- child CellColumn object"""
self.col_link[child] = parent, pcol
def get_parent(self, child):
"""Return the parent and parent column for a given column."""
return self.col_link.get(child, (None, None))
def column_empty(self, letter) -> bool:
"""Return True if the column passed is empty."""
return self.columns.contents[COLUMN_KEYS.index(letter)][0].is_empty()
def delete_column(self, letter) -> None:
"""Delete the column with the given letter."""
i = COLUMN_KEYS.index(letter)
col = self.columns.contents[i][0]
parent, pcol = self.get_parent(col)
f = self.columns.focus_position
if f == i:
# move focus to the parent column
f = next(iter(idx for idx, (w, _) in enumerate(self.columns.contents) if w == pcol))
self.columns.focus_position = f
parent.remove_child()
pcol.update_results(parent)
del self.columns.contents[i]
# delete children of this column
keep_right_cols = []
remove_cols = [col]
for rcol, _ in self.columns.contents[i:]:
parent, pcol = self.get_parent(rcol)
if pcol in remove_cols:
remove_cols.append(rcol)
else:
keep_right_cols.append(rcol)
for rc in remove_cols:
# remove the links
del self.col_link[rc]
# keep only the non-children
self.columns.contents[i:] = [(w, (urwid.WEIGHT, 1, False)) for w in keep_right_cols]
# fix the letter assignments
for j in range(i, len(self.columns)):
col = self.columns.contents[j][0]
# fix the column heading
col.set_letter(COLUMN_KEYS[j])
parent, pcol = self.get_parent(col)
# fix the parent cell
parent.edit.set_letter(COLUMN_KEYS[j])
def update_parent_columns(self) -> None:
"""Update the parent columns of the current focus column."""
f = self.columns.focus_position
col = self.columns.contents[f][0]
while 1:
parent, pcol = self.get_parent(col)
if pcol is None:
return
changed = pcol.update_results(start_from=parent)
if not changed:
return
col = pcol
def get_expression_result(self):
"""Return (expression, result) as strings."""
col = self.columns.contents[1][0]
return col.get_expression(), f"{col.get_result():d}"
class CalcNumLayout(urwid.TextLayout):
"""
TextLayout class for bottom-right aligned numbers with a space on
the last line for the cursor.
"""
def layout(self, text, width: int, align, wrap):
"""
Return layout structure for calculator number display.
"""
lt = len(text) + 1 # extra space for cursor
remaining = lt % width # remaining segment not full width wide
linestarts = range(remaining, lt, width)
layout = []
if linestarts:
if remaining:
# right-align the remaining segment on 1st line
layout.append([(width - remaining, None), (remaining, 0, remaining)])
# fill all but the last line
for x in linestarts[:-1]:
layout.append([(width, x, x + width)]) # noqa: PERF401
s = linestarts[-1]
# add the last line with a cursor hint
layout.append([(width - 1, s, lt - 1), (0, lt - 1)])
elif lt - 1:
# all fits on one line, so right align the text
# with a cursor hint at the end
layout.append([(width - lt, None), (lt - 1, 0, lt - 1), (0, lt - 1)])
else:
# nothing on the line, right align a cursor hint
layout.append([(width - 1, None), (0, 0)])
return layout
def main() -> None:
"""Launch Column Calculator."""
global CALC_LAYOUT # noqa: PLW0603 # pylint: disable=global-statement
CALC_LAYOUT = CalcNumLayout()
urwid.display.web.set_preferences("Column Calculator")
# try to handle short web requests quickly
if urwid.display.web.handle_short_request():
return
CalcDisplay().main()
if __name__ == "__main__" or urwid.display.web.is_web_request():
main()
| 27,315 | Python | .py | 654 | 32.035168 | 118 | 0.571979 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,142 | bigtext.py | urwid_urwid/examples/bigtext.py | #!/usr/bin/env python
#
# Urwid BigText example program
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example demonstrating use of the BigText widget.
"""
from __future__ import annotations
import typing
import urwid
import urwid.display.raw
if typing.TYPE_CHECKING:
from collections.abc import Callable
_Wrapped = typing.TypeVar("_Wrapped")
class SwitchingPadding(urwid.Padding[_Wrapped]):
def padding_values(self, size, focus: bool) -> tuple[int, int]:
maxcol = size[0]
width, _height = self.original_widget.pack(size, focus=focus)
if maxcol > width:
self.align = urwid.LEFT
else:
self.align = urwid.RIGHT
return super().padding_values(size, focus)
class BigTextDisplay:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "black", "light gray", "standout"),
("header", "white", "dark red", "bold"),
("button normal", "light gray", "dark blue", "standout"),
("button select", "white", "dark green"),
("button disabled", "dark gray", "dark blue"),
("edit", "light gray", "dark blue"),
("bigtext", "white", "black"),
("chars", "light gray", "black"),
("exit", "white", "dark cyan"),
]
def create_radio_button(
self,
g: list[urwid.RadioButton],
name: str,
font: urwid.Font,
fn: Callable[[urwid.RadioButton, bool], typing.Any],
) -> urwid.AttrMap:
w = urwid.RadioButton(g, name, False, on_state_change=fn)
w.font = font
w = urwid.AttrMap(w, "button normal", "button select")
return w
def create_disabled_radio_button(self, name: str) -> urwid.AttrMap:
w = urwid.Text(f" {name} (UTF-8 mode required)")
w = urwid.AttrMap(w, "button disabled")
return w
def create_edit(
self,
label: str,
text: str,
fn: Callable[[urwid.Edit, str], typing.Any],
) -> urwid.AttrMap:
w = urwid.Edit(label, text)
urwid.connect_signal(w, "change", fn)
fn(w, text)
w = urwid.AttrMap(w, "edit")
return w
def set_font_event(self, w, state: bool) -> None:
if state:
self.bigtext.set_font(w.font)
self.chars_avail.set_text(w.font.characters())
def edit_change_event(self, widget, text: str) -> None:
self.bigtext.set_text(text)
def setup_view(self) -> tuple[
urwid.Frame[urwid.AttrMap[urwid.ListBox], urwid.AttrMap[urwid.Text], None],
urwid.Overlay[urwid.BigText, urwid.Frame[urwid.AttrMap[urwid.ListBox], urwid.AttrMap[urwid.Text], None]],
]:
fonts = urwid.get_all_fonts()
# setup mode radio buttons
self.font_buttons = []
group = []
utf8 = urwid.get_encoding_mode() == "utf8"
for name, fontcls in fonts:
font = fontcls()
if font.utf8_required and not utf8:
rb = self.create_disabled_radio_button(name)
else:
rb = self.create_radio_button(group, name, font, self.set_font_event)
if fontcls == urwid.Thin6x6Font:
chosen_font_rb = rb
exit_font = font
self.font_buttons.append(rb)
# Create BigText
self.bigtext = urwid.BigText("", None)
bt = urwid.BoxAdapter(
urwid.Filler(
urwid.AttrMap(
SwitchingPadding(self.bigtext, urwid.LEFT, None),
"bigtext",
),
urwid.BOTTOM,
None,
7,
),
7,
)
# Create chars_avail
cah = urwid.Text("Characters Available:")
self.chars_avail = urwid.Text("", wrap=urwid.ANY)
ca = urwid.AttrMap(self.chars_avail, "chars")
chosen_font_rb.original_widget.set_state(True) # causes set_font_event call
# Create Edit widget
edit = self.create_edit("", "Urwid BigText example", self.edit_change_event)
# ListBox
chars = urwid.Pile([cah, ca])
fonts = urwid.Pile([urwid.Text("Fonts:"), *self.font_buttons], focus_item=1)
col = urwid.Columns([(16, chars), fonts], 3, focus_column=1)
bt = urwid.Pile([bt, edit], focus_item=1)
lines = [bt, urwid.Divider(), col]
listbox = urwid.ListBox(urwid.SimpleListWalker(lines))
# Frame
w = urwid.Frame(
body=urwid.AttrMap(listbox, "body"),
header=urwid.AttrMap(urwid.Text("Urwid BigText example program - F8 exits."), "header"),
)
# Exit message
exit_w = urwid.Overlay(
urwid.BigText(("exit", " Quit? "), exit_font),
w,
urwid.CENTER,
None,
urwid.MIDDLE,
None,
)
return w, exit_w
def main(self):
self.view, self.exit_view = self.setup_view()
self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input)
self.loop.run()
def unhandled_input(self, key: str | tuple[str, int, int, int]) -> bool | None:
if key == "f8":
self.loop.widget = self.exit_view
return True
if self.loop.widget != self.exit_view:
return None
if key in {"y", "Y"}:
raise urwid.ExitMainLoop()
if key in {"n", "N"}:
self.loop.widget = self.view
return True
return None
def main():
BigTextDisplay().main()
if __name__ == "__main__":
main()
| 6,402 | Python | .py | 165 | 30.345455 | 113 | 0.589496 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,143 | tour.py | urwid_urwid/examples/tour.py | #!/usr/bin/env python
#
# Urwid tour. It slices, it dices..
# Copyright (C) 2004-2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid tour. Shows many of the standard widget types and features.
"""
from __future__ import annotations
import urwid
def main():
text_header = "Welcome to the urwid tour! UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 exits."
text_intro = [
("important", "Text"),
" widgets are the most common in "
"any urwid program. This Text widget was created "
"without setting the wrap or align mode, so it "
"defaults to left alignment with wrapping on space "
"characters. ",
("important", "Change the window width"),
" to see how the widgets on this page react. This Text widget is wrapped with a ",
("important", "Padding"),
" widget to keep it indented on the left and right.",
]
text_right = "This Text widget is right aligned. Wrapped words stay to the right as well. "
text_center = "This one is center aligned."
text_clip = (
"Text widgets may be clipped instead of wrapped.\n"
"Extra text is discarded instead of wrapped to the next line. "
"65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n"
"Newlines embedded in the string are still respected."
)
text_right_clip = (
"This is a right aligned and clipped Text widget.\n"
"<100 <-95 <-90 <-85 <-80 <-75 <-70 <-65 "
"Text will be cut off at the left of this widget."
)
text_center_clip = "Center aligned and clipped widgets will have text cut off both sides."
text_ellipsis = (
"Text can be clipped using the ellipsis character (…)\n"
"Extra text is discarded and a … mark is shown."
"50-> 55-> 60-> 65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n"
)
text_any = (
"The 'any' wrap mode will wrap on any character. This "
"mode will not collapse space characters at the end of the "
"line but it still honors embedded newline characters.\n"
"Like this one."
)
text_padding = (
"Padding widgets have many options. This "
"is a standard Text widget wrapped with a Padding widget "
"with the alignment set to relative 20% and with its width "
"fixed at 40."
)
text_divider = [
"The ",
("important", "Divider"),
" widget repeats the same character across the whole line. It can also add blank lines above and below.",
]
text_edit = [
"The ",
("important", "Edit"),
" widget is a simple text editing widget. It supports cursor "
"movement and tries to maintain the current column when focus "
"moves to another edit widget. It wraps and aligns the same "
"way as Text widgets.",
]
text_edit_cap1 = ("editcp", "This is a caption. Edit here: ")
text_edit_text1 = "editable stuff"
text_edit_cap2 = ("editcp", "This one supports newlines: ")
text_edit_text2 = (
"line one starts them all\n"
"== line 2 == with some more text to edit.. words.. whee..\n"
"LINE III, the line to end lines one and two, unless you "
"change something."
)
text_edit_cap3 = ("editcp", "This one is clipped, try editing past the edge: ")
text_edit_text3 = "add some text here -> -> -> ...."
text_edit_alignments = "Different Alignments:"
text_edit_left = "left aligned (default)"
text_edit_center = "center aligned"
text_edit_right = "right aligned"
text_intedit = ("editcp", [("important", "IntEdit"), " allows only numbers: "])
text_edit_padding = ("editcp", "Edit widget within a Padding widget ")
text_columns1 = [
("important", "Columns"),
" are used to share horizontal screen space. "
"This one splits the space into two parts with "
"three characters between each column. The "
"contents of each column is a single widget.",
]
text_columns2 = [
"When you need to put more than one widget into a column you can use a ",
("important", "Pile"),
" to combine two or more widgets.",
]
text_col_columns = "Columns may be placed inside other columns."
text_col_21 = "Col 2.1"
text_col_22 = "Col 2.2"
text_col_23 = "Col 2.3"
text_column_widths = (
"Columns may also have uneven relative "
"weights or fixed widths. Use a minimum width so that "
"columns don't become too small."
)
text_weight = "Weight %d"
text_fixed_9 = "<Fixed 9>" # should be 9 columns wide
text_fixed_14 = "<--Fixed 14-->" # should be 14 columns wide
text_edit_col_cap1 = ("editcp", "Edit widget within Columns")
text_edit_col_text1 = "here's\nsome\ninfo"
text_edit_col_cap2 = ("editcp", "and within Pile ")
text_edit_col_text2 = "more"
text_edit_col_cap3 = ("editcp", "another ")
text_edit_col_text3 = "still more"
text_gridflow = [
"A ",
("important", "GridFlow"),
" widget "
"may be used to display a list of flow widgets with equal "
"widths. Widgets that don't fit on the first line will "
"flow to the next. This is useful for small widgets that "
"you want to keep together such as ",
("important", "Button"),
", ",
("important", "CheckBox"),
" and ",
("important", "RadioButton"),
" widgets.",
]
text_button_list = ["Yes", "No", "Perhaps", "Certainly", "Partially", "Tuesdays Only", "Help"]
text_cb_list = ["Wax", "Wash", "Buff", "Clear Coat", "Dry", "Racing Stripe"]
text_rb_list = ["Morning", "Afternoon", "Evening", "Weekend"]
text_listbox = [
"All these widgets have been displayed with the help of a ",
("important", "ListBox"),
" widget. ListBox widgets handle scrolling and changing focus. A ",
("important", "Frame"),
" widget is used to keep the instructions at the top of the screen.",
]
def button_press(button):
frame.footer = urwid.AttrMap(urwid.Text(["Pressed: ", button.get_label()]), "header")
radio_button_group = []
blank = urwid.Divider()
listbox_content = [
blank,
urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20),
blank,
urwid.Text(text_right, align=urwid.RIGHT),
blank,
urwid.Text(text_center, align=urwid.CENTER),
blank,
urwid.Text(text_clip, wrap=urwid.CLIP),
blank,
urwid.Text(text_right_clip, align=urwid.RIGHT, wrap=urwid.CLIP),
blank,
urwid.Text(text_center_clip, align=urwid.CENTER, wrap=urwid.CLIP),
blank,
urwid.Text(text_ellipsis, wrap=urwid.ELLIPSIS),
blank,
urwid.Text(text_any, wrap=urwid.ANY),
blank,
urwid.Padding(urwid.Text(text_padding), (urwid.RELATIVE, 20), 40),
blank,
urwid.AttrMap(urwid.Divider("=", 1), "bright"),
urwid.Padding(urwid.Text(text_divider), left=2, right=2, min_width=20),
urwid.AttrMap(urwid.Divider("-", 0, 1), "bright"),
blank,
urwid.Padding(urwid.Text(text_edit), left=2, right=2, min_width=20),
blank,
urwid.AttrMap(urwid.Edit(text_edit_cap1, text_edit_text1), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.Edit(text_edit_cap2, text_edit_text2, multiline=True), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.Edit(text_edit_cap3, text_edit_text3, wrap=urwid.CLIP), "editbx", "editfc"),
blank,
urwid.Text(text_edit_alignments),
urwid.AttrMap(urwid.Edit("", text_edit_left, align=urwid.LEFT), "editbx", "editfc"),
urwid.AttrMap(urwid.Edit("", text_edit_center, align=urwid.CENTER), "editbx", "editfc"),
urwid.AttrMap(urwid.Edit("", text_edit_right, align=urwid.RIGHT), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.IntEdit(text_intedit, 123), "editbx", "editfc"),
blank,
urwid.Padding(urwid.AttrMap(urwid.Edit(text_edit_padding, ""), "editbx", "editfc"), left=10, width=50),
blank,
blank,
urwid.AttrMap(
urwid.Columns(
[
urwid.Divider("."),
urwid.Divider(","),
urwid.Divider("."),
]
),
"bright",
),
blank,
urwid.Columns(
[
urwid.Padding(urwid.Text(text_columns1), left=2, right=0, min_width=20),
urwid.Pile([urwid.Divider("~"), urwid.Text(text_columns2), urwid.Divider("_")]),
],
3,
),
blank,
blank,
urwid.Columns(
[
urwid.Text(text_col_columns),
urwid.Columns(
[
urwid.Text(text_col_21),
urwid.Text(text_col_22),
urwid.Text(text_col_23),
],
1,
),
],
2,
),
blank,
urwid.Padding(urwid.Text(text_column_widths), left=2, right=2, min_width=20),
blank,
urwid.Columns(
[
urwid.AttrMap(urwid.Text(text_weight % 1), "reverse"),
(urwid.WEIGHT, 2, urwid.Text(text_weight % 2)),
(urwid.WEIGHT, 3, urwid.AttrMap(urwid.Text(text_weight % 3), "reverse")),
(urwid.WEIGHT, 4, urwid.Text(text_weight % 4)),
(urwid.WEIGHT, 5, urwid.AttrMap(urwid.Text(text_weight % 5), "reverse")),
(urwid.WEIGHT, 6, urwid.Text(text_weight % 6)),
],
0,
min_width=8,
),
blank,
urwid.Columns(
[
(urwid.WEIGHT, 2, urwid.AttrMap(urwid.Text(text_weight % 2), "reverse")),
(9, urwid.Text(text_fixed_9)),
(urwid.WEIGHT, 3, urwid.AttrMap(urwid.Text(text_weight % 3), "reverse")),
(14, urwid.Text(text_fixed_14)),
],
0,
min_width=8,
),
blank,
urwid.Columns(
[
urwid.AttrMap(urwid.Edit(text_edit_col_cap1, text_edit_col_text1, multiline=True), "editbx", "editfc"),
urwid.Pile(
[
urwid.AttrMap(urwid.Edit(text_edit_col_cap2, text_edit_col_text2), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.Edit(text_edit_col_cap3, text_edit_col_text3), "editbx", "editfc"),
]
),
],
1,
),
blank,
urwid.AttrMap(
urwid.Columns(
[
urwid.Divider("'"),
urwid.Divider('"'),
urwid.Divider("~"),
urwid.Divider('"'),
urwid.Divider("'"),
]
),
"bright",
),
blank,
blank,
urwid.Padding(urwid.Text(text_gridflow), left=2, right=2, min_width=20),
blank,
urwid.Padding(
urwid.GridFlow(
[urwid.AttrMap(urwid.Button(txt, button_press), "buttn", "buttnf") for txt in text_button_list],
13,
3,
1,
urwid.LEFT,
),
left=4,
right=3,
min_width=13,
),
blank,
urwid.Padding(
urwid.GridFlow(
[urwid.AttrMap(urwid.CheckBox(txt), "buttn", "buttnf") for txt in text_cb_list],
10,
3,
1,
urwid.LEFT,
),
left=4,
right=3,
min_width=10,
),
blank,
urwid.Padding(
urwid.GridFlow(
[urwid.AttrMap(urwid.RadioButton(radio_button_group, txt), "buttn", "buttnf") for txt in text_rb_list],
13,
3,
1,
urwid.LEFT,
),
left=4,
right=3,
min_width=13,
),
blank,
blank,
urwid.Padding(urwid.Text(text_listbox), left=2, right=2, min_width=20),
blank,
blank,
]
header = urwid.AttrMap(urwid.Text(text_header), "header")
listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content))
scrollable = urwid.ScrollBar(
listbox,
trough_char=urwid.ScrollBar.Symbols.LITE_SHADE,
)
frame = urwid.Frame(urwid.AttrMap(scrollable, "body"), header=header)
palette = [
("body", "black", "light gray", "standout"),
("reverse", "light gray", "black"),
("header", "white", "dark red", "bold"),
("important", "dark blue", "light gray", ("standout", "underline")),
("editfc", "white", "dark blue", "bold"),
("editbx", "light gray", "dark blue"),
("editcp", "black", "light gray", "standout"),
("bright", "dark gray", "light gray", ("bold", "standout")),
("buttn", "black", "dark cyan"),
("buttnf", "white", "dark blue", "bold"),
]
# use appropriate Screen class
if urwid.display.web.is_web_request():
screen = urwid.display.web.Screen()
else:
screen = urwid.display.raw.Screen()
def unhandled(key: str | tuple[str, int, int, int]) -> None:
if key == "f8":
raise urwid.ExitMainLoop()
urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled).run()
def setup():
urwid.display.web.set_preferences("Urwid Tour")
# try to handle short web requests quickly
if urwid.display.web.handle_short_request():
return
main()
if __name__ == "__main__" or urwid.display.web.is_web_request():
setup()
| 14,714 | Python | .py | 372 | 30.075269 | 119 | 0.559078 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,144 | input_test.py | urwid_urwid/examples/input_test.py | #!/usr/bin/env python
#
# Urwid keyboard input test app
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Keyboard test application
"""
from __future__ import annotations
import argparse
import logging
import urwid
if urwid.display.web.is_web_request():
Screen = urwid.display.web.Screen
loop_cls = urwid.SelectEventLoop
else:
event_loops: dict[str, type[urwid.EventLoop] | None] = {
"none": None,
"select": urwid.SelectEventLoop,
"asyncio": urwid.AsyncioEventLoop,
}
if hasattr(urwid, "TornadoEventLoop"):
event_loops["tornado"] = urwid.TornadoEventLoop
if hasattr(urwid, "GLibEventLoop"):
event_loops["glib"] = urwid.GLibEventLoop
if hasattr(urwid, "TwistedEventLoop"):
event_loops["twisted"] = urwid.TwistedEventLoop
if hasattr(urwid, "TrioEventLoop"):
event_loops["trio"] = urwid.TrioEventLoop
if hasattr(urwid, "ZMQEventLoop"):
event_loops["zmq"] = urwid.ZMQEventLoop
parser = argparse.ArgumentParser(description="Input test")
parser.add_argument(
"argc",
help="Positional arguments ('r' for raw display)",
metavar="<arguments>",
nargs="*",
default=(),
)
group = parser.add_argument_group("Advanced Options")
group.add_argument(
"--event-loop",
choices=event_loops,
default="none",
help="Event loop to use ('none' = use the default)",
)
group.add_argument("--debug-log", action="store_true", help="Enable debug logging")
args = parser.parse_args()
if not hasattr(urwid.display, "curses") or "r" in args.argc:
Screen = urwid.display.raw.Screen
else:
Screen = urwid.display.curses.Screen
loop_cls = event_loops[args.event_loop]
if args.debug_log:
logging.basicConfig(
level=logging.DEBUG,
filename="debug.log",
format=(
"%(levelname)1.1s %(asctime)s | %(threadName)s | %(name)s \n"
"\t%(message)s\n"
"-------------------------------------------------------------------------------"
),
datefmt="%d-%b-%Y %H:%M:%S",
force=True,
)
logging.captureWarnings(True)
def key_test():
screen = Screen()
header = urwid.AttrMap(
urwid.Text("Values from get_input(). Q exits."),
"header",
)
lw = urwid.SimpleListWalker([])
listbox = urwid.AttrMap(
urwid.ListBox(lw),
"listbox",
)
top = urwid.Frame(listbox, header)
def input_filter(keys, raw):
if "q" in keys or "Q" in keys:
raise urwid.ExitMainLoop
t = []
for k in keys:
if isinstance(k, tuple):
out = []
for v in k:
if out:
out += [", "]
out += [("key", repr(v))]
t += ["(", *out, ")"]
else:
t += ["'", ("key", k), "' "]
rawt = urwid.Text(", ".join(f"{r:d}" for r in raw))
if t:
lw.append(urwid.Columns([(urwid.WEIGHT, 2, urwid.Text(t)), rawt]))
listbox.original_widget.set_focus(len(lw) - 1, "above")
return keys
loop = urwid.MainLoop(
top,
[
("header", "black", "dark cyan", "standout"),
("key", "yellow", "dark blue", "bold"),
("listbox", "light gray", "black"),
],
screen,
input_filter=input_filter,
event_loop=loop_cls() if loop_cls is not None else None,
)
old = ()
try:
old = screen.tty_signal_keys("undefined", "undefined", "undefined", "undefined", "undefined")
loop.run()
finally:
if old:
screen.tty_signal_keys(*old)
def main():
urwid.display.web.set_preferences("Input Test")
if urwid.display.web.handle_short_request():
return
key_test()
if __name__ == "__main__" or urwid.display.web.is_web_request():
main()
| 4,821 | Python | .py | 137 | 27.861314 | 101 | 0.582278 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,145 | graph.py | urwid_urwid/examples/graph.py | #!/usr/bin/env python
#
# Urwid graphics example program
# Copyright (C) 2004-2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example demonstrating use of the BarGraph widget and creating a
floating-window appearance. Also shows use of alarms to create timed
animation.
"""
from __future__ import annotations
import math
import time
import typing
import urwid
UPDATE_INTERVAL = 0.2
def sin100(x):
"""
A sin function that returns values between 0 and 100 and repeats
after x == 100.
"""
return 50 + 50 * math.sin(x * math.pi / 50)
class GraphModel:
"""
A class responsible for storing the data that will be displayed
on the graph, and keeping track of which mode is enabled.
"""
data_max_value = 100
def __init__(self):
data = [
("Saw", list(range(0, 100, 2)) * 2),
("Square", [0] * 30 + [100] * 30),
("Sine 1", [sin100(x) for x in range(100)]),
("Sine 2", [(sin100(x) + sin100(x * 2)) / 2 for x in range(100)]),
("Sine 3", [(sin100(x) + sin100(x * 3)) / 2 for x in range(100)]),
]
self.modes = []
self.data = {}
for m, d in data:
self.modes.append(m)
self.data[m] = d
def get_modes(self):
return self.modes
def set_mode(self, m) -> None:
self.current_mode = m
def get_data(self, offset, r):
"""
Return the data in [offset:offset+r], the maximum value
for items returned, and the offset at which the data
repeats.
"""
lines = []
d = self.data[self.current_mode]
while r:
offset %= len(d)
segment = d[offset : offset + r]
r -= len(segment)
offset += len(segment)
lines += segment
return lines, self.data_max_value, len(d)
class GraphView(urwid.WidgetWrap):
"""
A class responsible for providing the application's interface and
graph display.
"""
palette: typing.ClassVar[tuple[str, str, str, ...]] = [
("body", "black", "light gray", "standout"),
("header", "white", "dark red", "bold"),
("screen edge", "light blue", "dark cyan"),
("main shadow", "dark gray", "black"),
("line", "black", "light gray", "standout"),
("bg background", "light gray", "black"),
("bg 1", "black", "dark blue", "standout"),
("bg 1 smooth", "dark blue", "black"),
("bg 2", "black", "dark cyan", "standout"),
("bg 2 smooth", "dark cyan", "black"),
("button normal", "light gray", "dark blue", "standout"),
("button select", "white", "dark green"),
("line", "black", "light gray", "standout"),
("pg normal", "white", "black", "standout"),
("pg complete", "white", "dark magenta"),
("pg smooth", "dark magenta", "black"),
]
graph_samples_per_bar = 10
graph_num_bars = 5
graph_offset_per_second = 5
def __init__(self, controller):
self.controller = controller
self.started = True
self.start_time = None
self.offset = 0
self.last_offset = None
super().__init__(self.main_window())
def get_offset_now(self):
if self.start_time is None:
return 0
if not self.started:
return self.offset
tdelta = time.time() - self.start_time
return int(self.offset + (tdelta * self.graph_offset_per_second))
def update_graph(self, force_update=False):
o = self.get_offset_now()
if o == self.last_offset and not force_update:
return False
self.last_offset = o
gspb = self.graph_samples_per_bar
r = gspb * self.graph_num_bars
d, max_value, repeat = self.controller.get_data(o, r)
lines = []
for n in range(self.graph_num_bars):
value = sum(d[n * gspb : (n + 1) * gspb]) / gspb
# toggle between two bar types
if n & 1:
lines.append([0, value])
else:
lines.append([value, 0])
self.graph.set_data(lines, max_value)
# also update progress
if (o // repeat) & 1:
# show 100% for first half, 0 for second half
if o % repeat > repeat // 2:
prog = 0
else:
prog = 1
else:
prog = float(o % repeat) / repeat
self.animate_progress.current = prog
return True
def on_animate_button(self, button):
"""Toggle started state and button text."""
if self.started: # stop animation
button.base_widget.set_label("Start")
self.offset = self.get_offset_now()
self.started = False
self.controller.stop_animation()
else:
button.base_widget.set_label("Stop")
self.started = True
self.start_time = time.time()
self.controller.animate_graph()
def on_reset_button(self, w):
self.offset = 0
self.start_time = time.time()
self.update_graph(True)
def on_mode_button(self, button, state):
"""Notify the controller of a new mode setting."""
if state:
# The new mode is the label of the button
self.controller.set_mode(button.get_label())
self.last_offset = None
def on_mode_change(self, m):
"""Handle external mode change by updating radio buttons."""
for rb in self.mode_buttons:
if rb.base_widget.label == m:
rb.base_widget.set_state(True, do_callback=False)
break
self.last_offset = None
def on_unicode_checkbox(self, w, state):
self.graph = self.bar_graph(state)
self.graph_wrap._w = self.graph
self.animate_progress = self.progress_bar(state)
self.animate_progress_wrap._w = self.animate_progress
self.update_graph(True)
def main_shadow(self, w):
"""Wrap a shadow and background around widget w."""
bg = urwid.AttrMap(urwid.SolidFill("▒"), "screen edge")
shadow = urwid.AttrMap(urwid.SolidFill(" "), "main shadow")
bg = urwid.Overlay(
shadow,
bg,
align=urwid.LEFT,
width=urwid.RELATIVE_100,
valign=urwid.TOP,
height=urwid.RELATIVE_100,
left=3,
right=1,
top=2,
bottom=1,
)
w = urwid.Overlay(
w,
bg,
align=urwid.LEFT,
width=urwid.RELATIVE_100,
valign=urwid.TOP,
height=urwid.RELATIVE_100,
left=2,
right=3,
top=1,
bottom=2,
)
return w
def bar_graph(self, smooth=False):
satt = None
if smooth:
satt = {(1, 0): "bg 1 smooth", (2, 0): "bg 2 smooth"}
w = urwid.BarGraph(["bg background", "bg 1", "bg 2"], satt=satt)
return w
def button(self, t, fn):
w = urwid.Button(t, fn)
w = urwid.AttrMap(w, "button normal", "button select")
return w
def radio_button(self, g, label, fn):
w = urwid.RadioButton(g, label, False, on_state_change=fn)
w = urwid.AttrMap(w, "button normal", "button select")
return w
def progress_bar(self, smooth=False):
if smooth:
return urwid.ProgressBar("pg normal", "pg complete", 0, 1, "pg smooth")
return urwid.ProgressBar("pg normal", "pg complete", 0, 1)
def exit_program(self, w):
raise urwid.ExitMainLoop()
def graph_controls(self):
modes = self.controller.get_modes()
# setup mode radio buttons
self.mode_buttons = []
group = []
for m in modes:
rb = self.radio_button(group, m, self.on_mode_button)
self.mode_buttons.append(rb)
# setup animate button
self.animate_button = self.button("", self.on_animate_button)
self.on_animate_button(self.animate_button)
self.offset = 0
self.animate_progress = self.progress_bar()
animate_controls = urwid.GridFlow(
[
self.animate_button,
self.button("Reset", self.on_reset_button),
],
9,
2,
0,
urwid.CENTER,
)
if urwid.get_encoding_mode() == "utf8":
unicode_checkbox = urwid.CheckBox("Enable Unicode Graphics", on_state_change=self.on_unicode_checkbox)
else:
unicode_checkbox = urwid.Text("UTF-8 encoding not detected")
self.animate_progress_wrap = urwid.WidgetWrap(self.animate_progress)
lines = [
urwid.Text("Mode", align=urwid.CENTER),
*self.mode_buttons,
urwid.Divider(),
urwid.Text("Animation", align=urwid.CENTER),
animate_controls,
self.animate_progress_wrap,
urwid.Divider(),
urwid.LineBox(unicode_checkbox),
urwid.Divider(),
self.button("Quit", self.exit_program),
]
w = urwid.ListBox(urwid.SimpleListWalker(lines))
return w
def main_window(self):
self.graph = self.bar_graph()
self.graph_wrap = urwid.WidgetWrap(self.graph)
vline = urwid.AttrMap(urwid.SolidFill("│"), "line")
c = self.graph_controls()
w = urwid.Columns([(urwid.WEIGHT, 2, self.graph_wrap), (1, vline), c], dividechars=1, focus_column=2)
w = urwid.Padding(w, urwid.LEFT, left=1)
w = urwid.AttrMap(w, "body")
w = urwid.LineBox(w)
w = urwid.AttrMap(w, "line")
w = self.main_shadow(w)
return w
class GraphController:
"""
A class responsible for setting up the model and view and running
the application.
"""
def __init__(self):
self.animate_alarm = None
self.model = GraphModel()
self.view = GraphView(self)
# use the first mode as the default
mode = self.get_modes()[0]
self.model.set_mode(mode)
# update the view
self.view.on_mode_change(mode)
self.view.update_graph(True)
def get_modes(self):
"""Allow our view access to the list of modes."""
return self.model.get_modes()
def set_mode(self, m) -> None:
"""Allow our view to set the mode."""
self.model.set_mode(m)
self.view.update_graph(True)
def get_data(self, offset, data_range):
"""Provide data to our view for the graph."""
return self.model.get_data(offset, data_range)
def main(self):
self.loop = urwid.MainLoop(self.view, self.view.palette)
self.loop.run()
def animate_graph(self, loop=None, user_data=None):
"""update the graph and schedule the next update"""
self.view.update_graph()
self.animate_alarm = self.loop.set_alarm_in(UPDATE_INTERVAL, self.animate_graph)
def stop_animation(self):
"""stop animating the graph"""
if self.animate_alarm:
self.loop.remove_alarm(self.animate_alarm)
self.animate_alarm = None
def main():
GraphController().main()
if __name__ == "__main__":
main()
| 12,077 | Python | .py | 322 | 28.73913 | 114 | 0.577962 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,146 | subproc.py | urwid_urwid/examples/subproc.py | #!/usr/bin/env python
from __future__ import annotations
import os
import subprocess
import sys
import urwid
factor_me = 362923067964327863989661926737477737673859044111968554257667
run_me = os.path.join(os.path.dirname(sys.argv[0]), "subproc2.py")
output_widget = urwid.Text(f"Factors of {factor_me:d}:\n")
edit_widget = urwid.Edit("Type anything or press enter to exit:")
frame_widget = urwid.Frame(
header=edit_widget,
body=urwid.Filler(output_widget, valign=urwid.BOTTOM),
focus_part="header",
)
def exit_on_enter(key: str | tuple[str, int, int, int]) -> None:
if key == "enter":
raise urwid.ExitMainLoop()
loop = urwid.MainLoop(frame_widget, unhandled_input=exit_on_enter)
def received_output(data: bytes) -> bool:
output_widget.set_text(output_widget.text + data.decode("utf8"))
return True
write_fd = loop.watch_pipe(received_output)
with subprocess.Popen( # noqa: S603
["python", "-u", run_me, str(factor_me)], # noqa: S607 # Example can be insecure
stdout=write_fd,
close_fds=True,
) as proc:
loop.run()
| 1,077 | Python | .py | 29 | 34.034483 | 86 | 0.725604 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,147 | fib.py | urwid_urwid/examples/fib.py | #!/usr/bin/env python
#
# Urwid example fibonacci sequence viewer / unbounded data demo
# Copyright (C) 2004-2007 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example fibonacci sequence viewer / unbounded data demo
Features:
- custom list walker class for browsing infinite set
- custom wrap mode "numeric" for wrapping numbers to right and bottom
"""
from __future__ import annotations
import typing
import urwid
if typing.TYPE_CHECKING:
from typing_extensions import Literal
class FibonacciWalker(urwid.ListWalker):
"""ListWalker-compatible class for browsing fibonacci set.
positions returned are (value at position-1, value at position) tuples.
"""
def __init__(self) -> None:
self.focus = (0, 1)
self.numeric_layout = NumericLayout()
def _get_at_pos(self, pos: tuple[int, int]) -> tuple[urwid.Text, tuple[int, int]]:
"""Return a widget and the position passed."""
return urwid.Text(f"{pos[1]:d}", layout=self.numeric_layout), pos
def get_focus(self) -> tuple[urwid.Text, tuple[int, int]]:
return self._get_at_pos(self.focus)
def set_focus(self, focus) -> None:
self.focus = focus
self._modified()
def get_next(self, position) -> tuple[urwid.Text, tuple[int, int]]:
a, b = position
focus = b, a + b
return self._get_at_pos(focus)
def get_prev(self, position) -> tuple[urwid.Text, tuple[int, int]]:
a, b = position
focus = b - a, a
return self._get_at_pos(focus)
def main() -> None:
palette = [
("body", "black", "dark cyan", "standout"),
("foot", "light gray", "black"),
("key", "light cyan", "black", "underline"),
(
"title",
"white",
"black",
),
]
footer_text = [
("title", "Fibonacci Set Viewer"),
" ",
("key", "UP"),
", ",
("key", "DOWN"),
", ",
("key", "PAGE UP"),
" and ",
("key", "PAGE DOWN"),
" move view ",
("key", "Q"),
" exits",
]
def exit_on_q(key: str | tuple[str, int, int, int]) -> None:
if key in {"q", "Q"}:
raise urwid.ExitMainLoop()
listbox = urwid.ListBox(FibonacciWalker())
footer = urwid.AttrMap(urwid.Text(footer_text), "foot")
view = urwid.Frame(urwid.AttrMap(listbox, "body"), footer=footer)
loop = urwid.MainLoop(view, palette, unhandled_input=exit_on_q)
loop.run()
class NumericLayout(urwid.TextLayout):
"""
TextLayout class for bottom-right aligned numbers
"""
def layout(
self,
text: str | bytes,
width: int,
align: Literal["left", "center", "right"] | urwid.Align,
wrap: Literal["any", "space", "clip", "ellipsis"] | urwid.WrapMode,
) -> list[list[tuple[int, int, int | bytes] | tuple[int, int | None]]]:
"""
Return layout structure for right justified numbers.
"""
lt = len(text)
r = lt % width # remaining segment not full width wide
if r:
return [
[(width - r, None), (r, 0, r)], # right-align the remaining segment on 1st line
*([(width, x, x + width)] for x in range(r, lt, width)), # fill the rest of the lines
]
return [[(width, x, x + width)] for x in range(0, lt, width)]
if __name__ == "__main__":
main()
| 4,209 | Python | .py | 111 | 31.711712 | 102 | 0.609528 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,148 | treesample.py | urwid_urwid/examples/treesample.py | #!/usr/bin/env python
#
# Trivial data browser
# This version:
# Copyright (C) 2010 Rob Lanphier
# Derived from browse.py in urwid distribution
# Copyright (C) 2004-2007 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example lazy directory browser / tree view
Features:
- custom selectable widgets for files and directories
- custom message widgets to identify access errors and empty directories
- custom list walker for displaying widgets in a tree fashion
"""
from __future__ import annotations
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Hashable, Iterable
class ExampleTreeWidget(urwid.TreeWidget):
"""Display widget for leaf nodes"""
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
return self.get_node().get_value()["name"]
class ExampleNode(urwid.TreeNode):
"""Data storage object for leaf nodes"""
def load_widget(self) -> ExampleTreeWidget:
return ExampleTreeWidget(self)
class ExampleParentNode(urwid.ParentNode):
"""Data storage object for interior/parent nodes"""
def load_widget(self) -> ExampleTreeWidget:
return ExampleTreeWidget(self)
def load_child_keys(self) -> Iterable[int]:
data = self.get_value()
return range(len(data["children"]))
def load_child_node(self, key) -> ExampleParentNode | ExampleNode:
"""Return either an ExampleNode or ExampleParentNode"""
childdata = self.get_value()["children"][key]
childdepth = self.get_depth() + 1
if "children" in childdata:
childclass = ExampleParentNode
else:
childclass = ExampleNode
return childclass(childdata, parent=self, key=key, depth=childdepth)
class ExampleTreeBrowser:
palette: typing.ClassVar[tuple[str, str, str, ...]] = [
("body", "black", "light gray"),
("focus", "light gray", "dark blue", "standout"),
("head", "yellow", "black", "standout"),
("foot", "light gray", "black"),
("key", "light cyan", "black", "underline"),
("title", "white", "black", "bold"),
("flag", "dark gray", "light gray"),
("error", "dark red", "light gray"),
]
footer_text: typing.ClassVar[list[tuple[str, str] | str]] = [
("title", "Example Data Browser"),
" ",
("key", "UP"),
",",
("key", "DOWN"),
",",
("key", "PAGE UP"),
",",
("key", "PAGE DOWN"),
" ",
("key", "+"),
",",
("key", "-"),
" ",
("key", "LEFT"),
" ",
("key", "HOME"),
" ",
("key", "END"),
" ",
("key", "Q"),
]
def __init__(self, data=None) -> None:
self.topnode = ExampleParentNode(data)
self.listbox = urwid.TreeListBox(urwid.TreeWalker(self.topnode))
self.listbox.offset_rows = 1
self.header = urwid.Text("")
self.footer = urwid.AttrMap(urwid.Text(self.footer_text), "foot")
self.view = urwid.Frame(
urwid.AttrMap(self.listbox, "body"),
header=urwid.AttrMap(self.header, "head"),
footer=self.footer,
)
def main(self) -> None:
"""Run the program."""
self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input)
self.loop.run()
def unhandled_input(self, k: str | tuple[str, int, int, int]) -> None:
if k in {"q", "Q"}:
raise urwid.ExitMainLoop()
def get_example_tree():
"""generate a quick 100 leaf tree for demo purposes"""
retval = {"name": "parent", "children": []}
for i in range(10):
retval["children"].append({"name": f"child {i!s}"})
retval["children"][i]["children"] = []
for j in range(10):
retval["children"][i]["children"].append({"name": "grandchild " + str(i) + "." + str(j)})
return retval
def main() -> None:
sample = get_example_tree()
ExampleTreeBrowser(sample).main()
if __name__ == "__main__":
main()
| 4,883 | Python | .py | 125 | 32.96 | 101 | 0.618866 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,149 | pop_up.py | urwid_urwid/examples/pop_up.py | #!/usr/bin/env python
from __future__ import annotations
import typing
import urwid
class PopUpDialog(urwid.WidgetWrap):
"""A dialog that appears with nothing but a close button"""
signals: typing.ClassVar[list[str]] = ["close"]
def __init__(self):
close_button = urwid.Button("that's pretty cool")
urwid.connect_signal(close_button, "click", lambda button: self._emit("close"))
pile = urwid.Pile(
[
urwid.Text("^^ I'm attached to the widget that opened me. Try resizing the window!\n"),
close_button,
]
)
super().__init__(urwid.AttrMap(urwid.Filler(pile), "popbg"))
class ThingWithAPopUp(urwid.PopUpLauncher):
def __init__(self) -> None:
super().__init__(urwid.Button("click-me"))
urwid.connect_signal(self.original_widget, "click", lambda button: self.open_pop_up())
def create_pop_up(self) -> PopUpDialog:
pop_up = PopUpDialog()
urwid.connect_signal(pop_up, "close", lambda button: self.close_pop_up())
return pop_up
def get_pop_up_parameters(self):
return {"left": 0, "top": 1, "overlay_width": 32, "overlay_height": 7}
def keypress(self, size: tuple[int], key: str) -> str | None:
parsed = super().keypress(size, key)
if parsed in {"q", "Q"}:
raise urwid.ExitMainLoop("Done")
return parsed
fill = urwid.Filler(urwid.Padding(ThingWithAPopUp(), urwid.CENTER, 15))
loop = urwid.MainLoop(fill, [("popbg", "white", "dark blue")], pop_ups=True)
loop.run()
| 1,578 | Python | .py | 35 | 37.742857 | 104 | 0.627207 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,150 | asyncio_socket_server.py | urwid_urwid/examples/asyncio_socket_server.py | #!/usr/bin/env python
"""Demo of using urwid with Python asyncio.
"""
from __future__ import annotations
import asyncio
import logging
import sys
import weakref
from datetime import datetime
import urwid
from urwid.display.raw import Screen
logging.basicConfig()
loop = asyncio.get_event_loop()
# -----------------------------------------------------------------------------
# General-purpose setup code
def build_widgets():
input1 = urwid.Edit("What is your name? ")
input2 = urwid.Edit("What is your quest? ")
input3 = urwid.Edit("What is the capital of Assyria? ")
inputs = [input1, input2, input3]
def update_clock(widget_ref):
widget = widget_ref()
if not widget:
# widget is dead; the main loop must've been destroyed
return
widget.set_text(datetime.now().isoformat())
# Schedule us to update the clock again in one second
loop.call_later(1, update_clock, widget_ref)
clock = urwid.Text("")
update_clock(weakref.ref(clock))
return urwid.Filler(urwid.Pile([clock, *inputs]), urwid.TOP)
def unhandled(key):
if key == "ctrl c":
raise urwid.ExitMainLoop
# -----------------------------------------------------------------------------
# Demo 1
def demo1():
"""Plain old urwid app. Just happens to be run atop asyncio as the event
loop.
Note that the clock is updated using the asyncio loop directly, not via any
of urwid's facilities.
"""
main_widget = build_widgets()
urwid_loop = urwid.MainLoop(
main_widget,
event_loop=urwid.AsyncioEventLoop(loop=loop),
unhandled_input=unhandled,
)
urwid_loop.run()
# -----------------------------------------------------------------------------
# Demo 2
class AsyncScreen(Screen):
"""An urwid screen that speaks to an asyncio stream, rather than polling
file descriptors.
This is fairly limited; it can't, for example, determine the size of the
remote screen. Fixing that depends on the nature of the stream.
"""
def __init__(self, reader, writer, encoding="utf-8"):
self.reader = reader
self.writer = writer
self.encoding = encoding
super().__init__(None, None)
_pending_task = None
def write(self, data):
self.writer.write(data.encode(self.encoding))
def flush(self):
pass
def hook_event_loop(self, event_loop, callback):
# Wait on the reader's read coro, and when there's data to read, call
# the callback and then wait again
def pump_reader(fut=None):
if fut is None:
# First call, do nothing
pass
elif fut.cancelled():
# This is in response to an earlier .read() call, so don't
# schedule another one!
return
elif fut.exception():
pass
else:
try:
self.parse_input(event_loop, callback, bytearray(fut.result()))
except urwid.ExitMainLoop:
# This will immediately close the transport and thus the
# connection, which in turn calls connection_lost, which
# stops the screen and the loop
self.writer.abort()
# create_task() schedules a coroutine without using `yield from` or
# `await`, which are syntax errors in Pythons before 3.5
self._pending_task = event_loop._loop.create_task(self.reader.read(1024))
self._pending_task.add_done_callback(pump_reader)
pump_reader()
def unhook_event_loop(self, event_loop):
if self._pending_task:
self._pending_task.cancel()
del self._pending_task
class UrwidProtocol(asyncio.Protocol):
def connection_made(self, transport):
print("Got a client!")
self.transport = transport
# StreamReader is super convenient here; it has a regular method on our
# end (feed_data), and a coroutine on the other end that will
# faux-block until there's data to be read. We could also just call a
# method directly on the screen, but this keeps the screen somewhat
# separate from the protocol.
self.reader = asyncio.StreamReader(loop=loop)
screen = AsyncScreen(self.reader, transport)
main_widget = build_widgets()
self.urwid_loop = urwid.MainLoop(
main_widget,
event_loop=urwid.AsyncioEventLoop(loop=loop),
screen=screen,
unhandled_input=unhandled,
)
self.urwid_loop.start()
def data_received(self, data):
self.reader.feed_data(data)
def connection_lost(self, exc):
print("Lost a client...")
self.reader.feed_eof()
self.urwid_loop.stop()
def demo2():
"""Urwid app served over the network to multiple clients at once, using an
asyncio Protocol.
"""
coro = loop.create_server(UrwidProtocol, port=12345)
loop.run_until_complete(coro)
print("OK, good to go! Try this in another terminal (or two):")
print()
print(" socat TCP:127.0.0.1:12345 STDIN,rawer")
print()
loop.run_forever()
if __name__ == "__main__":
if len(sys.argv) == 2:
which = sys.argv[1]
else:
which = None
if which == "1":
demo1()
elif which == "2":
demo2()
else:
print("Please run me with an argument of either 1 or 2.")
sys.exit(1)
| 5,564 | Python | .py | 145 | 30.475862 | 85 | 0.599516 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,151 | palette_test.py | urwid_urwid/examples/palette_test.py | #!/usr/bin/env python
#
# Urwid Palette Test. Showing off highcolor support
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Palette test. Shows the available foreground and background settings
in monochrome, 16 color, 88 color, 256 color, and 24-bit (true) color modes.
"""
from __future__ import annotations
import re
import typing
import urwid
if typing.TYPE_CHECKING:
from typing_extensions import Literal
CHART_TRUE = """
#e50000#e51000#e52000#e53000#e54000#e55000#e56000#e57000#e58000#e59000\
#e5a000#e5b100#e5c100#e5d100#e5e100#d9e500#c9e500#b9e500#a9e500#99e500\
#89e500#79e500#68e500#58e500#48e500#38e500#28e500#18e500#08e500#00e507\
#00e517#00e527#00e538#00e548#00e558#00e568#00e578#00e588#00e598#00e5a8\
#00e5b8#00e5c8#00e5d8#00e1e5#00d1e5#00c1e5#00b1e5#00a1e5#0091e5#0081e5\
#0071e5#0061e5#0051e5#0040e5#0030e5#0020e5#0010e5#0000e5#0f00e5#1f00e5\
#2f00e5#3f00e5#4f00e5#5f00e5#7000e5#8000e5#9000e5#a000e5#b000e5#c000e5\
#d000e5#e000e5#e500da#e500ca#e500b9#e500a9#e50099#e50089
#da0000#da0f00#da1e00#da2e00#da3d00#da4c00#da5c00#da6b00#da7a00#da8a00\
#da9900#daa800#dab800#dac700#dad600#cfda00#c0da00#b0da00#a1da00#92da00\
#82da00#73da00#64da00#54da00#45da00#35da00#26da00#17da00#07da00#00da07\
#00da16#00da26#00da35#00da44#00da54#00da63#00da72#00da82#00da91#00daa0\
#00dab0#00dabf#00dace#00d7da#00c8da#00b8da#00a9da#0099da#008ada#007bda\
#006bda#005cda#004dda#003dda#002eda#001fda#000fda#0000da#0e00da#1e00da\
#2d00da#3c00da#4c00da#5b00da#6a00da#7a00da#8900da#9800da#a800da#b700da\
#c600da#d600da#da00cf#da00c0#da00b1#da00a1#da0092#da0083
#d00000#d00e00#d01d00#d02b00#d03a00#d04800#d05700#d06600#d07400#d08300\
#d09100#d0a000#d0af00#d0bd00#d0cc00#c5d000#b6d000#a8d000#99d000#8ad000\
#7cd000#6dd000#5fd000#50d000#41d000#33d000#24d000#16d000#07d000#00d007\
#00d015#00d024#00d032#00d041#00d04f#00d05e#00d06d#00d07b#00d08a#00d098\
#00d0a7#00d0b6#00d0c4#00ccd0#00bed0#00afd0#00a1d0#0092d0#0083d0#0075d0\
#0066d0#0058d0#0049d0#003ad0#002cd0#001dd0#000fd0#0000d0#0e00d0#1c00d0\
#2b00d0#3900d0#4800d0#5600d0#6500d0#7400d0#8200d0#9100d0#9f00d0#ae00d0\
#bd00d0#cb00d0#d000c5#d000b7#d000a8#d00099#d0008b#d0007c
#c50000#c50d00#c51b00#c52900#c53700#c54500#c55300#c56000#c56e00#c57c00\
#c58a00#c59800#c5a600#c5b300#c5c100#bbc500#adc500#9fc500#91c500#83c500\
#75c500#68c500#5ac500#4cc500#3ec500#30c500#22c500#15c500#07c500#00c506\
#00c514#00c522#00c530#00c53e#00c54b#00c559#00c567#00c575#00c583#00c591\
#00c59e#00c5ac#00c5ba#00c2c5#00b4c5#00a6c5#0098c5#008ac5#007dc5#006fc5\
#0061c5#0053c5#0045c5#0037c5#002ac5#001cc5#000ec5#0000c5#0d00c5#1b00c5\
#2800c5#3600c5#4400c5#5200c5#6000c5#6e00c5#7c00c5#8900c5#9700c5#a500c5\
#b300c5#c100c5#c500bb#c500ad#c5009f#c50092#c50084#c50076
#ba0000#ba0d00#ba1a00#ba2700#ba3400#ba4100#ba4e00#ba5b00#ba6800#ba7500\
#ba8200#ba8f00#ba9c00#baaa00#bab700#b0ba00#a3ba00#96ba00#89ba00#7cba00\
#6fba00#62ba00#55ba00#48ba00#3bba00#2eba00#20ba00#13ba00#06ba00#00ba06\
#00ba13#00ba20#00ba2d#00ba3a#00ba47#00ba54#00ba61#00ba6e#00ba7c#00ba89\
#00ba96#00baa3#00bab0#00b7ba#00aaba#009dba#0090ba#0083ba#0076ba#0069ba\
#005cba#004eba#0041ba#0034ba#0027ba#001aba#000dba#0000ba#0c00ba#1900ba\
#2600ba#3300ba#4000ba#4e00ba#5b00ba#6800ba#7500ba#8200ba#8f00ba#9c00ba\
#a900ba#b600ba#ba00b1#ba00a4#ba0097#ba008a#ba007d#ba006f
#af0000#af0c00#af1800#af2400#af3100#af3d00#af4900#af5600#af6200#af6e00\
#af7b00#af8700#af9300#afa000#afac00#a6af00#9aaf00#8eaf00#81af00#75af00\
#69af00#5caf00#50af00#44af00#37af00#2baf00#1faf00#12af00#06af00#00af05\
#00af12#00af1e#00af2a#00af37#00af43#00af4f#00af5c#00af68#00af74#00af81\
#00af8d#00af99#00afa6#00adaf#00a0af#0094af#0088af#007baf#006faf#0063af\
#0056af#004aaf#003eaf#0031af#0025af#0019af#000caf#0000af#0b00af#1800af\
#2400af#3000af#3d00af#4900af#5500af#6200af#6e00af#7a00af#8700af#9300af\
#9f00af#ac00af#af00a7#af009a#af008e#af0082#af0075#af0069
#a50000#a50b00#a51700#a52200#a52e00#a53900#a54500#a55100#a55c00#a56800\
#a57300#a57f00#a58a00#a59600#a5a200#9ca500#90a500#85a500#79a500#6ea500\
#62a500#57a500#4ba500#3fa500#34a500#28a500#1da500#11a500#06a500#00a505\
#00a511#00a51c#00a528#00a533#00a53f#00a54b#00a556#00a562#00a56d#00a579\
#00a584#00a590#00a59c#00a2a5#0096a5#008ba5#007fa5#0074a5#0068a5#005da5\
#0051a5#0045a5#003aa5#002ea5#0023a5#0017a5#000ca5#0000a5#0b00a5#1600a5\
#2200a5#2d00a5#3900a5#4500a5#5000a5#5c00a5#6700a5#7300a5#7e00a5#8a00a5\
#9600a5#a100a5#a5009c#a50091#a50085#a5007a#a5006e#a50063
#9a0000#9a0a00#9a1500#9a2000#9a2b00#9a3600#9a4000#9a4b00#9a5600#9a6100\
#9a6c00#9a7700#9a8100#9a8c00#9a9700#929a00#879a00#7c9a00#719a00#679a00\
#5c9a00#519a00#469a00#3b9a00#309a00#269a00#1b9a00#109a00#059a00#009a05\
#009a10#009a1a#009a25#009a30#009a3b#009a46#009a50#009a5b#009a66#009a71\
#009a7c#009a87#009a91#00979a#008d9a#00829a#00779a#006c9a#00619a#00569a\
#004c9a#00419a#00369a#002b9a#00209a#00169a#000b9a#00009a#0a009a#15009a\
#20009a#2a009a#35009a#40009a#4b009a#56009a#61009a#6b009a#76009a#81009a\
#8c009a#97009a#9a0092#9a0087#9a007d#9a0072#9a0067#9a005c
#8f0000#8f0a00#8f1400#8f1e00#8f2800#8f3200#8f3c00#8f4600#8f5000#8f5a00\
#8f6400#8f6e00#8f7800#8f8200#8f8c00#888f00#7e8f00#748f00#698f00#5f8f00\
#558f00#4b8f00#418f00#378f00#2d8f00#238f00#198f00#0f8f00#058f00#008f04\
#008f0e#008f18#008f23#008f2d#008f37#008f41#008f4b#008f55#008f5f#008f69\
#008f73#008f7d#008f87#008d8f#00838f#00798f#006f8f#00658f#005b8f#00508f\
#00468f#003c8f#00328f#00288f#001e8f#00148f#000a8f#00008f#09008f#13008f\
#1d008f#27008f#31008f#3c008f#46008f#50008f#5a008f#64008f#6e008f#78008f\
#82008f#8c008f#8f0088#8f007e#8f0074#8f006a#8f0060#8f0056
#840000#840900#841200#841b00#842500#842e00#843700#844100#844a00#845300\
#845d00#846600#846f00#847900#848200#7d8400#748400#6b8400#628400#588400\
#4f8400#468400#3c8400#338400#2a8400#208400#178400#0e8400#048400#008404\
#00840d#008417#008420#008429#008433#00843c#008445#00844f#008458#008461\
#00846a#008474#00847d#008284#007984#007084#006684#005d84#005484#004a84\
#004184#003884#002e84#002584#001c84#001284#000984#000084#080084#120084\
#1b0084#240084#2e0084#370084#400084#4a0084#530084#5c0084#660084#6f0084\
#780084#820084#84007e#840074#84006b#840062#840059#84004f
#7a0000#7a0800#7a1100#7a1900#7a2200#7a2a00#7a3300#7a3b00#7a4400#7a4d00\
#7a5500#7a5e00#7a6600#7a6f00#7a7700#737a00#6b7a00#627a00#5a7a00#517a00\
#487a00#407a00#377a00#2f7a00#267a00#1e7a00#157a00#0d7a00#047a00#007a04\
#007a0c#007a15#007a1d#007a26#007a2e#007a37#007a40#007a48#007a51#007a59\
#007a62#007a6a#007a73#00787a#006f7a#00677a#005e7a#00557a#004d7a#00447a\
#003c7a#00337a#002b7a#00227a#001a7a#00117a#00087a#00007a#08007a#10007a\
#19007a#21007a#2a007a#33007a#3b007a#44007a#4c007a#55007a#5d007a#66007a\
#6f007a#77007a#7a0074#7a006b#7a0062#7a005a#7a0051#7a0049
#6f0000#6f0700#6f0f00#6f1700#6f1f00#6f2700#6f2e00#6f3600#6f3e00#6f4600\
#6f4e00#6f5500#6f5d00#6f6500#6f6d00#696f00#616f00#596f00#526f00#4a6f00\
#426f00#3a6f00#326f00#2b6f00#236f00#1b6f00#136f00#0b6f00#046f00#006f03\
#006f0b#006f13#006f1b#006f23#006f2a#006f32#006f3a#006f42#006f4a#006f51\
#006f59#006f61#006f69#006d6f#00656f#005e6f#00566f#004e6f#00466f#003e6f\
#00366f#002f6f#00276f#001f6f#00176f#000f6f#00086f#00006f#07006f#0f006f\
#17006f#1e006f#26006f#2e006f#36006f#3e006f#46006f#4d006f#55006f#5d006f\
#65006f#6d006f#6f0069#6f0062#6f005a#6f0052#6f004a#6f0042
#640000#640700#640e00#641500#641c00#642300#642a00#643100#643800#643f00\
#644600#644d00#645400#645b00#646200#5f6400#586400#516400#4a6400#436400\
#3c6400#356400#2e6400#266400#1f6400#186400#116400#0a6400#036400#006403\
#00640a#006411#006418#00641f#006426#00642d#006434#00643b#006442#006449\
#006451#006458#00645f#006364#005c64#005464#004d64#004664#003f64#003864\
#003164#002a64#002364#001c64#001564#000e64#000764#000064#060064#0d0064\
#140064#1b0064#230064#2a0064#310064#380064#3f0064#460064#4d0064#540064\
#5b0064#620064#64005f#640058#640051#64004a#640043#64003c
#590000#590600#590c00#591200#591900#591f00#592500#592c00#593200#593800\
#593f00#594500#594b00#595100#595800#555900#4e5900#485900#425900#3c5900\
#355900#2f5900#295900#225900#1c5900#165900#0f5900#095900#035900#005903\
#005909#00590f#005915#00591c#005922#005928#00592f#005935#00593b#005942\
#005948#00594e#005955#005859#005259#004b59#004559#003f59#003859#003259\
#002c59#002659#001f59#001959#001359#000c59#000659#000059#060059#0c0059\
#120059#180059#1f0059#250059#2b0059#320059#380059#3e0059#450059#4b0059\
#510059#580059#590055#59004f#590048#590042#59003c#590035
#4f0000#4f0500#4f0b00#4f1000#4f1600#4f1b00#4f2100#4f2600#4f2c00#4f3100\
#4f3700#4f3d00#4f4200#4f4800#4f4d00#4b4f00#454f00#3f4f00#3a4f00#344f00\
#2f4f00#294f00#244f00#1e4f00#194f00#134f00#0d4f00#084f00#024f00#004f02\
#004f08#004f0d#004f13#004f18#004f1e#004f23#004f29#004f2f#004f34#004f3a\
#004f3f#004f45#004f4a#004d4f#00484f#00424f#003d4f#00374f#00324f#002c4f\
#00274f#00214f#001b4f#00164f#00104f#000b4f#00054f#00004f#05004f#0a004f\
#10004f#16004f#1b004f#21004f#26004f#2c004f#31004f#37004f#3c004f#42004f\
#47004f#4d004f#4f004b#4f0045#4f0040#4f003a#4f0035#4f002f
#440000#440400#440900#440e00#441300#441800#441c00#442100#442600#442b00\
#443000#443400#443900#443e00#444300#404400#3c4400#374400#324400#2d4400\
#284400#244400#1f4400#1a4400#154400#104400#0c4400#074400#024400#004402\
#004407#00440b#004410#004415#00441a#00441f#004423#004428#00442d#004432\
#004437#00443b#004440#004344#003e44#003944#003444#003044#002b44#002644\
#002144#001c44#001844#001344#000e44#000944#000444#000044#040044#090044\
#0e0044#130044#170044#1c0044#210044#260044#2b0044#2f0044#340044#390044\
#3e0044#430044#440041#44003c#440037#440032#44002d#440029
#390000#390400#390800#390c00#391000#391400#391800#391c00#392000#392400\
#392800#392c00#393000#393400#393800#363900#323900#2e3900#2a3900#263900\
#223900#1e3900#1a3900#163900#123900#0e3900#0a3900#063900#023900#003901\
#003905#00390a#00390e#003912#003916#00391a#00391e#003922#003926#00392a\
#00392e#003932#003936#003839#003439#003039#002c39#002839#002439#002039\
#001c39#001839#001439#001039#000c39#000839#000439#000039#030039#070039\
#0b0039#100039#140039#180039#1c0039#200039#240039#280039#2c0039#300039\
#340039#380039#390036#390032#39002e#39002a#390026#390022
#2e0000#2e0300#2e0600#2e0900#2e0d00#2e1000#2e1300#2e1700#2e1a00#2e1d00\
#2e2000#2e2400#2e2700#2e2a00#2e2e00#2c2e00#292e00#252e00#222e00#1f2e00\
#1c2e00#182e00#152e00#122e00#0e2e00#0b2e00#082e00#052e00#012e00#002e01\
#002e04#002e08#002e0b#002e0e#002e12#002e15#002e18#002e1b#002e1f#002e22\
#002e25#002e29#002e2c#002e2e#002a2e#00272e#00242e#00212e#001d2e#001a2e\
#00172e#00132e#00102e#000d2e#000a2e#00062e#00032e#00002e#03002e#06002e\
#09002e#0d002e#10002e#13002e#16002e#1a002e#1d002e#20002e#24002e#27002e\
#2a002e#2d002e#2e002c#2e0029#2e0026#2e0022#2e001f#2e001c
#240000#240200#240500#240700#240a00#240c00#240f00#241100#241400#241600\
#241900#241b00#241e00#242100#242300#222400#1f2400#1d2400#1a2400#182400\
#152400#132400#102400#0e2400#0b2400#082400#062400#032400#012400#002401\
#002403#002406#002408#00240b#00240d#002410#002413#002415#002418#00241a\
#00241d#00241f#002422#002324#002124#001e24#001c24#001924#001624#001424\
#001124#000f24#000c24#000a24#000724#000524#000224#000024#020024#040024\
#070024#0a0024#0c0024#0f0024#110024#140024#160024#190024#1b0024#1e0024\
#200024#230024#240022#24001f#24001d#24001a#240018#240015
#190000#190100#190300#190500#190700#190800#190a00#190c00#190e00#191000\
#191100#191300#191500#191700#191900#181900#161900#141900#121900#111900\
#0f1900#0d1900#0b1900#091900#081900#061900#041900#021900#001900#001900\
#001902#001904#001906#001908#001909#00190b#00190d#00190f#001910#001912\
#001914#001916#001918#001919#001719#001519#001319#001119#001019#000e19\
#000c19#000a19#000919#000719#000519#000319#000119#000019#010019#030019\
#050019#070019#080019#0a0019#0c0019#0e0019#100019#110019#130019#150019\
#170019#180019#190018#190016#190014#190012#190011#19000f
"""
# raise Exception(CHART_TRUE)
CHART_256 = """
brown__ dark_red_ dark_magenta_ dark_blue_ dark_cyan_ dark_green_
yellow_ light_red light_magenta light_blue light_cyan light_green
#00f#06f#08f#0af#0df#0ff black_______ dark_gray___
#60f#00d#06d#08d#0ad#0dd#0fd light_gray__ white_______
#80f#60d#00a#06a#08a#0aa#0da#0fa
#a0f#80d#60a#008#068#088#0a8#0d8#0f8
#d0f#a0d#80d#608#006#066#086#0a6#0d6#0f6
#f0f#d0d#a0a#808#606#000#060#080#0a0#0d0#0f0#0f6#0f8#0fa#0fd#0ff
#f0d#d0a#a08#806#600#660#680#6a0#6d0#6f0#6f6#6f8#6fa#6fd#6ff#0df
#f0a#d08#a06#800#860#880#8a0#8d0#8f0#8f6#8f8#8fa#8fd#8ff#6df#0af
#f08#d06#a00#a60#a80#aa0#ad0#af0#af6#af8#afa#afd#aff#8df#6af#08f
#f06#d00#d60#d80#da0#dd0#df0#df6#df8#dfa#dfd#dff#adf#8af#68f#06f
#f00#f60#f80#fa0#fd0#ff0#ff6#ff8#ffa#ffd#fff#ddf#aaf#88f#66f#00f
#fd0#fd6#fd8#fda#fdd#fdf#daf#a8f#86f#60f
#66d#68d#6ad#6dd #fa0#fa6#fa8#faa#fad#faf#d8f#a6f#80f
#86d#66a#68a#6aa#6da #f80#f86#f88#f8a#f8d#f8f#d6f#a0f
#a6d#86a#668#688#6a8#6d8 #f60#f66#f68#f6a#f6d#f6f#d0f
#d6d#a6a#868#666#686#6a6#6d6#6d8#6da#6dd #f00#f06#f08#f0a#f0d#f0f
#d6a#a68#866#886#8a6#8d6#8d8#8da#8dd#6ad
#d68#a66#a86#aa6#ad6#ad8#ada#add#8ad#68d
#d66#d86#da6#dd6#dd8#dda#ddd#aad#88d#66d g78_g82_g85_g89_g93_g100
#da6#da8#daa#dad#a8d#86d g52_g58_g62_g66_g70_g74_
#88a#8aa #d86#d88#d8a#d8d#a6d g27_g31_g35_g38_g42_g46_g50_
#a8a#888#8a8#8aa #d66#d68#d6a#d6d g0__g3__g7__g11_g15_g19_g23_
#a88#aa8#aaa#88a
#a88#a8a
"""
CHART_88 = """
brown__ dark_red_ dark_magenta_ dark_blue_ dark_cyan_ dark_green_
yellow_ light_red light_magenta light_blue light_cyan light_green
#00f#08f#0cf#0ff black_______ dark_gray___
#80f#00c#08c#0cc#0fc light_gray__ white_______
#c0f#80c#008#088#0c8#0f8
#f0f#c0c#808#000#080#0c0#0f0#0f8#0fc#0ff #88c#8cc
#f0c#c08#800#880#8c0#8f0#8f8#8fc#8ff#0cf #c8c#888#8c8#8cc
#f08#c00#c80#cc0#cf0#cf8#cfc#cff#8cf#08f #c88#cc8#ccc#88c
#f00#f80#fc0#ff0#ff8#ffc#fff#ccf#88f#00f #c88#c8c
#fc0#fc8#fcc#fcf#c8f#80f
#f80#f88#f8c#f8f#c0f g62_g74_g82_g89_g100
#f00#f08#f0c#f0f g0__g19_g35_g46_g52
"""
CHART_16 = """
brown__ dark_red_ dark_magenta_ dark_blue_ dark_cyan_ dark_green_
yellow_ light_red light_magenta light_blue light_cyan light_green
black_______ dark_gray___ light_gray__ white_______
"""
ATTR_RE = re.compile("(?P<whitespace>[ \n]*)(?P<entry>(?:#[0-9A-Fa-f]{6})|(?:#[0-9A-Fa-f]{3})|(?:[^ \n]+))")
LONG_ATTR = 7
SHORT_ATTR = 4 # length of short high-colour descriptions which may
# be packed one after the next
def parse_chart(chart: str, convert):
"""
Convert string chart into text markup with the correct attributes.
chart -- palette chart as a string
convert -- function that converts a single palette entry to an
(attr, text) tuple, or None if no match is found
"""
out = []
for match in ATTR_RE.finditer(chart):
if match.group("whitespace"):
out.append(match.group("whitespace"))
entry = match.group("entry")
entry = entry.replace("_", " ")
while entry:
if chart == CHART_TRUE and len(entry) == LONG_ATTR:
attrtext = convert(entry[:LONG_ATTR])
elen = LONG_ATTR
else:
elen = SHORT_ATTR
attrtext = convert(entry[:SHORT_ATTR])
# try the first four characters
if attrtext:
entry = entry[elen:].strip()
else: # try the whole thing
attrtext = convert(entry.strip())
assert attrtext, f"Invalid palette entry: {entry!r}" # noqa: S101 # "assert" is ok for examples
elen = len(entry)
entry = ""
attr, text = attrtext
if chart == CHART_TRUE:
out.append((attr, "â–„"))
else:
out.append((attr, text.ljust(elen)))
return out
def foreground_chart(chart: str, background, colors: Literal[1, 16, 88, 256, 16777216]):
"""
Create text markup for a foreground colour chart
chart -- palette chart as string
background -- colour to use for background of chart
colors -- number of colors (88 or 256)
"""
def convert_foreground(entry):
try:
attr = urwid.AttrSpec(entry, background, colors)
except urwid.AttrSpecError:
return None
return attr, entry
return parse_chart(chart, convert_foreground)
def background_chart(chart: str, foreground, colors: Literal[1, 16, 88, 256, 16777216]):
"""
Create text markup for a background colour chart
chart -- palette chart as string
foreground -- colour to use for foreground of chart
colors -- number of colors (88 or 256)
This will remap 8 <= colour < 16 to high-colour versions
in the hopes of greater compatibility
"""
def convert_background(entry):
try:
attr = urwid.AttrSpec(foreground, entry, colors)
except urwid.AttrSpecError:
return None
# fix 8 <= colour < 16
if colors > 16 and attr.background_basic and attr.background_number >= 8:
# use high-colour with same number
entry = f"h{attr.background_number:d}"
attr = urwid.AttrSpec(foreground, entry, colors)
return attr, entry
return parse_chart(chart, convert_background)
def main() -> None:
palette = [
("header", "black,underline", "light gray", "standout,underline", "black,underline", "#88a"),
("panel", "light gray", "dark blue", "", "#ffd", "#00a"),
("focus", "light gray", "dark cyan", "standout", "#ff8", "#806"),
]
screen = urwid.display.raw.Screen()
screen.register_palette(palette)
lb = urwid.SimpleListWalker([])
chart_offset = None # offset of chart in lb list
mode_radio_buttons = []
chart_radio_buttons = []
def fcs(widget) -> urwid.AttrMap:
# wrap widgets that can take focus
return urwid.AttrMap(widget, None, "focus")
def set_mode(colors: int, is_foreground_chart: bool) -> None:
# set terminal mode and redraw chart
screen.set_terminal_properties(colors)
screen.reset_default_terminal_palette()
chart_fn = (background_chart, foreground_chart)[is_foreground_chart]
if colors == 1:
lb[chart_offset] = urwid.Divider()
else:
chart: str = {16: CHART_16, 88: CHART_88, 256: CHART_256, 2**24: CHART_TRUE}[colors]
txt = chart_fn(chart, "default", colors)
lb[chart_offset] = urwid.Text(txt, wrap=urwid.CLIP)
def on_mode_change(colors: int, rb: urwid.RadioButton, state: bool) -> None:
# if this radio button is checked
if state:
is_foreground_chart = chart_radio_buttons[0].state
set_mode(colors, is_foreground_chart)
def mode_rb(text: str, colors: int, state: bool = False) -> urwid.AttrMap:
# mode radio buttons
rb = urwid.RadioButton(mode_radio_buttons, text, state)
urwid.connect_signal(rb, "change", on_mode_change, user_args=(colors,))
return fcs(rb)
def on_chart_change(rb: urwid.RadioButton, state: bool) -> None:
# handle foreground check box state change
set_mode(screen.colors, state)
def click_exit(button) -> typing.NoReturn:
raise urwid.ExitMainLoop()
lb.extend(
[
urwid.AttrMap(urwid.Text("Urwid Palette Test"), "header"),
urwid.AttrMap(
urwid.Columns(
[
urwid.Pile(
[
mode_rb("Monochrome", 1),
mode_rb("16-Color", 16, True),
mode_rb("88-Color", 88),
mode_rb("256-Color", 256),
mode_rb("24-bit Color", 2**24),
]
),
urwid.Pile(
[
fcs(urwid.RadioButton(chart_radio_buttons, "Foreground Colors", True, on_chart_change)),
fcs(urwid.RadioButton(chart_radio_buttons, "Background Colors")),
urwid.Divider(),
fcs(urwid.Button("Exit", click_exit)),
]
),
]
),
"panel",
),
]
)
chart_offset = len(lb)
lb.extend([urwid.Divider()]) # placeholder for the chart
set_mode(16, True) # displays the chart
def unhandled_input(key: str | tuple[str, int, int, int]) -> None:
if key in {"Q", "q", "esc"}:
raise urwid.ExitMainLoop()
urwid.MainLoop(urwid.ListBox(lb), screen=screen, unhandled_input=unhandled_input).run()
if __name__ == "__main__":
main()
| 21,848 | Python | .py | 392 | 49.877551 | 120 | 0.720131 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,152 | lcd_cf635.py | urwid_urwid/examples/lcd_cf635.py | #!/usr/bin/env python
"""
The crystalfontz 635 has these characters in ROM:
....X. ...... ......
...XX. .XXXXX ..XXX.
..XXX. .XXXXX .XXXXX
.XXXX. .XXXXX .XXXXX
..XXX. .XXXXX .XXXXX
...XX. .XXXXX ..XXX.
....X. ...... ......
...... ...... ......
0x11 0xd0 0xbb
By adding the characters in CGRAM below we can use them as part of a
horizontal slider control, selected check box and selected radio button
respectively.
"""
from __future__ import annotations
import sys
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Callable
from typing_extensions import Literal
CGRAM = """
...... ...... ...... ...... ..X... ...... ...... ......
XXXXXX XXXXXX XXXXXX XXXXXX X.XX.. .XXXXX ..XXX. .....X
...... XX.... XXXX.. XXXXXX X.XXX. .X...X .X...X ....XX
...... XX.... XXXX.. XXXXXX X.XXXX .X...X .X...X .X.XX.
...... XX.... XXXX.. XXXXXX X.XXX. .X...X .X...X .XXX..
XXXXXX XXXXXX XXXXXX XXXXXX X.XX.. .XXXXX ..XXX. ..X...
...... ...... ...... ...... ..X... ...... ...... ......
...... ...... ...... ...... ...... ...... ...... ......
"""
def program_cgram(screen_inst: urwid.display.lcd.CF635Screen) -> None:
"""
Load the character data
"""
# convert .'s and X's above into integer data
cbuf = [[] for x in range(8)]
for row in CGRAM.strip().split("\n"):
rowsegments = row.strip().split()
for num, r in enumerate(rowsegments):
accum = 0
for c in r:
accum = (accum << 1) + (c == "X")
cbuf[num].append(accum)
for num, cdata in enumerate(cbuf):
screen_inst.program_cgram(num, cdata)
class LCDCheckBox(urwid.CheckBox):
"""
A check box+label that uses only one character for the check box,
including custom CGRAM character
"""
states: typing.ClassVar[dict[bool, urwid.SelectableIcon]] = {
True: urwid.SelectableIcon("\xd0"),
False: urwid.SelectableIcon("\x05"),
}
reserve_columns = 1
class LCDRadioButton(urwid.RadioButton):
"""
A radio button+label that uses only one character for the radio button,
including custom CGRAM character
"""
states: typing.ClassVar[dict[bool, urwid.SelectableIcon]] = {
True: urwid.SelectableIcon("\xbb"),
False: urwid.SelectableIcon("\x06"),
}
reserve_columns = 1
class LCDProgressBar(urwid.Widget):
"""
The "progress bar" used by the horizontal slider for this device,
using custom CGRAM characters
"""
segments = "\x00\x01\x02\x03"
_sizing = frozenset([urwid.Sizing.FLOW])
def __init__(self, data_range, value) -> None:
super().__init__()
self.range = data_range
self.value = value
def rows(self, size, focus=False) -> int:
return 1
def render(self, size, focus=False):
"""
Draw the bar with self.segments where [0] is empty and [-1]
is completely full
"""
(maxcol,) = size
steps = self.get_steps(size)
filled = urwid.int_scale(self.value, self.range, steps)
full_segments = int(filled / (len(self.segments) - 1))
last_char = filled % (len(self.segments) - 1) + 1
s = (
self.segments[-1] * full_segments
+ self.segments[last_char]
+ self.segments[0] * (maxcol - full_segments - 1)
)
return urwid.Text(s).render(size)
def move_position(self, size, direction):
"""
Update and return the value one step +ve or -ve, based on
the size of the displayed bar.
direction -- 1 for +ve, 0 for -ve
"""
steps = self.get_steps(size)
filled = urwid.int_scale(self.value, self.range, steps)
filled += 2 * direction - 1
value = urwid.int_scale(filled, steps, self.range)
value = max(0, min(self.range - 1, value))
if value != self.value:
self.value = value
self._invalidate()
return value
def get_steps(self, size):
"""
Return the number of steps available given size for rendering
the bar and number of segments we can draw.
"""
(maxcol,) = size
return maxcol * (len(self.segments) - 1)
class LCDHorizontalSlider(urwid.WidgetWrap[urwid.Columns]):
"""
A slider control using custom CGRAM characters
"""
def __init__(self, data_range, value, callback):
self.bar = LCDProgressBar(data_range, value)
cols = urwid.Columns(
[
(1, urwid.SelectableIcon("\x11")),
self.bar,
(1, urwid.SelectableIcon("\x04")),
]
)
super().__init__(cols)
self.callback = callback
def keypress(self, size, key: str):
# move the slider based on which arrow is focused
if key == "enter":
# use the correct size for adjusting the bar
self.bar.move_position((self._w.column_widths(size)[1],), self._w.get_focus_column() != 0)
self.callback(self.bar.value)
return None
return super().keypress(size, key)
class MenuOption(urwid.Button):
"""
A menu option, indicated with a single arrow character
"""
def __init__(self, label, submenu):
super().__init__("")
# use a Text widget for label, we want the cursor
# on the arrow not the label
self._label = urwid.Text("")
self.set_label(label)
self._w = urwid.Columns([(1, urwid.SelectableIcon("\xdf")), self._label])
urwid.connect_signal(self, "click", lambda option: show_menu(submenu))
def keypress(self, size, key: str):
if key == "right":
key = "enter"
return super().keypress(size, key)
class Menu(urwid.ListBox):
def __init__(self, widgets):
self.menu_parent = None
super().__init__(urwid.SimpleListWalker(widgets))
def keypress(self, size, key: str):
"""
Go back to the previous menu on cancel button (mapped to esc)
"""
key = super().keypress(size, key)
if key in {"left", "esc"} and self.menu_parent:
show_menu(self.menu_parent)
return None
return key
def build_menus():
cursor_option_group = []
def cursor_option(label: str, style: Literal[1, 2, 3, 4]) -> LCDRadioButton:
"""A radio button that sets the cursor style"""
def on_change(b, state):
if state:
screen.set_cursor_style(style)
b = LCDRadioButton(cursor_option_group, label, screen.cursor_style == style)
urwid.connect_signal(b, "change", on_change)
return b
def display_setting(label: str, data_range: int, fn: Callable[[int], None]) -> urwid.Columns:
slider = LCDHorizontalSlider(data_range, data_range / 2, fn)
return urwid.Columns(
[
urwid.Text(label),
(10, slider),
]
)
def led_custom(index: Literal[0, 1, 2, 3]) -> urwid.Columns:
def exp_scale_led(rg: Literal[0, 1]) -> Callable[[int], None]:
"""
apply an exponential transformation to values sent so
that apparent brightness increases in a natural way.
"""
return lambda value: screen.set_led_pin(
index,
rg,
[0, 1, 2, 3, 4, 5, 6, 8, 11, 14, 18, 23, 29, 38, 48, 61, 79, 100][value],
)
return urwid.Columns(
[
(2, urwid.Text(f"{index:d}R")),
LCDHorizontalSlider(18, 0, exp_scale_led(0)),
(2, urwid.Text(" G")),
LCDHorizontalSlider(18, 0, exp_scale_led(1)),
]
)
menu_structure = [
(
"Display Settings",
[
display_setting("Brightness", 101, screen.set_backlight),
display_setting("Contrast", 76, lambda x: screen.set_lcd_contrast(x + 75)),
],
),
(
"Cursor Settings",
[
cursor_option("Block", screen.CURSOR_BLINKING_BLOCK),
cursor_option("Underscore", screen.CURSOR_UNDERSCORE),
cursor_option("Block + Underscore", screen.CURSOR_BLINKING_BLOCK_UNDERSCORE),
cursor_option("Inverting Block", screen.CURSOR_INVERTING_BLINKING_BLOCK),
],
),
(
"LEDs",
[
led_custom(0),
led_custom(1),
led_custom(2),
led_custom(3),
],
),
(
"About this Demo",
[
urwid.Text(
"This is a demo of Urwid's CF635Display "
"module. If you need an interface for a limited "
"character display device this should serve as a "
"good example for implementing your own display "
"module and menu-driven application."
),
],
),
]
def build_submenu(ms):
"""
Recursive menu building from structure above
"""
options = []
submenus = []
for opt in ms:
# shortform for MenuOptions
if isinstance(opt, tuple):
name, sub = opt
submenu = build_submenu(sub)
opt = MenuOption(name, submenu) # noqa: PLW2901
submenus.append(submenu)
options.append(opt)
menu = Menu(options)
for s in submenus:
s.menu_parent = menu
return menu
return build_submenu(menu_structure)
screen = urwid.display.lcd.CF635Screen(sys.argv[1])
# set up our font
program_cgram(screen)
loop = urwid.MainLoop(build_menus(), screen=screen)
# FIXME: want screen to know it is in narrow mode, or better yet,
# do the unicode conversion for us
urwid.set_encoding("narrow")
def show_menu(menu):
loop.widget = menu
loop.run()
| 10,044 | Python | .py | 276 | 27.630435 | 102 | 0.557581 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,153 | subproc2.py | urwid_urwid/examples/subproc2.py | # this is part of the subproc.py example
from __future__ import annotations
import sys
num = int(sys.argv[1])
for c in range(1, 10000000):
if num % c == 0:
print("factor:", c)
| 192 | Python | .py | 7 | 24.142857 | 40 | 0.662983 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,154 | twisted_serve_ssh.py | urwid_urwid/examples/twisted_serve_ssh.py | """
Twisted integration for Urwid.
This module allows you to serve Urwid applications remotely over ssh.
The idea is that the server listens as an SSH server, and each connection is
routed by Twisted to urwid, and the urwid UI is routed back to the console.
The concept was a bit of a head-bender for me, but really we are just sending
escape codes and the what-not back to the console over the shell that ssh has
created. This is the same service as provided by the UI components in
twisted.conch.insults.window, except urwid has more features, and seems more
mature.
This module is not highly configurable, and the API is not great, so
don't worry about just using it as an example and copy-pasting.
Process
-------
TODO:
- better gpm tracking: there is no place for os.Popen in a Twisted app I
think.
Copyright: 2010, Ali Afshar <[email protected]>
License: MIT <https://www.opensource.org/licenses/mit-license.php>
Portions Copyright: 2010, Ian Ward <[email protected]>
Licence: LGPL <https://opensource.org/licenses/lgpl-2.1.php>
"""
from __future__ import annotations
import typing
from twisted.application.internet import TCPServer
from twisted.application.service import Application
from twisted.conch.insults.insults import ServerProtocol, TerminalProtocol
from twisted.conch.interfaces import IConchUser, ISession
from twisted.conch.manhole_ssh import (
ConchFactory,
TerminalRealm,
TerminalSession,
TerminalSessionTransport,
TerminalUser,
)
from twisted.cred.portal import Portal
from twisted.python.components import Adapter, Componentized
from zope.interface import Attribute, Interface, implementer
import urwid
from urwid.display.raw import Screen
if typing.TYPE_CHECKING:
from twisted.cred.checkers import ICredentialsChecker
class IUrwidUi(Interface):
"""Toplevel urwid widget"""
toplevel = Attribute("Urwid Toplevel Widget")
palette = Attribute("Urwid Palette")
screen = Attribute("Urwid Screen")
loop = Attribute("Urwid Main Loop")
def create_urwid_toplevel():
"""Create a toplevel widget."""
def create_urwid_mainloop():
"""Create the urwid main loop."""
class IUrwidMind(Interface):
ui = Attribute("")
terminalProtocol = Attribute("")
terminal = Attribute("")
checkers = Attribute("")
avatar = Attribute("The avatar")
def push(data):
"""Push data"""
def draw():
"""Refresh the UI"""
class UrwidUi:
def __init__(self, urwid_mind):
self.mind = urwid_mind
self.toplevel = self.create_urwid_toplevel()
self.palette = self.create_urwid_palette()
self.screen = TwistedScreen(self.mind.terminalProtocol)
self.loop = self.create_urwid_mainloop()
def create_urwid_toplevel(self):
raise NotImplementedError
def create_urwid_palette(self):
return
def create_urwid_mainloop(self):
evl = urwid.TwistedEventLoop(manage_reactor=False)
loop = urwid.MainLoop(
self.toplevel,
screen=self.screen,
event_loop=evl,
unhandled_input=self.mind.unhandled_key,
palette=self.palette,
)
self.screen.loop = loop
loop.run()
return loop
class UnhandledKeyHandler:
def __init__(self, mind):
self.mind = mind
def push(self, key):
if isinstance(key, tuple):
return None
f = getattr(self, f"key_{key.replace(' ', '_')}", None)
if f is None:
return None
return f(key)
def key_ctrl_c(self, key):
self.mind.terminal.loseConnection()
@implementer(IUrwidMind)
class UrwidMind(Adapter):
cred_checkers: typing.ClassVar[list[ICredentialsChecker]] = []
ui = None
ui_factory = None
unhandled_key_factory = UnhandledKeyHandler
@property
def avatar(self):
return IConchUser(self.original)
def set_terminalProtocol(self, terminalProtocol):
self.terminalProtocol = terminalProtocol
self.terminal = terminalProtocol.terminal
self.unhandled_key_handler = self.unhandled_key_factory(self)
self.unhandled_key = self.unhandled_key_handler.push
self.ui = self.ui_factory(self)
def push(self, data):
self.ui.screen.push(data)
def draw(self):
self.ui.loop.draw_screen()
class TwistedScreen(Screen):
"""A Urwid screen which knows about the Twisted terminal protocol that is
driving it.
A Urwid screen is responsible for:
1. Input
2. Output
Input is achieved in normal urwid by passing a list of available readable
file descriptors to the event loop for polling/selecting etc. In the
Twisted situation, this is not necessary because Twisted polls the input
descriptors itself. Urwid allows this by being driven using the main loop
instance's `process_input` method which is triggered on Twisted protocol's
standard `dataReceived` method.
"""
def __init__(self, terminalProtocol):
# We will need these later
self.terminalProtocol = terminalProtocol
self.terminal = terminalProtocol.terminal
super().__init__()
self.colors = 16
self._pal_escape = {}
self.bright_is_bold = True
self.register_palette_entry(None, "black", "white")
urwid.signals.connect_signal(self, urwid.UPDATE_PALETTE_ENTRY, self._on_update_palette_entry)
# Don't need to wait for anything to start
self._started = True
# Urwid Screen API
def get_cols_rows(self) -> tuple[int, int]:
"""Get the size of the terminal as (cols, rows)"""
return self.terminalProtocol.width, self.terminalProtocol.height
def draw_screen(self, size: tuple[int, int], canvas: urwid.Canvas) -> None:
"""Render a canvas to the terminal.
The canvas contains all the information required to render the Urwid
UI. The content method returns a list of rows as (attr, cs, text)
tuples. This very simple implementation iterates each row and simply
writes it out.
"""
(_maxcol, _maxrow) = size
# self.terminal.eraseDisplay()
lasta = None
for i, row in enumerate(canvas.content()):
self.terminal.cursorPosition(0, i)
for attr, _cs, text in row:
if attr != lasta:
text = f"{self._attr_to_escape(attr)}{text}" # noqa: PLW2901
lasta = attr
# if cs or attr:
# print(cs, attr)
self.write(text)
cursor = canvas.get_cursor()
if cursor is not None:
self.terminal.cursorPosition(*cursor)
# XXX from base screen
def set_mouse_tracking(self, enable=True):
"""
Enable (or disable) mouse tracking.
After calling this function get_input will include mouse
click events along with keystrokes.
"""
if enable:
self.write(urwid.escape.MOUSE_TRACKING_ON)
else:
self.write(urwid.escape.MOUSE_TRACKING_OFF)
# twisted handles polling, so we don't need the loop to do it, we just
# push what we get to the loop from dataReceived.
def hook_event_loop(self, event_loop, callback):
self._urwid_callback = callback
self._evl = event_loop
def unhook_event_loop(self, event_loop):
pass
# Do nothing here either. Not entirely sure when it gets called.
def get_input(self, raw_keys=False):
return
def get_available_raw_input(self):
data = self._data
self._data = []
return data
# Twisted driven
def push(self, data):
"""Receive data from Twisted and push it into the urwid main loop.
We must here:
1. filter the input data against urwid's input filter.
2. Calculate escapes and other clever things using urwid's
`escape.process_keyqueue`.
3. Pass the calculated keys as a list to the Urwid main loop.
4. Redraw the screen
"""
self._data = list(map(ord, data))
self.parse_input(self._evl, self._urwid_callback)
self.loop.draw_screen()
# Convenience
def write(self, data):
self.terminal.write(data)
# Private
def _on_update_palette_entry(self, name, *attrspecs):
# copy the attribute to a dictionary containing the escape sequences
self._pal_escape[name] = self._attrspec_to_escape(attrspecs[{16: 0, 1: 1, 88: 2, 256: 3}[self.colors]])
def _attr_to_escape(self, a):
if a in self._pal_escape:
return self._pal_escape[a]
if isinstance(a, urwid.AttrSpec):
return self._attrspec_to_escape(a)
# undefined attributes use default/default
# TODO: track and report these
return self._attrspec_to_escape(urwid.AttrSpec("default", "default"))
def _attrspec_to_escape(self, a):
"""
Convert AttrSpec instance a to an escape sequence for the terminal
>>> s = Screen()
>>> s.set_terminal_properties(colors=256)
>>> a2e = s._attrspec_to_escape
>>> a2e(s.AttrSpec('brown', 'dark green'))
'\\x1b[0;33;42m'
>>> a2e(s.AttrSpec('#fea,underline', '#d0d'))
'\\x1b[0;38;5;229;4;48;5;164m'
"""
if a.foreground_high:
fg = f"38;5;{a.foreground_number:d}"
elif a.foreground_basic:
if a.foreground_number > 7:
if self.bright_is_bold:
fg = f"1;{a.foreground_number - 8 + 30:d}"
else:
fg = f"{a.foreground_number - 8 + 90:d}"
else:
fg = f"{a.foreground_number + 30:d}"
else:
fg = "39"
st = "1;" * a.bold + "4;" * a.underline + "7;" * a.standout
if a.background_high:
bg = f"48;5;{a.background_number:d}"
elif a.background_basic:
if a.background_number > 7:
# this doesn't work on most terminals
bg = f"{a.background_number - 8 + 100:d}"
else:
bg = f"{a.background_number + 40:d}"
else:
bg = "49"
return f"{urwid.escape.ESC}[0;{fg};{st}{bg}m"
class UrwidTerminalProtocol(TerminalProtocol):
"""A terminal protocol that knows to proxy input and receive output from
Urwid.
This integrates with the TwistedScreen in a 1:1.
"""
def __init__(self, urwid_mind):
self.urwid_mind = urwid_mind
self.width = 80
self.height = 24
def connectionMade(self):
self.urwid_mind.set_terminalProtocol(self)
self.terminalSize(self.height, self.width)
def terminalSize(self, height, width):
"""Resize the terminal."""
self.width = width
self.height = height
self.urwid_mind.ui.loop.screen_size = None
self.terminal.eraseDisplay()
self.urwid_mind.draw()
def dataReceived(self, data):
"""Received data from the connection.
This overrides the default implementation which parses and passes to
the keyReceived method. We don't do that here, and must not do that so
that Urwid can get the right juice (which includes things like mouse
tracking).
Instead we just pass the data to the screen instance's dataReceived,
which handles the proxying to Urwid.
"""
self.urwid_mind.push(data)
def _unhandled_input(self, data):
# evil
proceed = True
if hasattr(self.urwid_toplevel, "app"):
proceed = self.urwid_toplevel.app.unhandled_input(self, data)
if not proceed:
return
if data == "ctrl c":
self.terminal.loseConnection()
class UrwidServerProtocol(ServerProtocol):
def dataReceived(self, data):
self.terminalProtocol.dataReceived(data)
class UrwidUser(TerminalUser):
"""A terminal user that remembers its avatarId
The default implementation doesn't
"""
def __init__(self, original, avatarId):
super().__init__(original, avatarId)
self.avatarId = avatarId
class UrwidTerminalSession(TerminalSession):
"""A terminal session that remembers the avatar and chained protocol for
later use. And implements a missing method for changed Window size.
Note: This implementation assumes that each SSH connection will only
request a single shell, which is not an entirely safe assumption, but is
by far the most common case.
"""
def openShell(self, proto):
"""Open a shell."""
self.chained_protocol = UrwidServerProtocol(UrwidTerminalProtocol, IUrwidMind(self.original))
TerminalSessionTransport(proto, self.chained_protocol, IConchUser(self.original), self.height, self.width)
def windowChanged(self, dimensions):
"""Called when the window size has changed."""
(h, w, _x, _y) = dimensions
self.chained_protocol.terminalProtocol.terminalSize(h, w)
class UrwidRealm(TerminalRealm):
"""Custom terminal realm class-configured to use our custom Terminal User
Terminal Session.
"""
def __init__(self, mind_factory):
super().__init__()
self.mind_factory = mind_factory
def _getAvatar(self, avatarId):
comp = Componentized()
user = UrwidUser(comp, avatarId)
comp.setComponent(IConchUser, user)
sess = UrwidTerminalSession(comp)
comp.setComponent(ISession, sess)
mind = self.mind_factory(comp)
comp.setComponent(IUrwidMind, mind)
return user
def requestAvatar(self, avatarId, mind, *interfaces):
for i in interfaces:
if i is IConchUser:
return (IConchUser, self._getAvatar(avatarId), lambda: None)
raise NotImplementedError()
def create_server_factory(urwid_mind_factory):
"""Convenience to create a server factory with a portal that uses a realm
serving a given urwid widget against checkers provided.
"""
rlm = UrwidRealm(urwid_mind_factory)
ptl = Portal(rlm, urwid_mind_factory.cred_checkers)
return ConchFactory(ptl)
def create_service(urwid_mind_factory, port, *args, **kw):
"""Convenience to create a service for use in tac-ish situations."""
f = create_server_factory(urwid_mind_factory)
return TCPServer(port, f, *args, **kw)
def create_application(application_name, urwid_mind_factory, port, *args, **kw):
"""Convenience to create an application suitable for tac file"""
application = Application(application_name)
svc = create_service(urwid_mind_factory, 6022)
svc.setServiceParent(application)
return application
| 14,732 | Python | .py | 356 | 33.83427 | 114 | 0.660831 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,155 | conf.py | urwid_urwid/docs/conf.py | #
# Urwid documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 30 20:10:17 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from __future__ import annotations
import ast
import os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinx.ext.githubpages",
"sphinx_github_changelog",
]
sphinx_github_changelog_token = os.environ.get("SPHINX_GITHUB_CHANGELOG_TOKEN")
# Add any paths that contain templates here, relative to this directory.
templates_path = ["tools/templates"]
# The suffix of source filenames.
source_suffix = ".rst"
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = "index"
# General information about the project.
project = "Urwid"
copyright = "2014, Ian Ward et al" # noqa: A001 # sphinx magic
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
FILE_PATH = os.path.dirname(__file__)
VERSION_MODULE = os.path.abspath(os.path.join(FILE_PATH, "../urwid/version.py"))
VERSION_VARS = {}
with open(VERSION_MODULE, encoding="utf-8") as f:
parsed = ast.parse(f.read())
for node in parsed.body:
if not isinstance(node, (ast.Assign, ast.AnnAssign)):
# Not variable define
continue
if node.value is None:
# Not a proper assign
continue
try:
value = ast.literal_eval(node.value)
except ValueError:
continue
if isinstance(node, ast.Assign):
VERSION_VARS.update(
{tgt.id: value for tgt in node.targets if isinstance(tgt, ast.Name) and isinstance(tgt.ctx, ast.Store)}
)
else:
VERSION_VARS[node.target.id] = value
# The short X.Y version.
version = ".".join(str(x) for x in VERSION_VARS["__version_tuple__"][:2])
# The full version, including alpha/beta/rc tags.
release = VERSION_VARS["__version__"]
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# Generate CNAME
html_baseurl = "https://urwid.org"
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "default"
html_style = None # make readthedocs really use the default theme
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
html_theme_options = {
"sidebarbgcolor": "#263193",
"sidebarbtncolor": "#263193",
"footerbgcolor": "#181035",
"relbarbgcolor": "#181035",
"sidebarlinkcolor": "#aabee8",
"linkcolor": "#263193",
"visitedlinkcolor": "#263193",
"headtextcolor": "#181035",
"headlinkcolor": "#181035",
"collapsiblesidebar": False,
}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = f"Urwid {release}"
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "urwid-logo.png"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["tools/static"]
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {"index": ["indexsidebar.html"]}
# Additional templates that should be rendered to pages, maps page names to
# template names.
html_additional_pages = {
"index": "indexcontent.html",
}
# If false, no module index is generated.
html_domain_indices = False
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = "Urwiddoc"
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
("index", "Urwid.tex", "Urwid Documentation", "Ian Ward", "manual"),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [("index", "urwid", "Urwid Documentation", ["Ian Ward"], 1)]
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
("index", "Urwid", "Urwid Documentation", "Ian Ward", "Urwid", "One line description of project.", "Miscellaneous"),
]
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = "Urwid"
epub_author = "Ian Ward"
epub_publisher = "Ian Ward"
epub_copyright = "2014, Ian Ward et al"
# The language of the text. It defaults to the language option
# or en if the language is not set.
# epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
# epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
# epub_identifier = ''
# A unique identification for the text.
# epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
# epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
# epub_post_files = []
# A list of files that should not be packed into the epub file.
# epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
# epub_tocdepth = 3
# Allow duplicate toc entries.
# epub_tocdup = True
autoclass_content = "both"
autodoc_member_order = "alphabetical"
autodoc_default_options = {"members": True}
| 10,805 | Python | .py | 249 | 40.927711 | 120 | 0.708035 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,156 | wmod.py | urwid_urwid/docs/manual/wmod.py | from __future__ import annotations
import urwid
class QuestionnaireItem(urwid.WidgetWrap[urwid.GridFlow]):
def __init__(self) -> None:
self.options: list[urwid.RadioButton] = []
unsure = urwid.RadioButton(self.options, "Unsure")
yes = urwid.RadioButton(self.options, "Yes")
no = urwid.RadioButton(self.options, "No")
display_widget = urwid.GridFlow([unsure, yes, no], 15, 3, 1, "left")
super().__init__(display_widget)
def get_state(self) -> str:
return next(o.label for o in self.options if o.state is True)
| 577 | Python | .py | 12 | 41.416667 | 76 | 0.657754 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,157 | wcur1.py | urwid_urwid/docs/manual/wcur1.py | from __future__ import annotations
import urwid
class CursorPudding(urwid.Widget):
_sizing = frozenset(["flow"])
_selectable = True
def __init__(self):
super().__init__()
self.cursor_col = 0
def rows(self, size: tuple[int], focus: bool = False) -> int:
return 1
def render(self, size: tuple[int], focus: bool = False) -> urwid.TextCanvas:
(maxcol,) = size
num_pudding = maxcol // len("Pudding")
cursor = None
if focus:
cursor = self.get_cursor_coords(size)
return urwid.TextCanvas([b"Pudding" * num_pudding], [], cursor=cursor, maxcol=maxcol)
def get_cursor_coords(self, size: tuple[int]) -> tuple[int, int]:
(maxcol,) = size
col = min(self.cursor_col, maxcol - 1)
return col, 0
def keypress(self, size: tuple[int], key: str) -> str | None:
(maxcol,) = size
if key == "left":
col = self.cursor_col - 1
elif key == "right":
col = self.cursor_col + 1
else:
return key
self.cursor_x = max(0, min(maxcol - 1, col))
self._invalidate()
return None
| 1,170 | Python | .py | 32 | 28.4375 | 93 | 0.567257 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,158 | wanat_multi.py | urwid_urwid/docs/manual/wanat_multi.py | from __future__ import annotations
import urwid
class MultiPudding(urwid.Widget):
_sizing = frozenset((urwid.FLOW, urwid.BOX))
def rows(self, size: tuple[int], focus: bool = False) -> int:
return 1
def render(self, size: tuple[int], focus: bool = False) -> urwid.TextCanvas:
if len(size) == 1:
(maxcol,) = size
maxrow = 1
else:
(maxcol, maxrow) = size
num_pudding = maxcol // len("Pudding")
return urwid.TextCanvas([b"Pudding" * num_pudding] * maxrow, maxcol=maxcol)
| 560 | Python | .py | 14 | 32.357143 | 83 | 0.608133 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,159 | wsel.py | urwid_urwid/docs/manual/wsel.py | from __future__ import annotations
import urwid
class SelectablePudding(urwid.Widget):
_sizing = frozenset((urwid.FLOW,))
_selectable = True
def __init__(self) -> None:
super().__init__()
self.pudding = "pudding"
def rows(self, size: tuple[int], focus: bool = False) -> int:
return 1
def render(self, size: tuple[int], focus: bool = False) -> urwid.TextCanvas:
(maxcol,) = size
num_pudding = maxcol // len(self.pudding)
pudding = self.pudding
if focus:
pudding = pudding.upper()
return urwid.TextCanvas([pudding.encode("utf-8") * num_pudding], maxcol=maxcol)
def keypress(self, size: tuple[int], key: str) -> str | None:
if len(key) > 1:
return key
if key.lower() in self.pudding:
# remove letter from pudding
n = self.pudding.index(key.lower())
self.pudding = self.pudding[:n] + self.pudding[n + 1 :]
if not self.pudding:
self.pudding = "pudding"
self._invalidate()
return None
return key
| 1,123 | Python | .py | 29 | 29.689655 | 87 | 0.578802 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,160 | bright_combinations.py | urwid_urwid/docs/manual/bright_combinations.py | #!/usr/bin/env python
from __future__ import annotations
import sys
import urwid
RED_FGS = (
"black",
"light gray",
"white",
"light cyan",
"light red",
"light green",
"yellow",
"light magenta",
)
GREEN_FGS = (
"black",
"light gray",
"dark blue",
"white",
"light cyan",
"light red",
"light green",
"yellow",
)
BROWN_FGS = (
"black",
"dark blue",
"dark gray",
"white",
"light blue",
"light cyan",
"light red",
"light green",
"yellow",
)
MAGENTA_FGS = (
"black",
"light gray",
"dark blue",
"white",
"light cyan",
"light red",
"light green",
"yellow",
"light magenta",
)
BG_FGS = [
("dark red", RED_FGS),
("dark green", GREEN_FGS),
("brown", BROWN_FGS),
("dark magenta", MAGENTA_FGS),
]
body = urwid.SimpleFocusListWalker([])
for bg, fgs in BG_FGS:
spec = urwid.AttrSpec(fgs[0], bg)
body.extend(
(
urwid.AttrMap(urwid.Divider(), spec),
urwid.AttrMap(
urwid.GridFlow(
(urwid.AttrMap(urwid.Text(f"'{fg}' on '{bg}'"), urwid.AttrSpec(fg, bg)) for fg in fgs),
35,
0,
0,
urwid.LEFT,
),
spec,
),
urwid.AttrMap(urwid.Divider(), spec),
)
)
try:
urwid.MainLoop(urwid.ListBox(body)).run()
except KeyboardInterrupt:
sys.exit(0)
| 1,505 | Python | .py | 75 | 13.826667 | 107 | 0.5095 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,161 | safe_combinations.py | urwid_urwid/docs/manual/safe_combinations.py | #!/usr/bin/env python
from __future__ import annotations
import sys
import urwid
BLACK_FGS = (
"light gray",
"dark cyan",
"dark red",
"dark green",
"dark magenta",
"white",
"light blue",
"light cyan",
"light red",
"light green",
"yellow",
"light magenta",
)
GRAY_FGS = (
"black",
"dark blue",
"dark cyan",
"dark red",
"dark green",
"dark magenta",
"white",
"light red",
"yellow",
"light magenta",
)
BLUE_FGS = (
"light gray",
"dark cyan",
"white",
"light cyan",
"light red",
"light green",
"yellow",
"light magenta",
)
CYAN_FGS = (
"black",
"light gray",
"dark blue",
"white",
"light cyan",
"light green",
"yellow",
)
BG_FGS = [
("black", BLACK_FGS),
("light gray", GRAY_FGS),
("dark blue", BLUE_FGS),
("dark cyan", CYAN_FGS),
]
body = urwid.SimpleFocusListWalker([])
for bg, fgs in BG_FGS:
spec = urwid.AttrSpec(fgs[0], bg)
body.extend(
(
urwid.AttrMap(urwid.Divider(), spec),
urwid.AttrMap(
urwid.GridFlow(
(urwid.AttrMap(urwid.Text(f"'{fg}' on '{bg}'"), urwid.AttrSpec(fg, bg)) for fg in fgs),
35,
0,
0,
urwid.LEFT,
),
spec,
),
urwid.AttrMap(urwid.Divider(), spec),
)
)
try:
urwid.MainLoop(urwid.ListBox(body)).run()
except KeyboardInterrupt:
sys.exit(0)
| 1,563 | Python | .py | 78 | 13.846154 | 107 | 0.510163 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,162 | wanat.py | urwid_urwid/docs/manual/wanat.py | from __future__ import annotations
import urwid
class Pudding(urwid.Widget):
_sizing = frozenset((urwid.FLOW,))
def rows(self, size: tuple[int], focus: bool = False) -> int:
return 1
def render(self, size: tuple[int], focus: bool = False) -> urwid.TextCanvas:
(maxcol,) = size
num_pudding = maxcol // len("Pudding")
return urwid.TextCanvas([b"Pudding" * num_pudding], maxcol=maxcol)
class BoxPudding(urwid.Widget):
_sizing = frozenset((urwid.BOX,))
def render(self, size: tuple[int, int], focus: bool = False) -> urwid.TextCanvas:
(maxcol, maxrow) = size
num_pudding = maxcol // len("Pudding")
return urwid.TextCanvas([b"Pudding" * num_pudding] * maxrow, maxcol=maxcol)
| 754 | Python | .py | 16 | 40.875 | 85 | 0.654795 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,163 | wcur2.py | urwid_urwid/docs/manual/wcur2.py | from __future__ import annotations
import urwid
class Widget(urwid.ListBox):
def get_pref_col(self, size: tuple[int, int]) -> int:
return self.cursor_x
def move_cursor_to_coords(self, size: tuple[int, int], col: int, row: int) -> bool:
assert row == 0 # noqa: S101 # in examples we can use `assert`
self.cursor_x = col
return True
| 377 | Python | .py | 9 | 36 | 87 | 0.645604 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,164 | edit.py | urwid_urwid/docs/examples/edit.py | #!/usr/bin/env python
from __future__ import annotations
import os
import sys
import real_edit
real_edit.EditDisplay(os.path.join(os.path.dirname(sys.argv[0]), "edit_text.txt")).main()
| 189 | Python | .py | 6 | 29.833333 | 89 | 0.77095 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,165 | browse.py | urwid_urwid/docs/examples/browse.py | #!/usr/bin/env python
from __future__ import annotations
import os
import real_browse
os.chdir("/usr/share/doc/python3")
real_browse.main()
| 144 | Python | .py | 6 | 22.333333 | 34 | 0.783582 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,166 | real_browse.py | urwid_urwid/docs/examples/real_browse.py | #!/usr/bin/env python
#
# Urwid example lazy directory browser / tree view
# Copyright (C) 2004-2011 Ian Ward
# Copyright (C) 2010 Kirk McDonald
# Copyright (C) 2010 Rob Lanphier
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example lazy directory browser / tree view
Features:
- custom selectable widgets for files and directories
- custom message widgets to identify access errors and empty directories
- custom list walker for displaying widgets in a tree fashion
- outputs a quoted list of files and directories "selected" on exit
"""
from __future__ import annotations
import itertools
import os
import re
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Hashable
class FlagFileWidget(urwid.TreeWidget):
# apply an attribute to the expand/unexpand icons
unexpanded_icon = urwid.AttrMap(urwid.TreeWidget.unexpanded_icon, "dirmark")
expanded_icon = urwid.AttrMap(urwid.TreeWidget.expanded_icon, "dirmark")
def __init__(self, node: urwid.TreeNode) -> None:
super().__init__(node)
# insert an extra AttrWrap for our own use
self._w = urwid.AttrMap(self._w, None)
self.flagged = False
self.update_w()
def selectable(self) -> bool:
return True
def keypress(self, size, key: str) -> str | None:
"""allow subclasses to intercept keystrokes"""
key = super().keypress(size, key)
if key:
key = self.unhandled_keys(size, key)
return key
def unhandled_keys(self, size, key: str) -> str | None:
"""
Override this method to intercept keystrokes in subclasses.
Default behavior: Toggle flagged on space, ignore other keys.
"""
if key == " ":
self.flagged = not self.flagged
self.update_w()
return None
return key
def update_w(self) -> None:
"""Update the attributes of self.widget based on self.flagged."""
if self.flagged:
self._w.attr_map = {None: "flagged"}
self._w.focus_map = {None: "flagged focus"}
else:
self._w.attr_map = {None: "body"}
self._w.focus_map = {None: "focus"}
class FileTreeWidget(FlagFileWidget):
"""Widget for individual files."""
def __init__(self, node: FileNode) -> None:
super().__init__(node)
path = node.get_value()
add_widget(path, self)
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
return self.get_node().get_key()
class EmptyWidget(urwid.TreeWidget):
"""A marker for expanded directories with no contents."""
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
return ("flag", "(empty directory)")
class ErrorWidget(urwid.TreeWidget):
"""A marker for errors reading directories."""
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
return ("error", "(error/permission denied)")
class DirectoryWidget(FlagFileWidget):
"""Widget for a directory."""
def __init__(self, node: DirectoryNode) -> None:
super().__init__(node)
path = node.get_value()
add_widget(path, self)
self.expanded = starts_expanded(path)
self.update_expanded_icon()
def get_display_text(self) -> str | tuple[Hashable, str] | list[str | tuple[Hashable, str]]:
node = self.get_node()
if node.get_depth() == 0:
return "/"
return node.get_key()
class FileNode(urwid.TreeNode):
"""Metadata storage for individual files"""
def __init__(self, path: str, parent: urwid.ParentNode | None = None) -> None:
depth = path.count(dir_sep())
key = os.path.basename(path)
super().__init__(path, key=key, parent=parent, depth=depth)
def load_parent(self) -> DirectoryNode:
parentname, _myname = os.path.split(self.get_value())
parent = DirectoryNode(parentname)
parent.set_child_node(self.get_key(), self)
return parent
def load_widget(self) -> FileTreeWidget:
return FileTreeWidget(self)
class EmptyNode(urwid.TreeNode):
def load_widget(self) -> EmptyWidget:
return EmptyWidget(self)
class ErrorNode(urwid.TreeNode):
def load_widget(self) -> ErrorWidget:
return ErrorWidget(self)
class DirectoryNode(urwid.ParentNode):
"""Metadata storage for directories"""
def __init__(self, path: str, parent: urwid.ParentNode | None = None) -> None:
if path == dir_sep():
depth = 0
key = None
else:
depth = path.count(dir_sep())
key = os.path.basename(path)
super().__init__(path, key=key, parent=parent, depth=depth)
def load_parent(self) -> DirectoryNode:
parentname, _myname = os.path.split(self.get_value())
parent = DirectoryNode(parentname)
parent.set_child_node(self.get_key(), self)
return parent
def load_child_keys(self):
dirs = []
files = []
try:
path = self.get_value()
# separate dirs and files
for a in os.listdir(path):
if os.path.isdir(os.path.join(path, a)):
dirs.append(a)
else:
files.append(a)
except OSError:
depth = self.get_depth() + 1
self._children[None] = ErrorNode(self, parent=self, key=None, depth=depth)
return [None]
# sort dirs and files
dirs.sort(key=alphabetize)
files.sort(key=alphabetize)
# store where the first file starts
self.dir_count = len(dirs)
# collect dirs and files together again
keys = dirs + files
if len(keys) == 0:
depth = self.get_depth() + 1
self._children[None] = EmptyNode(self, parent=self, key=None, depth=depth)
keys = [None]
return keys
def load_child_node(self, key) -> EmptyNode | DirectoryNode | FileNode:
"""Return either a FileNode or DirectoryNode"""
index = self.get_child_index(key)
if key is None:
return EmptyNode(None)
path = os.path.join(self.get_value(), key)
if index < self.dir_count:
return DirectoryNode(path, parent=self)
path = os.path.join(self.get_value(), key)
return FileNode(path, parent=self)
def load_widget(self) -> DirectoryWidget:
return DirectoryWidget(self)
class DirectoryBrowser:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "black", "light gray"),
("flagged", "black", "dark green", ("bold", "underline")),
("focus", "light gray", "dark blue", "standout"),
("flagged focus", "yellow", "dark cyan", ("bold", "standout", "underline")),
("head", "yellow", "black", "standout"),
("foot", "light gray", "black"),
("key", "light cyan", "black", "underline"),
("title", "white", "black", "bold"),
("dirmark", "black", "dark cyan", "bold"),
("flag", "dark gray", "light gray"),
("error", "dark red", "light gray"),
]
footer_text: typing.ClassVar[list[tuple[str, str] | str]] = [
("title", "Directory Browser"),
" ",
("key", "UP"),
",",
("key", "DOWN"),
",",
("key", "PAGE UP"),
",",
("key", "PAGE DOWN"),
" ",
("key", "SPACE"),
" ",
("key", "+"),
",",
("key", "-"),
" ",
("key", "LEFT"),
" ",
("key", "HOME"),
" ",
("key", "END"),
" ",
("key", "Q"),
]
def __init__(self) -> None:
cwd = os.getcwd()
store_initial_cwd(cwd)
self.header = urwid.Text("")
self.listbox = urwid.TreeListBox(urwid.TreeWalker(DirectoryNode(cwd)))
self.listbox.offset_rows = 1
self.footer = urwid.AttrMap(urwid.Text(self.footer_text), "foot")
self.view = urwid.Frame(
urwid.AttrMap(
urwid.ScrollBar(
self.listbox,
thumb_char=urwid.ScrollBar.Symbols.FULL_BLOCK,
trough_char=urwid.ScrollBar.Symbols.LITE_SHADE,
),
"body",
),
header=urwid.AttrMap(self.header, "head"),
footer=self.footer,
)
def main(self) -> None:
"""Run the program."""
self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input)
self.loop.run()
# on exit, write the flagged filenames to the console
names = [escape_filename_sh(x) for x in get_flagged_names()]
print(" ".join(names))
def unhandled_input(self, k: str | tuple[str, int, int, int]) -> None:
# update display of focus directory
if k in {"q", "Q"}:
raise urwid.ExitMainLoop()
def main():
DirectoryBrowser().main()
#######
# global cache of widgets
_widget_cache = {}
def add_widget(path, widget):
"""Add the widget for a given path"""
_widget_cache[path] = widget
def get_flagged_names() -> list[str]:
"""Return a list of all filenames marked as flagged."""
names = [w.get_node().get_value() for w in _widget_cache.values() if w.flagged]
return names
######
# store path components of initial current working directory
_initial_cwd = []
def store_initial_cwd(name: str) -> None:
"""Store the initial current working directory path components."""
_initial_cwd.clear()
_initial_cwd.extend(name.split(dir_sep()))
def starts_expanded(name: str) -> bool:
"""Return True if directory is a parent of initial cwd."""
if name == "/":
return True
path_elements = name.split(dir_sep())
if len(path_elements) > len(_initial_cwd):
return False
return path_elements == _initial_cwd[: len(path_elements)]
def escape_filename_sh(name: str) -> str:
"""Return a hopefully safe shell-escaped version of a filename."""
# check whether we have unprintable characters
for ch in name:
if ord(ch) < 32:
# found one so use the ansi-c escaping
return escape_filename_sh_ansic(name)
# all printable characters, so return a double-quoted version
name = name.replace("\\", "\\\\").replace('"', '\\"').replace("`", "\\`").replace("$", "\\$")
return f'"{name}"'
def escape_filename_sh_ansic(name: str) -> str:
"""Return an ansi-c shell-escaped version of a filename."""
out = []
# gather the escaped characters into a list
for ch in name:
if ord(ch) < 32:
out.append(f"\\x{ord(ch):02x}")
elif ch == "\\":
out.append("\\\\")
else:
out.append(ch)
# slap them back together in an ansi-c quote $'...'
return f"$'{''.join(out)}'"
SPLIT_RE = re.compile(r"[a-zA-Z]+|\d+")
def alphabetize(s: str) -> list[str]:
L = []
for isdigit, group in itertools.groupby(SPLIT_RE.findall(s), key=str.isdigit):
if isdigit:
L.extend(("", int(n)) for n in group)
else:
L.append(("".join(group).lower(), 0))
return L
def dir_sep() -> str:
"""Return the separator used in this os."""
return getattr(os.path, "sep", "/")
if __name__ == "__main__":
main()
| 12,258 | Python | .py | 309 | 32.142395 | 97 | 0.60113 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,167 | browse.py.xdotool | urwid_urwid/docs/examples/browse.py.xdotool | windowsize --usehints $RXVTWINDOWID 79 19
key --window $RXVTWINDOWID Down plus Down space Down space Down Down Down
| 116 | Python | .py | 2 | 57 | 73 | 0.815789 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,168 | real_edit.py | urwid_urwid/docs/examples/real_edit.py | #!/usr/bin/env python
#
# Urwid example lazy text editor suitable for tabbed and format=flowed text
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example lazy text editor suitable for tabbed and flowing text
Features:
- custom list walker for lazily loading text file
Usage:
edit.py <filename>
"""
from __future__ import annotations
import sys
import typing
import urwid
class LineWalker(urwid.ListWalker):
"""ListWalker-compatible class for lazily reading file contents."""
def __init__(self, name: str) -> None:
# do not overcomplicate example
self.file = open(name, encoding="utf-8") # noqa: SIM115 # pylint: disable=consider-using-with
self.lines = []
self.focus = 0
def __del__(self) -> None:
self.file.close()
def get_focus(self):
return self._get_at_pos(self.focus)
def set_focus(self, focus) -> None:
self.focus = focus
self._modified()
def get_next(self, position: int) -> tuple[urwid.Edit, int] | tuple[None, None]:
return self._get_at_pos(position + 1)
def get_prev(self, position: int) -> tuple[urwid.Edit, int] | tuple[None, None]:
return self._get_at_pos(position - 1)
def read_next_line(self) -> str:
"""Read another line from the file."""
next_line = self.file.readline()
if not next_line or next_line[-1:] != "\n":
# no newline on last line of file
self.file = None
else:
# trim newline characters
next_line = next_line[:-1]
expanded = next_line.expandtabs()
edit = urwid.Edit("", expanded, allow_tab=True)
edit.edit_pos = 0
edit.original_text = next_line
self.lines.append(edit)
return next_line
def _get_at_pos(self, pos: int) -> tuple[urwid.Edit, int] | tuple[None, None]:
"""Return a widget for the line number passed."""
if pos < 0:
# line 0 is the start of the file, no more above
return None, None
if len(self.lines) > pos:
# we have that line so return it
return self.lines[pos], pos
if self.file is None:
# file is closed, so there are no more lines
return None, None
assert pos == len(self.lines), "out of order request?" # noqa: S101 # "assert" is ok in examples
self.read_next_line()
return self.lines[-1], pos
def split_focus(self) -> None:
"""Divide the focus edit widget at the cursor location."""
focus = self.lines[self.focus]
pos = focus.edit_pos
edit = urwid.Edit("", focus.edit_text[pos:], allow_tab=True)
edit.original_text = ""
focus.set_edit_text(focus.edit_text[:pos])
edit.edit_pos = 0
self.lines.insert(self.focus + 1, edit)
def combine_focus_with_prev(self) -> None:
"""Combine the focus edit widget with the one above."""
above, _ = self.get_prev(self.focus)
if above is None:
# already at the top
return
focus = self.lines[self.focus]
above.set_edit_pos(len(above.edit_text))
above.set_edit_text(above.edit_text + focus.edit_text)
del self.lines[self.focus]
self.focus -= 1
def combine_focus_with_next(self) -> None:
"""Combine the focus edit widget with the one below."""
below, _ = self.get_next(self.focus)
if below is None:
# already at bottom
return
focus = self.lines[self.focus]
focus.set_edit_text(focus.edit_text + below.edit_text)
del self.lines[self.focus + 1]
class EditDisplay:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "default", "default"),
("foot", "dark cyan", "dark blue", "bold"),
("key", "light cyan", "dark blue", "underline"),
]
footer_text = (
"foot",
[
"Text Editor ",
("key", "F5"),
" save ",
("key", "F8"),
" quit",
],
)
def __init__(self, name: str) -> None:
self.save_name = name
self.walker = LineWalker(name)
self.listbox = urwid.ListBox(self.walker)
self.footer = urwid.AttrMap(urwid.Text(self.footer_text), "foot")
self.view = urwid.Frame(urwid.AttrMap(self.listbox, "body"), footer=self.footer)
def main(self) -> None:
self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_keypress)
self.loop.run()
def unhandled_keypress(self, k: str | tuple[str, int, int, int]) -> bool | None:
"""Last resort for keypresses."""
if k == "f5":
self.save_file()
elif k == "f8":
raise urwid.ExitMainLoop()
elif k == "delete":
# delete at end of line
self.walker.combine_focus_with_next()
elif k == "backspace":
# backspace at beginning of line
self.walker.combine_focus_with_prev()
elif k == "enter":
# start new line
self.walker.split_focus()
# move the cursor to the new line and reset pref_col
self.loop.process_input(["down", "home"])
elif k == "right":
w, pos = self.walker.get_focus()
w, pos = self.walker.get_next(pos)
if w:
self.listbox.set_focus(pos, "above")
self.loop.process_input(["home"])
elif k == "left":
w, pos = self.walker.get_focus()
w, pos = self.walker.get_prev(pos)
if w:
self.listbox.set_focus(pos, "below")
self.loop.process_input(["end"])
else:
return None
return True
def save_file(self) -> None:
"""Write the file out to disk."""
lines = []
walk = self.walker
for edit in walk.lines:
# collect the text already stored in edit widgets
if edit.original_text.expandtabs() == edit.edit_text:
lines.append(edit.original_text)
else:
lines.append(re_tab(edit.edit_text))
# then the rest
while walk.file is not None:
lines.append(walk.read_next_line())
# write back to disk
with open(self.save_name, "w", encoding="utf-8") as outfile:
prefix = ""
for line in lines:
outfile.write(prefix + line)
prefix = "\n"
def re_tab(s) -> str:
"""Return a tabbed string from an expanded one."""
line = []
p = 0
for i in range(8, len(s), 8):
if s[i - 2 : i] == " ":
# collapse two or more spaces into a tab
line.append(f"{s[p:i].rstrip()}\t")
p = i
if p == 0:
return s
line.append(s[p:])
return "".join(line)
def main() -> None:
try:
name = sys.argv[1]
# do not overcomplicate example
assert open(name, "ab") # noqa: SIM115,S101 # pylint: disable=consider-using-with
except OSError:
sys.stderr.write(__doc__)
return
EditDisplay(name).main()
if __name__ == "__main__":
main()
| 8,054 | Python | .py | 207 | 30.454106 | 106 | 0.584189 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,169 | bigtext.py | urwid_urwid/docs/examples/bigtext.py | #!/usr/bin/env python
#
# Urwid BigText example program
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example demonstrating use of the BigText widget.
"""
from __future__ import annotations
import typing
import urwid
import urwid.display.raw
if typing.TYPE_CHECKING:
from collections.abc import Callable
_Wrapped = typing.TypeVar("_Wrapped")
class SwitchingPadding(urwid.Padding[_Wrapped]):
def padding_values(self, size, focus: bool) -> tuple[int, int]:
maxcol = size[0]
width, _height = self.original_widget.pack(size, focus=focus)
if maxcol > width:
self.align = urwid.LEFT
else:
self.align = urwid.RIGHT
return super().padding_values(size, focus)
class BigTextDisplay:
palette: typing.ClassVar[list[tuple[str, str, str, ...]]] = [
("body", "black", "light gray", "standout"),
("header", "white", "dark red", "bold"),
("button normal", "light gray", "dark blue", "standout"),
("button select", "white", "dark green"),
("button disabled", "dark gray", "dark blue"),
("edit", "light gray", "dark blue"),
("bigtext", "white", "black"),
("chars", "light gray", "black"),
("exit", "white", "dark cyan"),
]
def create_radio_button(
self,
g: list[urwid.RadioButton],
name: str,
font: urwid.Font,
fn: Callable[[urwid.RadioButton, bool], typing.Any],
) -> urwid.AttrMap:
w = urwid.RadioButton(g, name, False, on_state_change=fn)
w.font = font
w = urwid.AttrMap(w, "button normal", "button select")
return w
def create_disabled_radio_button(self, name: str) -> urwid.AttrMap:
w = urwid.Text(f" {name} (UTF-8 mode required)")
w = urwid.AttrMap(w, "button disabled")
return w
def create_edit(
self,
label: str,
text: str,
fn: Callable[[urwid.Edit, str], typing.Any],
) -> urwid.AttrMap:
w = urwid.Edit(label, text)
urwid.connect_signal(w, "change", fn)
fn(w, text)
w = urwid.AttrMap(w, "edit")
return w
def set_font_event(self, w, state: bool) -> None:
if state:
self.bigtext.set_font(w.font)
self.chars_avail.set_text(w.font.characters())
def edit_change_event(self, widget, text: str) -> None:
self.bigtext.set_text(text)
def setup_view(self) -> tuple[
urwid.Frame[urwid.AttrMap[urwid.ListBox], urwid.AttrMap[urwid.Text], None],
urwid.Overlay[urwid.BigText, urwid.Frame[urwid.AttrMap[urwid.ListBox], urwid.AttrMap[urwid.Text], None]],
]:
fonts = urwid.get_all_fonts()
# setup mode radio buttons
self.font_buttons = []
group = []
utf8 = urwid.get_encoding_mode() == "utf8"
for name, fontcls in fonts:
font = fontcls()
if font.utf8_required and not utf8:
rb = self.create_disabled_radio_button(name)
else:
rb = self.create_radio_button(group, name, font, self.set_font_event)
if fontcls == urwid.Thin6x6Font:
chosen_font_rb = rb
exit_font = font
self.font_buttons.append(rb)
# Create BigText
self.bigtext = urwid.BigText("", None)
bt = urwid.BoxAdapter(
urwid.Filler(
urwid.AttrMap(
SwitchingPadding(self.bigtext, urwid.LEFT, None),
"bigtext",
),
urwid.BOTTOM,
None,
7,
),
7,
)
# Create chars_avail
cah = urwid.Text("Characters Available:")
self.chars_avail = urwid.Text("", wrap=urwid.ANY)
ca = urwid.AttrMap(self.chars_avail, "chars")
chosen_font_rb.original_widget.set_state(True) # causes set_font_event call
# Create Edit widget
edit = self.create_edit("", "Urwid BigText example", self.edit_change_event)
# ListBox
chars = urwid.Pile([cah, ca])
fonts = urwid.Pile([urwid.Text("Fonts:"), *self.font_buttons], focus_item=1)
col = urwid.Columns([(16, chars), fonts], 3, focus_column=1)
bt = urwid.Pile([bt, edit], focus_item=1)
lines = [bt, urwid.Divider(), col]
listbox = urwid.ListBox(urwid.SimpleListWalker(lines))
# Frame
w = urwid.Frame(
body=urwid.AttrMap(listbox, "body"),
header=urwid.AttrMap(urwid.Text("Urwid BigText example program - F8 exits."), "header"),
)
# Exit message
exit_w = urwid.Overlay(
urwid.BigText(("exit", " Quit? "), exit_font),
w,
urwid.CENTER,
None,
urwid.MIDDLE,
None,
)
return w, exit_w
def main(self):
self.view, self.exit_view = self.setup_view()
self.loop = urwid.MainLoop(self.view, self.palette, unhandled_input=self.unhandled_input)
self.loop.run()
def unhandled_input(self, key: str | tuple[str, int, int, int]) -> bool | None:
if key == "f8":
self.loop.widget = self.exit_view
return True
if self.loop.widget != self.exit_view:
return None
if key in {"y", "Y"}:
raise urwid.ExitMainLoop()
if key in {"n", "N"}:
self.loop.widget = self.view
return True
return None
def main():
BigTextDisplay().main()
if __name__ == "__main__":
main()
| 6,402 | Python | .py | 165 | 30.345455 | 113 | 0.589496 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,170 | tour.py | urwid_urwid/docs/examples/tour.py | #!/usr/bin/env python
#
# Urwid tour. It slices, it dices..
# Copyright (C) 2004-2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid tour. Shows many of the standard widget types and features.
"""
from __future__ import annotations
import urwid
def main():
text_header = "Welcome to the urwid tour! UP / DOWN / PAGE UP / PAGE DOWN scroll. F8 exits."
text_intro = [
("important", "Text"),
" widgets are the most common in "
"any urwid program. This Text widget was created "
"without setting the wrap or align mode, so it "
"defaults to left alignment with wrapping on space "
"characters. ",
("important", "Change the window width"),
" to see how the widgets on this page react. This Text widget is wrapped with a ",
("important", "Padding"),
" widget to keep it indented on the left and right.",
]
text_right = "This Text widget is right aligned. Wrapped words stay to the right as well. "
text_center = "This one is center aligned."
text_clip = (
"Text widgets may be clipped instead of wrapped.\n"
"Extra text is discarded instead of wrapped to the next line. "
"65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n"
"Newlines embedded in the string are still respected."
)
text_right_clip = (
"This is a right aligned and clipped Text widget.\n"
"<100 <-95 <-90 <-85 <-80 <-75 <-70 <-65 "
"Text will be cut off at the left of this widget."
)
text_center_clip = "Center aligned and clipped widgets will have text cut off both sides."
text_ellipsis = (
"Text can be clipped using the ellipsis character (…)\n"
"Extra text is discarded and a … mark is shown."
"50-> 55-> 60-> 65-> 70-> 75-> 80-> 85-> 90-> 95-> 100>\n"
)
text_any = (
"The 'any' wrap mode will wrap on any character. This "
"mode will not collapse space characters at the end of the "
"line but it still honors embedded newline characters.\n"
"Like this one."
)
text_padding = (
"Padding widgets have many options. This "
"is a standard Text widget wrapped with a Padding widget "
"with the alignment set to relative 20% and with its width "
"fixed at 40."
)
text_divider = [
"The ",
("important", "Divider"),
" widget repeats the same character across the whole line. It can also add blank lines above and below.",
]
text_edit = [
"The ",
("important", "Edit"),
" widget is a simple text editing widget. It supports cursor "
"movement and tries to maintain the current column when focus "
"moves to another edit widget. It wraps and aligns the same "
"way as Text widgets.",
]
text_edit_cap1 = ("editcp", "This is a caption. Edit here: ")
text_edit_text1 = "editable stuff"
text_edit_cap2 = ("editcp", "This one supports newlines: ")
text_edit_text2 = (
"line one starts them all\n"
"== line 2 == with some more text to edit.. words.. whee..\n"
"LINE III, the line to end lines one and two, unless you "
"change something."
)
text_edit_cap3 = ("editcp", "This one is clipped, try editing past the edge: ")
text_edit_text3 = "add some text here -> -> -> ...."
text_edit_alignments = "Different Alignments:"
text_edit_left = "left aligned (default)"
text_edit_center = "center aligned"
text_edit_right = "right aligned"
text_intedit = ("editcp", [("important", "IntEdit"), " allows only numbers: "])
text_edit_padding = ("editcp", "Edit widget within a Padding widget ")
text_columns1 = [
("important", "Columns"),
" are used to share horizontal screen space. "
"This one splits the space into two parts with "
"three characters between each column. The "
"contents of each column is a single widget.",
]
text_columns2 = [
"When you need to put more than one widget into a column you can use a ",
("important", "Pile"),
" to combine two or more widgets.",
]
text_col_columns = "Columns may be placed inside other columns."
text_col_21 = "Col 2.1"
text_col_22 = "Col 2.2"
text_col_23 = "Col 2.3"
text_column_widths = (
"Columns may also have uneven relative "
"weights or fixed widths. Use a minimum width so that "
"columns don't become too small."
)
text_weight = "Weight %d"
text_fixed_9 = "<Fixed 9>" # should be 9 columns wide
text_fixed_14 = "<--Fixed 14-->" # should be 14 columns wide
text_edit_col_cap1 = ("editcp", "Edit widget within Columns")
text_edit_col_text1 = "here's\nsome\ninfo"
text_edit_col_cap2 = ("editcp", "and within Pile ")
text_edit_col_text2 = "more"
text_edit_col_cap3 = ("editcp", "another ")
text_edit_col_text3 = "still more"
text_gridflow = [
"A ",
("important", "GridFlow"),
" widget "
"may be used to display a list of flow widgets with equal "
"widths. Widgets that don't fit on the first line will "
"flow to the next. This is useful for small widgets that "
"you want to keep together such as ",
("important", "Button"),
", ",
("important", "CheckBox"),
" and ",
("important", "RadioButton"),
" widgets.",
]
text_button_list = ["Yes", "No", "Perhaps", "Certainly", "Partially", "Tuesdays Only", "Help"]
text_cb_list = ["Wax", "Wash", "Buff", "Clear Coat", "Dry", "Racing Stripe"]
text_rb_list = ["Morning", "Afternoon", "Evening", "Weekend"]
text_listbox = [
"All these widgets have been displayed with the help of a ",
("important", "ListBox"),
" widget. ListBox widgets handle scrolling and changing focus. A ",
("important", "Frame"),
" widget is used to keep the instructions at the top of the screen.",
]
def button_press(button):
frame.footer = urwid.AttrMap(urwid.Text(["Pressed: ", button.get_label()]), "header")
radio_button_group = []
blank = urwid.Divider()
listbox_content = [
blank,
urwid.Padding(urwid.Text(text_intro), left=2, right=2, min_width=20),
blank,
urwid.Text(text_right, align=urwid.RIGHT),
blank,
urwid.Text(text_center, align=urwid.CENTER),
blank,
urwid.Text(text_clip, wrap=urwid.CLIP),
blank,
urwid.Text(text_right_clip, align=urwid.RIGHT, wrap=urwid.CLIP),
blank,
urwid.Text(text_center_clip, align=urwid.CENTER, wrap=urwid.CLIP),
blank,
urwid.Text(text_ellipsis, wrap=urwid.ELLIPSIS),
blank,
urwid.Text(text_any, wrap=urwid.ANY),
blank,
urwid.Padding(urwid.Text(text_padding), (urwid.RELATIVE, 20), 40),
blank,
urwid.AttrMap(urwid.Divider("=", 1), "bright"),
urwid.Padding(urwid.Text(text_divider), left=2, right=2, min_width=20),
urwid.AttrMap(urwid.Divider("-", 0, 1), "bright"),
blank,
urwid.Padding(urwid.Text(text_edit), left=2, right=2, min_width=20),
blank,
urwid.AttrMap(urwid.Edit(text_edit_cap1, text_edit_text1), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.Edit(text_edit_cap2, text_edit_text2, multiline=True), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.Edit(text_edit_cap3, text_edit_text3, wrap=urwid.CLIP), "editbx", "editfc"),
blank,
urwid.Text(text_edit_alignments),
urwid.AttrMap(urwid.Edit("", text_edit_left, align=urwid.LEFT), "editbx", "editfc"),
urwid.AttrMap(urwid.Edit("", text_edit_center, align=urwid.CENTER), "editbx", "editfc"),
urwid.AttrMap(urwid.Edit("", text_edit_right, align=urwid.RIGHT), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.IntEdit(text_intedit, 123), "editbx", "editfc"),
blank,
urwid.Padding(urwid.AttrMap(urwid.Edit(text_edit_padding, ""), "editbx", "editfc"), left=10, width=50),
blank,
blank,
urwid.AttrMap(
urwid.Columns(
[
urwid.Divider("."),
urwid.Divider(","),
urwid.Divider("."),
]
),
"bright",
),
blank,
urwid.Columns(
[
urwid.Padding(urwid.Text(text_columns1), left=2, right=0, min_width=20),
urwid.Pile([urwid.Divider("~"), urwid.Text(text_columns2), urwid.Divider("_")]),
],
3,
),
blank,
blank,
urwid.Columns(
[
urwid.Text(text_col_columns),
urwid.Columns(
[
urwid.Text(text_col_21),
urwid.Text(text_col_22),
urwid.Text(text_col_23),
],
1,
),
],
2,
),
blank,
urwid.Padding(urwid.Text(text_column_widths), left=2, right=2, min_width=20),
blank,
urwid.Columns(
[
urwid.AttrMap(urwid.Text(text_weight % 1), "reverse"),
(urwid.WEIGHT, 2, urwid.Text(text_weight % 2)),
(urwid.WEIGHT, 3, urwid.AttrMap(urwid.Text(text_weight % 3), "reverse")),
(urwid.WEIGHT, 4, urwid.Text(text_weight % 4)),
(urwid.WEIGHT, 5, urwid.AttrMap(urwid.Text(text_weight % 5), "reverse")),
(urwid.WEIGHT, 6, urwid.Text(text_weight % 6)),
],
0,
min_width=8,
),
blank,
urwid.Columns(
[
(urwid.WEIGHT, 2, urwid.AttrMap(urwid.Text(text_weight % 2), "reverse")),
(9, urwid.Text(text_fixed_9)),
(urwid.WEIGHT, 3, urwid.AttrMap(urwid.Text(text_weight % 3), "reverse")),
(14, urwid.Text(text_fixed_14)),
],
0,
min_width=8,
),
blank,
urwid.Columns(
[
urwid.AttrMap(urwid.Edit(text_edit_col_cap1, text_edit_col_text1, multiline=True), "editbx", "editfc"),
urwid.Pile(
[
urwid.AttrMap(urwid.Edit(text_edit_col_cap2, text_edit_col_text2), "editbx", "editfc"),
blank,
urwid.AttrMap(urwid.Edit(text_edit_col_cap3, text_edit_col_text3), "editbx", "editfc"),
]
),
],
1,
),
blank,
urwid.AttrMap(
urwid.Columns(
[
urwid.Divider("'"),
urwid.Divider('"'),
urwid.Divider("~"),
urwid.Divider('"'),
urwid.Divider("'"),
]
),
"bright",
),
blank,
blank,
urwid.Padding(urwid.Text(text_gridflow), left=2, right=2, min_width=20),
blank,
urwid.Padding(
urwid.GridFlow(
[urwid.AttrMap(urwid.Button(txt, button_press), "buttn", "buttnf") for txt in text_button_list],
13,
3,
1,
urwid.LEFT,
),
left=4,
right=3,
min_width=13,
),
blank,
urwid.Padding(
urwid.GridFlow(
[urwid.AttrMap(urwid.CheckBox(txt), "buttn", "buttnf") for txt in text_cb_list],
10,
3,
1,
urwid.LEFT,
),
left=4,
right=3,
min_width=10,
),
blank,
urwid.Padding(
urwid.GridFlow(
[urwid.AttrMap(urwid.RadioButton(radio_button_group, txt), "buttn", "buttnf") for txt in text_rb_list],
13,
3,
1,
urwid.LEFT,
),
left=4,
right=3,
min_width=13,
),
blank,
blank,
urwid.Padding(urwid.Text(text_listbox), left=2, right=2, min_width=20),
blank,
blank,
]
header = urwid.AttrMap(urwid.Text(text_header), "header")
listbox = urwid.ListBox(urwid.SimpleListWalker(listbox_content))
scrollable = urwid.ScrollBar(
listbox,
trough_char=urwid.ScrollBar.Symbols.LITE_SHADE,
)
frame = urwid.Frame(urwid.AttrMap(scrollable, "body"), header=header)
palette = [
("body", "black", "light gray", "standout"),
("reverse", "light gray", "black"),
("header", "white", "dark red", "bold"),
("important", "dark blue", "light gray", ("standout", "underline")),
("editfc", "white", "dark blue", "bold"),
("editbx", "light gray", "dark blue"),
("editcp", "black", "light gray", "standout"),
("bright", "dark gray", "light gray", ("bold", "standout")),
("buttn", "black", "dark cyan"),
("buttnf", "white", "dark blue", "bold"),
]
# use appropriate Screen class
if urwid.display.web.is_web_request():
screen = urwid.display.web.Screen()
else:
screen = urwid.display.raw.Screen()
def unhandled(key: str | tuple[str, int, int, int]) -> None:
if key == "f8":
raise urwid.ExitMainLoop()
urwid.MainLoop(frame, palette, screen, unhandled_input=unhandled).run()
def setup():
urwid.display.web.set_preferences("Urwid Tour")
# try to handle short web requests quickly
if urwid.display.web.handle_short_request():
return
main()
if __name__ == "__main__" or urwid.display.web.is_web_request():
setup()
| 14,714 | Python | .py | 372 | 30.075269 | 119 | 0.559078 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,171 | subproc.py.xdotool | urwid_urwid/docs/examples/subproc.py.xdotool | windowsize --usehints $RXVTWINDOWID 39 18
key --window $RXVTWINDOWID a n y t h i n g question
| 94 | Python | .py | 2 | 46 | 51 | 0.771739 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,172 | graph.py | urwid_urwid/docs/examples/graph.py | #!/usr/bin/env python
#
# Urwid graphics example program
# Copyright (C) 2004-2011 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Urwid example demonstrating use of the BarGraph widget and creating a
floating-window appearance. Also shows use of alarms to create timed
animation.
"""
from __future__ import annotations
import math
import time
import typing
import urwid
UPDATE_INTERVAL = 0.2
def sin100(x):
"""
A sin function that returns values between 0 and 100 and repeats
after x == 100.
"""
return 50 + 50 * math.sin(x * math.pi / 50)
class GraphModel:
"""
A class responsible for storing the data that will be displayed
on the graph, and keeping track of which mode is enabled.
"""
data_max_value = 100
def __init__(self):
data = [
("Saw", list(range(0, 100, 2)) * 2),
("Square", [0] * 30 + [100] * 30),
("Sine 1", [sin100(x) for x in range(100)]),
("Sine 2", [(sin100(x) + sin100(x * 2)) / 2 for x in range(100)]),
("Sine 3", [(sin100(x) + sin100(x * 3)) / 2 for x in range(100)]),
]
self.modes = []
self.data = {}
for m, d in data:
self.modes.append(m)
self.data[m] = d
def get_modes(self):
return self.modes
def set_mode(self, m) -> None:
self.current_mode = m
def get_data(self, offset, r):
"""
Return the data in [offset:offset+r], the maximum value
for items returned, and the offset at which the data
repeats.
"""
lines = []
d = self.data[self.current_mode]
while r:
offset %= len(d)
segment = d[offset : offset + r]
r -= len(segment)
offset += len(segment)
lines += segment
return lines, self.data_max_value, len(d)
class GraphView(urwid.WidgetWrap):
"""
A class responsible for providing the application's interface and
graph display.
"""
palette: typing.ClassVar[tuple[str, str, str, ...]] = [
("body", "black", "light gray", "standout"),
("header", "white", "dark red", "bold"),
("screen edge", "light blue", "dark cyan"),
("main shadow", "dark gray", "black"),
("line", "black", "light gray", "standout"),
("bg background", "light gray", "black"),
("bg 1", "black", "dark blue", "standout"),
("bg 1 smooth", "dark blue", "black"),
("bg 2", "black", "dark cyan", "standout"),
("bg 2 smooth", "dark cyan", "black"),
("button normal", "light gray", "dark blue", "standout"),
("button select", "white", "dark green"),
("line", "black", "light gray", "standout"),
("pg normal", "white", "black", "standout"),
("pg complete", "white", "dark magenta"),
("pg smooth", "dark magenta", "black"),
]
graph_samples_per_bar = 10
graph_num_bars = 5
graph_offset_per_second = 5
def __init__(self, controller):
self.controller = controller
self.started = True
self.start_time = None
self.offset = 0
self.last_offset = None
super().__init__(self.main_window())
def get_offset_now(self):
if self.start_time is None:
return 0
if not self.started:
return self.offset
tdelta = time.time() - self.start_time
return int(self.offset + (tdelta * self.graph_offset_per_second))
def update_graph(self, force_update=False):
o = self.get_offset_now()
if o == self.last_offset and not force_update:
return False
self.last_offset = o
gspb = self.graph_samples_per_bar
r = gspb * self.graph_num_bars
d, max_value, repeat = self.controller.get_data(o, r)
lines = []
for n in range(self.graph_num_bars):
value = sum(d[n * gspb : (n + 1) * gspb]) / gspb
# toggle between two bar types
if n & 1:
lines.append([0, value])
else:
lines.append([value, 0])
self.graph.set_data(lines, max_value)
# also update progress
if (o // repeat) & 1:
# show 100% for first half, 0 for second half
if o % repeat > repeat // 2:
prog = 0
else:
prog = 1
else:
prog = float(o % repeat) / repeat
self.animate_progress.current = prog
return True
def on_animate_button(self, button):
"""Toggle started state and button text."""
if self.started: # stop animation
button.base_widget.set_label("Start")
self.offset = self.get_offset_now()
self.started = False
self.controller.stop_animation()
else:
button.base_widget.set_label("Stop")
self.started = True
self.start_time = time.time()
self.controller.animate_graph()
def on_reset_button(self, w):
self.offset = 0
self.start_time = time.time()
self.update_graph(True)
def on_mode_button(self, button, state):
"""Notify the controller of a new mode setting."""
if state:
# The new mode is the label of the button
self.controller.set_mode(button.get_label())
self.last_offset = None
def on_mode_change(self, m):
"""Handle external mode change by updating radio buttons."""
for rb in self.mode_buttons:
if rb.base_widget.label == m:
rb.base_widget.set_state(True, do_callback=False)
break
self.last_offset = None
def on_unicode_checkbox(self, w, state):
self.graph = self.bar_graph(state)
self.graph_wrap._w = self.graph
self.animate_progress = self.progress_bar(state)
self.animate_progress_wrap._w = self.animate_progress
self.update_graph(True)
def main_shadow(self, w):
"""Wrap a shadow and background around widget w."""
bg = urwid.AttrMap(urwid.SolidFill("▒"), "screen edge")
shadow = urwid.AttrMap(urwid.SolidFill(" "), "main shadow")
bg = urwid.Overlay(
shadow,
bg,
align=urwid.LEFT,
width=urwid.RELATIVE_100,
valign=urwid.TOP,
height=urwid.RELATIVE_100,
left=3,
right=1,
top=2,
bottom=1,
)
w = urwid.Overlay(
w,
bg,
align=urwid.LEFT,
width=urwid.RELATIVE_100,
valign=urwid.TOP,
height=urwid.RELATIVE_100,
left=2,
right=3,
top=1,
bottom=2,
)
return w
def bar_graph(self, smooth=False):
satt = None
if smooth:
satt = {(1, 0): "bg 1 smooth", (2, 0): "bg 2 smooth"}
w = urwid.BarGraph(["bg background", "bg 1", "bg 2"], satt=satt)
return w
def button(self, t, fn):
w = urwid.Button(t, fn)
w = urwid.AttrMap(w, "button normal", "button select")
return w
def radio_button(self, g, label, fn):
w = urwid.RadioButton(g, label, False, on_state_change=fn)
w = urwid.AttrMap(w, "button normal", "button select")
return w
def progress_bar(self, smooth=False):
if smooth:
return urwid.ProgressBar("pg normal", "pg complete", 0, 1, "pg smooth")
return urwid.ProgressBar("pg normal", "pg complete", 0, 1)
def exit_program(self, w):
raise urwid.ExitMainLoop()
def graph_controls(self):
modes = self.controller.get_modes()
# setup mode radio buttons
self.mode_buttons = []
group = []
for m in modes:
rb = self.radio_button(group, m, self.on_mode_button)
self.mode_buttons.append(rb)
# setup animate button
self.animate_button = self.button("", self.on_animate_button)
self.on_animate_button(self.animate_button)
self.offset = 0
self.animate_progress = self.progress_bar()
animate_controls = urwid.GridFlow(
[
self.animate_button,
self.button("Reset", self.on_reset_button),
],
9,
2,
0,
urwid.CENTER,
)
if urwid.get_encoding_mode() == "utf8":
unicode_checkbox = urwid.CheckBox("Enable Unicode Graphics", on_state_change=self.on_unicode_checkbox)
else:
unicode_checkbox = urwid.Text("UTF-8 encoding not detected")
self.animate_progress_wrap = urwid.WidgetWrap(self.animate_progress)
lines = [
urwid.Text("Mode", align=urwid.CENTER),
*self.mode_buttons,
urwid.Divider(),
urwid.Text("Animation", align=urwid.CENTER),
animate_controls,
self.animate_progress_wrap,
urwid.Divider(),
urwid.LineBox(unicode_checkbox),
urwid.Divider(),
self.button("Quit", self.exit_program),
]
w = urwid.ListBox(urwid.SimpleListWalker(lines))
return w
def main_window(self):
self.graph = self.bar_graph()
self.graph_wrap = urwid.WidgetWrap(self.graph)
vline = urwid.AttrMap(urwid.SolidFill("│"), "line")
c = self.graph_controls()
w = urwid.Columns([(urwid.WEIGHT, 2, self.graph_wrap), (1, vline), c], dividechars=1, focus_column=2)
w = urwid.Padding(w, urwid.LEFT, left=1)
w = urwid.AttrMap(w, "body")
w = urwid.LineBox(w)
w = urwid.AttrMap(w, "line")
w = self.main_shadow(w)
return w
class GraphController:
"""
A class responsible for setting up the model and view and running
the application.
"""
def __init__(self):
self.animate_alarm = None
self.model = GraphModel()
self.view = GraphView(self)
# use the first mode as the default
mode = self.get_modes()[0]
self.model.set_mode(mode)
# update the view
self.view.on_mode_change(mode)
self.view.update_graph(True)
def get_modes(self):
"""Allow our view access to the list of modes."""
return self.model.get_modes()
def set_mode(self, m) -> None:
"""Allow our view to set the mode."""
self.model.set_mode(m)
self.view.update_graph(True)
def get_data(self, offset, data_range):
"""Provide data to our view for the graph."""
return self.model.get_data(offset, data_range)
def main(self):
self.loop = urwid.MainLoop(self.view, self.view.palette)
self.loop.run()
def animate_graph(self, loop=None, user_data=None):
"""update the graph and schedule the next update"""
self.view.update_graph()
self.animate_alarm = self.loop.set_alarm_in(UPDATE_INTERVAL, self.animate_graph)
def stop_animation(self):
"""stop animating the graph"""
if self.animate_alarm:
self.loop.remove_alarm(self.animate_alarm)
self.animate_alarm = None
def main():
GraphController().main()
if __name__ == "__main__":
main()
| 12,077 | Python | .py | 322 | 28.73913 | 114 | 0.577962 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,173 | edit.py.xdotool | urwid_urwid/docs/examples/edit.py.xdotool | windowsize --usehints $RXVTWINDOWID 39 20
key --window $RXVTWINDOWID Return Return a d d i n g space s o m e space t e x t space
| 129 | Python | .py | 2 | 63.5 | 86 | 0.755906 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,174 | palette_test.py.xdotool | urwid_urwid/docs/examples/palette_test.py.xdotool | windowsize --usehints $RXVTWINDOWID 79 34
key --window $RXVTWINDOWID Down Down Down Return Right Down Return
| 109 | Python | .py | 2 | 53.5 | 66 | 0.82243 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,175 | subproc.py | urwid_urwid/docs/examples/subproc.py | #!/usr/bin/env python
from __future__ import annotations
import os
import subprocess
import sys
import urwid
factor_me = 362923067964327863989661926737477737673859044111968554257667
run_me = os.path.join(os.path.dirname(sys.argv[0]), "subproc2.py")
output_widget = urwid.Text(f"Factors of {factor_me:d}:\n")
edit_widget = urwid.Edit("Type anything or press enter to exit:")
frame_widget = urwid.Frame(
header=edit_widget,
body=urwid.Filler(output_widget, valign=urwid.BOTTOM),
focus_part="header",
)
def exit_on_enter(key: str | tuple[str, int, int, int]) -> None:
if key == "enter":
raise urwid.ExitMainLoop()
loop = urwid.MainLoop(frame_widget, unhandled_input=exit_on_enter)
def received_output(data: bytes) -> bool:
output_widget.set_text(output_widget.text + data.decode("utf8"))
return True
write_fd = loop.watch_pipe(received_output)
with subprocess.Popen( # noqa: S603
["python", "-u", run_me, str(factor_me)], # noqa: S607 # Example can be insecure
stdout=write_fd,
close_fds=True,
) as proc:
loop.run()
| 1,077 | Python | .py | 29 | 34.034483 | 86 | 0.725604 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,176 | pop_up.py | urwid_urwid/docs/examples/pop_up.py | #!/usr/bin/env python
from __future__ import annotations
import typing
import urwid
class PopUpDialog(urwid.WidgetWrap):
"""A dialog that appears with nothing but a close button"""
signals: typing.ClassVar[list[str]] = ["close"]
def __init__(self):
close_button = urwid.Button("that's pretty cool")
urwid.connect_signal(close_button, "click", lambda button: self._emit("close"))
pile = urwid.Pile(
[
urwid.Text("^^ I'm attached to the widget that opened me. Try resizing the window!\n"),
close_button,
]
)
super().__init__(urwid.AttrMap(urwid.Filler(pile), "popbg"))
class ThingWithAPopUp(urwid.PopUpLauncher):
def __init__(self) -> None:
super().__init__(urwid.Button("click-me"))
urwid.connect_signal(self.original_widget, "click", lambda button: self.open_pop_up())
def create_pop_up(self) -> PopUpDialog:
pop_up = PopUpDialog()
urwid.connect_signal(pop_up, "close", lambda button: self.close_pop_up())
return pop_up
def get_pop_up_parameters(self):
return {"left": 0, "top": 1, "overlay_width": 32, "overlay_height": 7}
def keypress(self, size: tuple[int], key: str) -> str | None:
parsed = super().keypress(size, key)
if parsed in {"q", "Q"}:
raise urwid.ExitMainLoop("Done")
return parsed
fill = urwid.Filler(urwid.Padding(ThingWithAPopUp(), urwid.CENTER, 15))
loop = urwid.MainLoop(fill, [("popbg", "white", "dark blue")], pop_ups=True)
loop.run()
| 1,578 | Python | .py | 35 | 37.742857 | 104 | 0.627207 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,177 | palette_test.py | urwid_urwid/docs/examples/palette_test.py | #!/usr/bin/env python
#
# Urwid Palette Test. Showing off highcolor support
# Copyright (C) 2004-2009 Ian Ward
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Urwid web site: https://urwid.org/
"""
Palette test. Shows the available foreground and background settings
in monochrome, 16 color, 88 color, 256 color, and 24-bit (true) color modes.
"""
from __future__ import annotations
import re
import typing
import urwid
if typing.TYPE_CHECKING:
from typing_extensions import Literal
CHART_TRUE = """
#e50000#e51000#e52000#e53000#e54000#e55000#e56000#e57000#e58000#e59000\
#e5a000#e5b100#e5c100#e5d100#e5e100#d9e500#c9e500#b9e500#a9e500#99e500\
#89e500#79e500#68e500#58e500#48e500#38e500#28e500#18e500#08e500#00e507\
#00e517#00e527#00e538#00e548#00e558#00e568#00e578#00e588#00e598#00e5a8\
#00e5b8#00e5c8#00e5d8#00e1e5#00d1e5#00c1e5#00b1e5#00a1e5#0091e5#0081e5\
#0071e5#0061e5#0051e5#0040e5#0030e5#0020e5#0010e5#0000e5#0f00e5#1f00e5\
#2f00e5#3f00e5#4f00e5#5f00e5#7000e5#8000e5#9000e5#a000e5#b000e5#c000e5\
#d000e5#e000e5#e500da#e500ca#e500b9#e500a9#e50099#e50089
#da0000#da0f00#da1e00#da2e00#da3d00#da4c00#da5c00#da6b00#da7a00#da8a00\
#da9900#daa800#dab800#dac700#dad600#cfda00#c0da00#b0da00#a1da00#92da00\
#82da00#73da00#64da00#54da00#45da00#35da00#26da00#17da00#07da00#00da07\
#00da16#00da26#00da35#00da44#00da54#00da63#00da72#00da82#00da91#00daa0\
#00dab0#00dabf#00dace#00d7da#00c8da#00b8da#00a9da#0099da#008ada#007bda\
#006bda#005cda#004dda#003dda#002eda#001fda#000fda#0000da#0e00da#1e00da\
#2d00da#3c00da#4c00da#5b00da#6a00da#7a00da#8900da#9800da#a800da#b700da\
#c600da#d600da#da00cf#da00c0#da00b1#da00a1#da0092#da0083
#d00000#d00e00#d01d00#d02b00#d03a00#d04800#d05700#d06600#d07400#d08300\
#d09100#d0a000#d0af00#d0bd00#d0cc00#c5d000#b6d000#a8d000#99d000#8ad000\
#7cd000#6dd000#5fd000#50d000#41d000#33d000#24d000#16d000#07d000#00d007\
#00d015#00d024#00d032#00d041#00d04f#00d05e#00d06d#00d07b#00d08a#00d098\
#00d0a7#00d0b6#00d0c4#00ccd0#00bed0#00afd0#00a1d0#0092d0#0083d0#0075d0\
#0066d0#0058d0#0049d0#003ad0#002cd0#001dd0#000fd0#0000d0#0e00d0#1c00d0\
#2b00d0#3900d0#4800d0#5600d0#6500d0#7400d0#8200d0#9100d0#9f00d0#ae00d0\
#bd00d0#cb00d0#d000c5#d000b7#d000a8#d00099#d0008b#d0007c
#c50000#c50d00#c51b00#c52900#c53700#c54500#c55300#c56000#c56e00#c57c00\
#c58a00#c59800#c5a600#c5b300#c5c100#bbc500#adc500#9fc500#91c500#83c500\
#75c500#68c500#5ac500#4cc500#3ec500#30c500#22c500#15c500#07c500#00c506\
#00c514#00c522#00c530#00c53e#00c54b#00c559#00c567#00c575#00c583#00c591\
#00c59e#00c5ac#00c5ba#00c2c5#00b4c5#00a6c5#0098c5#008ac5#007dc5#006fc5\
#0061c5#0053c5#0045c5#0037c5#002ac5#001cc5#000ec5#0000c5#0d00c5#1b00c5\
#2800c5#3600c5#4400c5#5200c5#6000c5#6e00c5#7c00c5#8900c5#9700c5#a500c5\
#b300c5#c100c5#c500bb#c500ad#c5009f#c50092#c50084#c50076
#ba0000#ba0d00#ba1a00#ba2700#ba3400#ba4100#ba4e00#ba5b00#ba6800#ba7500\
#ba8200#ba8f00#ba9c00#baaa00#bab700#b0ba00#a3ba00#96ba00#89ba00#7cba00\
#6fba00#62ba00#55ba00#48ba00#3bba00#2eba00#20ba00#13ba00#06ba00#00ba06\
#00ba13#00ba20#00ba2d#00ba3a#00ba47#00ba54#00ba61#00ba6e#00ba7c#00ba89\
#00ba96#00baa3#00bab0#00b7ba#00aaba#009dba#0090ba#0083ba#0076ba#0069ba\
#005cba#004eba#0041ba#0034ba#0027ba#001aba#000dba#0000ba#0c00ba#1900ba\
#2600ba#3300ba#4000ba#4e00ba#5b00ba#6800ba#7500ba#8200ba#8f00ba#9c00ba\
#a900ba#b600ba#ba00b1#ba00a4#ba0097#ba008a#ba007d#ba006f
#af0000#af0c00#af1800#af2400#af3100#af3d00#af4900#af5600#af6200#af6e00\
#af7b00#af8700#af9300#afa000#afac00#a6af00#9aaf00#8eaf00#81af00#75af00\
#69af00#5caf00#50af00#44af00#37af00#2baf00#1faf00#12af00#06af00#00af05\
#00af12#00af1e#00af2a#00af37#00af43#00af4f#00af5c#00af68#00af74#00af81\
#00af8d#00af99#00afa6#00adaf#00a0af#0094af#0088af#007baf#006faf#0063af\
#0056af#004aaf#003eaf#0031af#0025af#0019af#000caf#0000af#0b00af#1800af\
#2400af#3000af#3d00af#4900af#5500af#6200af#6e00af#7a00af#8700af#9300af\
#9f00af#ac00af#af00a7#af009a#af008e#af0082#af0075#af0069
#a50000#a50b00#a51700#a52200#a52e00#a53900#a54500#a55100#a55c00#a56800\
#a57300#a57f00#a58a00#a59600#a5a200#9ca500#90a500#85a500#79a500#6ea500\
#62a500#57a500#4ba500#3fa500#34a500#28a500#1da500#11a500#06a500#00a505\
#00a511#00a51c#00a528#00a533#00a53f#00a54b#00a556#00a562#00a56d#00a579\
#00a584#00a590#00a59c#00a2a5#0096a5#008ba5#007fa5#0074a5#0068a5#005da5\
#0051a5#0045a5#003aa5#002ea5#0023a5#0017a5#000ca5#0000a5#0b00a5#1600a5\
#2200a5#2d00a5#3900a5#4500a5#5000a5#5c00a5#6700a5#7300a5#7e00a5#8a00a5\
#9600a5#a100a5#a5009c#a50091#a50085#a5007a#a5006e#a50063
#9a0000#9a0a00#9a1500#9a2000#9a2b00#9a3600#9a4000#9a4b00#9a5600#9a6100\
#9a6c00#9a7700#9a8100#9a8c00#9a9700#929a00#879a00#7c9a00#719a00#679a00\
#5c9a00#519a00#469a00#3b9a00#309a00#269a00#1b9a00#109a00#059a00#009a05\
#009a10#009a1a#009a25#009a30#009a3b#009a46#009a50#009a5b#009a66#009a71\
#009a7c#009a87#009a91#00979a#008d9a#00829a#00779a#006c9a#00619a#00569a\
#004c9a#00419a#00369a#002b9a#00209a#00169a#000b9a#00009a#0a009a#15009a\
#20009a#2a009a#35009a#40009a#4b009a#56009a#61009a#6b009a#76009a#81009a\
#8c009a#97009a#9a0092#9a0087#9a007d#9a0072#9a0067#9a005c
#8f0000#8f0a00#8f1400#8f1e00#8f2800#8f3200#8f3c00#8f4600#8f5000#8f5a00\
#8f6400#8f6e00#8f7800#8f8200#8f8c00#888f00#7e8f00#748f00#698f00#5f8f00\
#558f00#4b8f00#418f00#378f00#2d8f00#238f00#198f00#0f8f00#058f00#008f04\
#008f0e#008f18#008f23#008f2d#008f37#008f41#008f4b#008f55#008f5f#008f69\
#008f73#008f7d#008f87#008d8f#00838f#00798f#006f8f#00658f#005b8f#00508f\
#00468f#003c8f#00328f#00288f#001e8f#00148f#000a8f#00008f#09008f#13008f\
#1d008f#27008f#31008f#3c008f#46008f#50008f#5a008f#64008f#6e008f#78008f\
#82008f#8c008f#8f0088#8f007e#8f0074#8f006a#8f0060#8f0056
#840000#840900#841200#841b00#842500#842e00#843700#844100#844a00#845300\
#845d00#846600#846f00#847900#848200#7d8400#748400#6b8400#628400#588400\
#4f8400#468400#3c8400#338400#2a8400#208400#178400#0e8400#048400#008404\
#00840d#008417#008420#008429#008433#00843c#008445#00844f#008458#008461\
#00846a#008474#00847d#008284#007984#007084#006684#005d84#005484#004a84\
#004184#003884#002e84#002584#001c84#001284#000984#000084#080084#120084\
#1b0084#240084#2e0084#370084#400084#4a0084#530084#5c0084#660084#6f0084\
#780084#820084#84007e#840074#84006b#840062#840059#84004f
#7a0000#7a0800#7a1100#7a1900#7a2200#7a2a00#7a3300#7a3b00#7a4400#7a4d00\
#7a5500#7a5e00#7a6600#7a6f00#7a7700#737a00#6b7a00#627a00#5a7a00#517a00\
#487a00#407a00#377a00#2f7a00#267a00#1e7a00#157a00#0d7a00#047a00#007a04\
#007a0c#007a15#007a1d#007a26#007a2e#007a37#007a40#007a48#007a51#007a59\
#007a62#007a6a#007a73#00787a#006f7a#00677a#005e7a#00557a#004d7a#00447a\
#003c7a#00337a#002b7a#00227a#001a7a#00117a#00087a#00007a#08007a#10007a\
#19007a#21007a#2a007a#33007a#3b007a#44007a#4c007a#55007a#5d007a#66007a\
#6f007a#77007a#7a0074#7a006b#7a0062#7a005a#7a0051#7a0049
#6f0000#6f0700#6f0f00#6f1700#6f1f00#6f2700#6f2e00#6f3600#6f3e00#6f4600\
#6f4e00#6f5500#6f5d00#6f6500#6f6d00#696f00#616f00#596f00#526f00#4a6f00\
#426f00#3a6f00#326f00#2b6f00#236f00#1b6f00#136f00#0b6f00#046f00#006f03\
#006f0b#006f13#006f1b#006f23#006f2a#006f32#006f3a#006f42#006f4a#006f51\
#006f59#006f61#006f69#006d6f#00656f#005e6f#00566f#004e6f#00466f#003e6f\
#00366f#002f6f#00276f#001f6f#00176f#000f6f#00086f#00006f#07006f#0f006f\
#17006f#1e006f#26006f#2e006f#36006f#3e006f#46006f#4d006f#55006f#5d006f\
#65006f#6d006f#6f0069#6f0062#6f005a#6f0052#6f004a#6f0042
#640000#640700#640e00#641500#641c00#642300#642a00#643100#643800#643f00\
#644600#644d00#645400#645b00#646200#5f6400#586400#516400#4a6400#436400\
#3c6400#356400#2e6400#266400#1f6400#186400#116400#0a6400#036400#006403\
#00640a#006411#006418#00641f#006426#00642d#006434#00643b#006442#006449\
#006451#006458#00645f#006364#005c64#005464#004d64#004664#003f64#003864\
#003164#002a64#002364#001c64#001564#000e64#000764#000064#060064#0d0064\
#140064#1b0064#230064#2a0064#310064#380064#3f0064#460064#4d0064#540064\
#5b0064#620064#64005f#640058#640051#64004a#640043#64003c
#590000#590600#590c00#591200#591900#591f00#592500#592c00#593200#593800\
#593f00#594500#594b00#595100#595800#555900#4e5900#485900#425900#3c5900\
#355900#2f5900#295900#225900#1c5900#165900#0f5900#095900#035900#005903\
#005909#00590f#005915#00591c#005922#005928#00592f#005935#00593b#005942\
#005948#00594e#005955#005859#005259#004b59#004559#003f59#003859#003259\
#002c59#002659#001f59#001959#001359#000c59#000659#000059#060059#0c0059\
#120059#180059#1f0059#250059#2b0059#320059#380059#3e0059#450059#4b0059\
#510059#580059#590055#59004f#590048#590042#59003c#590035
#4f0000#4f0500#4f0b00#4f1000#4f1600#4f1b00#4f2100#4f2600#4f2c00#4f3100\
#4f3700#4f3d00#4f4200#4f4800#4f4d00#4b4f00#454f00#3f4f00#3a4f00#344f00\
#2f4f00#294f00#244f00#1e4f00#194f00#134f00#0d4f00#084f00#024f00#004f02\
#004f08#004f0d#004f13#004f18#004f1e#004f23#004f29#004f2f#004f34#004f3a\
#004f3f#004f45#004f4a#004d4f#00484f#00424f#003d4f#00374f#00324f#002c4f\
#00274f#00214f#001b4f#00164f#00104f#000b4f#00054f#00004f#05004f#0a004f\
#10004f#16004f#1b004f#21004f#26004f#2c004f#31004f#37004f#3c004f#42004f\
#47004f#4d004f#4f004b#4f0045#4f0040#4f003a#4f0035#4f002f
#440000#440400#440900#440e00#441300#441800#441c00#442100#442600#442b00\
#443000#443400#443900#443e00#444300#404400#3c4400#374400#324400#2d4400\
#284400#244400#1f4400#1a4400#154400#104400#0c4400#074400#024400#004402\
#004407#00440b#004410#004415#00441a#00441f#004423#004428#00442d#004432\
#004437#00443b#004440#004344#003e44#003944#003444#003044#002b44#002644\
#002144#001c44#001844#001344#000e44#000944#000444#000044#040044#090044\
#0e0044#130044#170044#1c0044#210044#260044#2b0044#2f0044#340044#390044\
#3e0044#430044#440041#44003c#440037#440032#44002d#440029
#390000#390400#390800#390c00#391000#391400#391800#391c00#392000#392400\
#392800#392c00#393000#393400#393800#363900#323900#2e3900#2a3900#263900\
#223900#1e3900#1a3900#163900#123900#0e3900#0a3900#063900#023900#003901\
#003905#00390a#00390e#003912#003916#00391a#00391e#003922#003926#00392a\
#00392e#003932#003936#003839#003439#003039#002c39#002839#002439#002039\
#001c39#001839#001439#001039#000c39#000839#000439#000039#030039#070039\
#0b0039#100039#140039#180039#1c0039#200039#240039#280039#2c0039#300039\
#340039#380039#390036#390032#39002e#39002a#390026#390022
#2e0000#2e0300#2e0600#2e0900#2e0d00#2e1000#2e1300#2e1700#2e1a00#2e1d00\
#2e2000#2e2400#2e2700#2e2a00#2e2e00#2c2e00#292e00#252e00#222e00#1f2e00\
#1c2e00#182e00#152e00#122e00#0e2e00#0b2e00#082e00#052e00#012e00#002e01\
#002e04#002e08#002e0b#002e0e#002e12#002e15#002e18#002e1b#002e1f#002e22\
#002e25#002e29#002e2c#002e2e#002a2e#00272e#00242e#00212e#001d2e#001a2e\
#00172e#00132e#00102e#000d2e#000a2e#00062e#00032e#00002e#03002e#06002e\
#09002e#0d002e#10002e#13002e#16002e#1a002e#1d002e#20002e#24002e#27002e\
#2a002e#2d002e#2e002c#2e0029#2e0026#2e0022#2e001f#2e001c
#240000#240200#240500#240700#240a00#240c00#240f00#241100#241400#241600\
#241900#241b00#241e00#242100#242300#222400#1f2400#1d2400#1a2400#182400\
#152400#132400#102400#0e2400#0b2400#082400#062400#032400#012400#002401\
#002403#002406#002408#00240b#00240d#002410#002413#002415#002418#00241a\
#00241d#00241f#002422#002324#002124#001e24#001c24#001924#001624#001424\
#001124#000f24#000c24#000a24#000724#000524#000224#000024#020024#040024\
#070024#0a0024#0c0024#0f0024#110024#140024#160024#190024#1b0024#1e0024\
#200024#230024#240022#24001f#24001d#24001a#240018#240015
#190000#190100#190300#190500#190700#190800#190a00#190c00#190e00#191000\
#191100#191300#191500#191700#191900#181900#161900#141900#121900#111900\
#0f1900#0d1900#0b1900#091900#081900#061900#041900#021900#001900#001900\
#001902#001904#001906#001908#001909#00190b#00190d#00190f#001910#001912\
#001914#001916#001918#001919#001719#001519#001319#001119#001019#000e19\
#000c19#000a19#000919#000719#000519#000319#000119#000019#010019#030019\
#050019#070019#080019#0a0019#0c0019#0e0019#100019#110019#130019#150019\
#170019#180019#190018#190016#190014#190012#190011#19000f
"""
# raise Exception(CHART_TRUE)
CHART_256 = """
brown__ dark_red_ dark_magenta_ dark_blue_ dark_cyan_ dark_green_
yellow_ light_red light_magenta light_blue light_cyan light_green
#00f#06f#08f#0af#0df#0ff black_______ dark_gray___
#60f#00d#06d#08d#0ad#0dd#0fd light_gray__ white_______
#80f#60d#00a#06a#08a#0aa#0da#0fa
#a0f#80d#60a#008#068#088#0a8#0d8#0f8
#d0f#a0d#80d#608#006#066#086#0a6#0d6#0f6
#f0f#d0d#a0a#808#606#000#060#080#0a0#0d0#0f0#0f6#0f8#0fa#0fd#0ff
#f0d#d0a#a08#806#600#660#680#6a0#6d0#6f0#6f6#6f8#6fa#6fd#6ff#0df
#f0a#d08#a06#800#860#880#8a0#8d0#8f0#8f6#8f8#8fa#8fd#8ff#6df#0af
#f08#d06#a00#a60#a80#aa0#ad0#af0#af6#af8#afa#afd#aff#8df#6af#08f
#f06#d00#d60#d80#da0#dd0#df0#df6#df8#dfa#dfd#dff#adf#8af#68f#06f
#f00#f60#f80#fa0#fd0#ff0#ff6#ff8#ffa#ffd#fff#ddf#aaf#88f#66f#00f
#fd0#fd6#fd8#fda#fdd#fdf#daf#a8f#86f#60f
#66d#68d#6ad#6dd #fa0#fa6#fa8#faa#fad#faf#d8f#a6f#80f
#86d#66a#68a#6aa#6da #f80#f86#f88#f8a#f8d#f8f#d6f#a0f
#a6d#86a#668#688#6a8#6d8 #f60#f66#f68#f6a#f6d#f6f#d0f
#d6d#a6a#868#666#686#6a6#6d6#6d8#6da#6dd #f00#f06#f08#f0a#f0d#f0f
#d6a#a68#866#886#8a6#8d6#8d8#8da#8dd#6ad
#d68#a66#a86#aa6#ad6#ad8#ada#add#8ad#68d
#d66#d86#da6#dd6#dd8#dda#ddd#aad#88d#66d g78_g82_g85_g89_g93_g100
#da6#da8#daa#dad#a8d#86d g52_g58_g62_g66_g70_g74_
#88a#8aa #d86#d88#d8a#d8d#a6d g27_g31_g35_g38_g42_g46_g50_
#a8a#888#8a8#8aa #d66#d68#d6a#d6d g0__g3__g7__g11_g15_g19_g23_
#a88#aa8#aaa#88a
#a88#a8a
"""
CHART_88 = """
brown__ dark_red_ dark_magenta_ dark_blue_ dark_cyan_ dark_green_
yellow_ light_red light_magenta light_blue light_cyan light_green
#00f#08f#0cf#0ff black_______ dark_gray___
#80f#00c#08c#0cc#0fc light_gray__ white_______
#c0f#80c#008#088#0c8#0f8
#f0f#c0c#808#000#080#0c0#0f0#0f8#0fc#0ff #88c#8cc
#f0c#c08#800#880#8c0#8f0#8f8#8fc#8ff#0cf #c8c#888#8c8#8cc
#f08#c00#c80#cc0#cf0#cf8#cfc#cff#8cf#08f #c88#cc8#ccc#88c
#f00#f80#fc0#ff0#ff8#ffc#fff#ccf#88f#00f #c88#c8c
#fc0#fc8#fcc#fcf#c8f#80f
#f80#f88#f8c#f8f#c0f g62_g74_g82_g89_g100
#f00#f08#f0c#f0f g0__g19_g35_g46_g52
"""
CHART_16 = """
brown__ dark_red_ dark_magenta_ dark_blue_ dark_cyan_ dark_green_
yellow_ light_red light_magenta light_blue light_cyan light_green
black_______ dark_gray___ light_gray__ white_______
"""
ATTR_RE = re.compile("(?P<whitespace>[ \n]*)(?P<entry>(?:#[0-9A-Fa-f]{6})|(?:#[0-9A-Fa-f]{3})|(?:[^ \n]+))")
LONG_ATTR = 7
SHORT_ATTR = 4 # length of short high-colour descriptions which may
# be packed one after the next
def parse_chart(chart: str, convert):
"""
Convert string chart into text markup with the correct attributes.
chart -- palette chart as a string
convert -- function that converts a single palette entry to an
(attr, text) tuple, or None if no match is found
"""
out = []
for match in ATTR_RE.finditer(chart):
if match.group("whitespace"):
out.append(match.group("whitespace"))
entry = match.group("entry")
entry = entry.replace("_", " ")
while entry:
if chart == CHART_TRUE and len(entry) == LONG_ATTR:
attrtext = convert(entry[:LONG_ATTR])
elen = LONG_ATTR
else:
elen = SHORT_ATTR
attrtext = convert(entry[:SHORT_ATTR])
# try the first four characters
if attrtext:
entry = entry[elen:].strip()
else: # try the whole thing
attrtext = convert(entry.strip())
assert attrtext, f"Invalid palette entry: {entry!r}" # noqa: S101 # "assert" is ok for examples
elen = len(entry)
entry = ""
attr, text = attrtext
if chart == CHART_TRUE:
out.append((attr, "â–„"))
else:
out.append((attr, text.ljust(elen)))
return out
def foreground_chart(chart: str, background, colors: Literal[1, 16, 88, 256, 16777216]):
"""
Create text markup for a foreground colour chart
chart -- palette chart as string
background -- colour to use for background of chart
colors -- number of colors (88 or 256)
"""
def convert_foreground(entry):
try:
attr = urwid.AttrSpec(entry, background, colors)
except urwid.AttrSpecError:
return None
return attr, entry
return parse_chart(chart, convert_foreground)
def background_chart(chart: str, foreground, colors: Literal[1, 16, 88, 256, 16777216]):
"""
Create text markup for a background colour chart
chart -- palette chart as string
foreground -- colour to use for foreground of chart
colors -- number of colors (88 or 256)
This will remap 8 <= colour < 16 to high-colour versions
in the hopes of greater compatibility
"""
def convert_background(entry):
try:
attr = urwid.AttrSpec(foreground, entry, colors)
except urwid.AttrSpecError:
return None
# fix 8 <= colour < 16
if colors > 16 and attr.background_basic and attr.background_number >= 8:
# use high-colour with same number
entry = f"h{attr.background_number:d}"
attr = urwid.AttrSpec(foreground, entry, colors)
return attr, entry
return parse_chart(chart, convert_background)
def main() -> None:
palette = [
("header", "black,underline", "light gray", "standout,underline", "black,underline", "#88a"),
("panel", "light gray", "dark blue", "", "#ffd", "#00a"),
("focus", "light gray", "dark cyan", "standout", "#ff8", "#806"),
]
screen = urwid.display.raw.Screen()
screen.register_palette(palette)
lb = urwid.SimpleListWalker([])
chart_offset = None # offset of chart in lb list
mode_radio_buttons = []
chart_radio_buttons = []
def fcs(widget) -> urwid.AttrMap:
# wrap widgets that can take focus
return urwid.AttrMap(widget, None, "focus")
def set_mode(colors: int, is_foreground_chart: bool) -> None:
# set terminal mode and redraw chart
screen.set_terminal_properties(colors)
screen.reset_default_terminal_palette()
chart_fn = (background_chart, foreground_chart)[is_foreground_chart]
if colors == 1:
lb[chart_offset] = urwid.Divider()
else:
chart: str = {16: CHART_16, 88: CHART_88, 256: CHART_256, 2**24: CHART_TRUE}[colors]
txt = chart_fn(chart, "default", colors)
lb[chart_offset] = urwid.Text(txt, wrap=urwid.CLIP)
def on_mode_change(colors: int, rb: urwid.RadioButton, state: bool) -> None:
# if this radio button is checked
if state:
is_foreground_chart = chart_radio_buttons[0].state
set_mode(colors, is_foreground_chart)
def mode_rb(text: str, colors: int, state: bool = False) -> urwid.AttrMap:
# mode radio buttons
rb = urwid.RadioButton(mode_radio_buttons, text, state)
urwid.connect_signal(rb, "change", on_mode_change, user_args=(colors,))
return fcs(rb)
def on_chart_change(rb: urwid.RadioButton, state: bool) -> None:
# handle foreground check box state change
set_mode(screen.colors, state)
def click_exit(button) -> typing.NoReturn:
raise urwid.ExitMainLoop()
lb.extend(
[
urwid.AttrMap(urwid.Text("Urwid Palette Test"), "header"),
urwid.AttrMap(
urwid.Columns(
[
urwid.Pile(
[
mode_rb("Monochrome", 1),
mode_rb("16-Color", 16, True),
mode_rb("88-Color", 88),
mode_rb("256-Color", 256),
mode_rb("24-bit Color", 2**24),
]
),
urwid.Pile(
[
fcs(urwid.RadioButton(chart_radio_buttons, "Foreground Colors", True, on_chart_change)),
fcs(urwid.RadioButton(chart_radio_buttons, "Background Colors")),
urwid.Divider(),
fcs(urwid.Button("Exit", click_exit)),
]
),
]
),
"panel",
),
]
)
chart_offset = len(lb)
lb.extend([urwid.Divider()]) # placeholder for the chart
set_mode(16, True) # displays the chart
def unhandled_input(key: str | tuple[str, int, int, int]) -> None:
if key in {"Q", "q", "esc"}:
raise urwid.ExitMainLoop()
urwid.MainLoop(urwid.ListBox(lb), screen=screen, unhandled_input=unhandled_input).run()
if __name__ == "__main__":
main()
| 21,848 | Python | .py | 392 | 49.877551 | 120 | 0.720131 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,178 | graph.py.xdotool | urwid_urwid/docs/examples/graph.py.xdotool | windowsize --usehints $RXVTWINDOWID 79 24
key --window $RXVTWINDOWID Down Down Down Return
| 91 | Python | .py | 2 | 44.5 | 48 | 0.820225 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,179 | tour.py.xdotool | urwid_urwid/docs/examples/tour.py.xdotool | windowsize --usehints $RXVTWINDOWID 39 25
key --window $RXVTWINDOWID Return End
| 80 | Python | .py | 2 | 39 | 41 | 0.820513 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,180 | bigtext.py.xdotool | urwid_urwid/docs/examples/bigtext.py.xdotool | windowsize --usehints $RXVTWINDOWID 39 21
key --window $RXVTWINDOWID Down Down Down Down Down Down Down Down Return
key --window $RXVTWINDOWID Up Up Up Return
| 159 | Python | .py | 3 | 52 | 73 | 0.807692 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,181 | subproc2.py | urwid_urwid/docs/examples/subproc2.py | from __future__ import annotations
import time
time.sleep(1)
print(
"""factor: 1
factor: 1000003
factor: 2000029
factor: 3000073
factor: 4000159
factor: 5000101"""
)
| 173 | Python | .py | 11 | 14.090909 | 34 | 0.779874 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,182 | cmenu.py | urwid_urwid/docs/tutorial/cmenu.py | from __future__ import annotations
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Callable, Hashable, Iterable
def menu_button(
caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
callback: Callable[[urwid.Button], typing.Any],
) -> urwid.AttrMap:
button = urwid.Button(caption, on_press=callback)
return urwid.AttrMap(button, None, focus_map="reversed")
def sub_menu(
caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
choices: Iterable[urwid.Widget],
) -> urwid.Widget:
contents = menu(caption, choices)
def open_menu(button: urwid.Button) -> None:
return top.open_box(contents)
return menu_button([caption, "..."], open_menu)
def menu(
title: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
choices: Iterable[urwid.Widget],
) -> urwid.ListBox:
body = [urwid.Text(title), urwid.Divider(), *choices]
return urwid.ListBox(urwid.SimpleFocusListWalker(body))
def item_chosen(button: urwid.Button) -> None:
response = urwid.Text(["You chose ", button.label, "\n"])
done = menu_button("Ok", exit_program)
top.open_box(urwid.Filler(urwid.Pile([response, done])))
def exit_program(button: urwid.Button) -> typing.NoReturn:
raise urwid.ExitMainLoop()
menu_top = menu(
"Main Menu",
[
sub_menu(
"Applications",
[
sub_menu(
"Accessories",
[
menu_button("Text Editor", item_chosen),
menu_button("Terminal", item_chosen),
],
),
],
),
sub_menu(
"System",
[
sub_menu(
"Preferences",
[menu_button("Appearance", item_chosen)],
),
menu_button("Lock Screen", item_chosen),
],
),
],
)
class CascadingBoxes(urwid.WidgetPlaceholder):
max_box_levels = 4
def __init__(self, box: urwid.Widget) -> None:
super().__init__(urwid.SolidFill("/"))
self.box_level = 0
self.open_box(box)
def open_box(self, box: urwid.Widget) -> None:
self.original_widget = urwid.Overlay(
urwid.LineBox(box),
self.original_widget,
align=urwid.CENTER,
width=(urwid.RELATIVE, 80),
valign=urwid.MIDDLE,
height=(urwid.RELATIVE, 80),
min_width=24,
min_height=8,
left=self.box_level * 3,
right=(self.max_box_levels - self.box_level - 1) * 3,
top=self.box_level * 2,
bottom=(self.max_box_levels - self.box_level - 1) * 2,
)
self.box_level += 1
def keypress(self, size, key: str) -> str | None:
if key == "esc" and self.box_level > 1:
self.original_widget = self.original_widget[0]
self.box_level -= 1
return None
return super().keypress(size, key)
top = CascadingBoxes(menu_top)
urwid.MainLoop(top, palette=[("reversed", "standout", "")]).run()
| 3,188 | Python | .py | 88 | 27.170455 | 75 | 0.571057 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,183 | sig.py.xdotool | urwid_urwid/docs/tutorial/sig.py.xdotool | windowsize --usehints $RXVTWINDOWID 21 7
type --window $RXVTWINDOWID 'Tim t'
type --window $RXVTWINDOWID 'he Enchanter'
key --window $RXVTWINDOWID Down
| 152 | Python | .py | 4 | 37 | 42 | 0.790541 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,184 | hmenu.py.xdotool | urwid_urwid/docs/tutorial/hmenu.py.xdotool | windowsize --usehints $RXVTWINDOWID 80 12
key --window $RXVTWINDOWID Return
key --window $RXVTWINDOWID Return Down
key --window $RXVTWINDOWID Return
| 149 | Python | .py | 4 | 36.25 | 41 | 0.82069 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,185 | minimal.py | urwid_urwid/docs/tutorial/minimal.py | from __future__ import annotations
import urwid
txt = urwid.Text("Hello World")
fill = urwid.Filler(txt, "top")
loop = urwid.MainLoop(fill)
loop.run()
| 153 | Python | .py | 6 | 24.166667 | 34 | 0.751724 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,186 | input.py | urwid_urwid/docs/tutorial/input.py | from __future__ import annotations
import urwid
def show_or_exit(key: str) -> None:
if key in {"q", "Q"}:
raise urwid.ExitMainLoop()
txt.set_text(repr(key))
txt = urwid.Text("Hello World")
fill = urwid.Filler(txt, "top")
loop = urwid.MainLoop(fill, unhandled_input=show_or_exit)
loop.run()
| 311 | Python | .py | 10 | 28 | 57 | 0.689189 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,187 | qa.py.xdotool | urwid_urwid/docs/tutorial/qa.py.xdotool | windowsize --usehints $RXVTWINDOWID 21 7
type --window $RXVTWINDOWID 'Arthur, King of the Britons'
key --window $RXVTWINDOWID Return
| 133 | Python | .py | 3 | 43.333333 | 57 | 0.8 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,188 | cmenu.py.xdotool | urwid_urwid/docs/tutorial/cmenu.py.xdotool | windowsize --usehints $RXVTWINDOWID 33 14
key --window $RXVTWINDOWID Return
key --window $RXVTWINDOWID Return Down
key --window $RXVTWINDOWID Return
| 149 | Python | .py | 4 | 36.25 | 41 | 0.82069 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,189 | multiple.py.xdotool | urwid_urwid/docs/tutorial/multiple.py.xdotool | windowsize --usehints $RXVTWINDOWID 23 13
key --window $RXVTWINDOWID A b e Return B o b
key --window $RXVTWINDOWID Return C a r l Return
key --window $RXVTWINDOWID D a v e Return
| 179 | Python | .py | 4 | 43.75 | 48 | 0.771429 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,190 | adventure.py.xdotool | urwid_urwid/docs/tutorial/adventure.py.xdotool | windowsize --usehints $RXVTWINDOWID 23 16
key --window $RXVTWINDOWID Return Down Down
key --window $RXVTWINDOWID Return Down
key --window $RXVTWINDOWID Return
| 159 | Python | .py | 4 | 38.75 | 43 | 0.819355 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,191 | urwid_attr.py | urwid_urwid/docs/tutorial/urwid_attr.py | from __future__ import annotations
import urwid
def exit_on_q(key: str) -> None:
if key in {"q", "Q"}:
raise urwid.ExitMainLoop()
palette = [
("banner", "black", "light gray"),
("streak", "black", "dark red"),
("bg", "black", "dark blue"),
]
txt = urwid.Text(("banner", " Hello World "), align="center")
map1 = urwid.AttrMap(txt, "streak")
fill = urwid.Filler(map1)
map2 = urwid.AttrMap(fill, "bg")
loop = urwid.MainLoop(map2, palette, unhandled_input=exit_on_q)
loop.run()
| 504 | Python | .py | 16 | 28.625 | 63 | 0.643154 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,192 | input.py.xdotool | urwid_urwid/docs/tutorial/input.py.xdotool | windowsize --usehints $RXVTWINDOWID 12 3
key --window $RXVTWINDOWID Return
key --window $RXVTWINDOWID N
key --window $RXVTWINDOWID O
key --window $RXVTWINDOWID P
| 162 | Python | .py | 5 | 31.4 | 40 | 0.802548 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,193 | multiple.py | urwid_urwid/docs/tutorial/multiple.py | from __future__ import annotations
import urwid
def question():
return urwid.Pile([urwid.Edit(("I say", "What is your name?\n"))])
def answer(name):
return urwid.Text(("I say", f"Nice to meet you, {name}\n"))
class ConversationListBox(urwid.ListBox):
def __init__(self) -> None:
body = urwid.SimpleFocusListWalker([question()])
super().__init__(body)
def keypress(self, size: tuple[int, int], key: str) -> str | None:
key = super().keypress(size, key)
if key != "enter":
return key
name = self.focus[0].edit_text
if not name:
raise urwid.ExitMainLoop()
# replace or add response
self.focus.contents[1:] = [(answer(name), self.focus.options())]
pos = self.focus_position
# add a new question
self.body.insert(pos + 1, question())
self.focus_position = pos + 1
return None
palette = [("I say", "default,bold", "default")]
urwid.MainLoop(ConversationListBox(), palette).run()
| 1,027 | Python | .py | 26 | 32.576923 | 72 | 0.61554 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,194 | hmenu.py | urwid_urwid/docs/tutorial/hmenu.py | from __future__ import annotations
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Callable, Hashable, Iterable
class MenuButton(urwid.Button):
def __init__(
self,
caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
callback: Callable[[MenuButton], typing.Any],
) -> None:
super().__init__("", on_press=callback)
self._w = urwid.AttrMap(
urwid.SelectableIcon([" \N{BULLET} ", caption], 2),
None,
"selected",
)
class SubMenu(urwid.WidgetWrap[MenuButton]):
def __init__(
self,
caption: str | tuple[Hashable, str],
choices: Iterable[urwid.Widget],
) -> None:
super().__init__(MenuButton([caption, "\N{HORIZONTAL ELLIPSIS}"], self.open_menu))
line = urwid.Divider("\N{LOWER ONE QUARTER BLOCK}")
listbox = urwid.ListBox(
urwid.SimpleFocusListWalker(
[
urwid.AttrMap(urwid.Text(["\n ", caption]), "heading"),
urwid.AttrMap(line, "line"),
urwid.Divider(),
*choices,
urwid.Divider(),
]
)
)
self.menu = urwid.AttrMap(listbox, "options")
def open_menu(self, button: MenuButton) -> None:
top.open_box(self.menu)
class Choice(urwid.WidgetWrap[MenuButton]):
def __init__(
self,
caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
) -> None:
super().__init__(MenuButton(caption, self.item_chosen))
self.caption = caption
def item_chosen(self, button: MenuButton) -> None:
response = urwid.Text([" You chose ", self.caption, "\n"])
done = MenuButton("Ok", exit_program)
response_box = urwid.Filler(urwid.Pile([response, done]))
top.open_box(urwid.AttrMap(response_box, "options"))
def exit_program(key):
raise urwid.ExitMainLoop()
menu_top = SubMenu(
"Main Menu",
[
SubMenu(
"Applications",
[
SubMenu(
"Accessories",
[
Choice("Text Editor"),
Choice("Terminal"),
],
)
],
),
SubMenu(
"System",
[
SubMenu("Preferences", [Choice("Appearance")]),
Choice("Lock Screen"),
],
),
],
)
palette = [
(None, "light gray", "black"),
("heading", "black", "light gray"),
("line", "black", "light gray"),
("options", "dark gray", "black"),
("focus heading", "white", "dark red"),
("focus line", "black", "dark red"),
("focus options", "black", "light gray"),
("selected", "white", "dark blue"),
]
focus_map = {"heading": "focus heading", "options": "focus options", "line": "focus line"}
class HorizontalBoxes(urwid.Columns):
def __init__(self) -> None:
super().__init__([], dividechars=1)
def open_box(self, box: urwid.Widget) -> None:
if self.contents:
del self.contents[self.focus_position + 1 :]
self.contents.append(
(
urwid.AttrMap(box, "options", focus_map),
self.options(urwid.GIVEN, 24),
)
)
self.focus_position = len(self.contents) - 1
top = HorizontalBoxes()
top.open_box(menu_top.menu)
urwid.MainLoop(urwid.Filler(top, "middle", 10), palette).run()
| 3,577 | Python | .py | 104 | 25 | 90 | 0.535921 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,195 | sig.py | urwid_urwid/docs/tutorial/sig.py | from __future__ import annotations
import typing
import urwid
palette = [("I say", "default,bold", "default", "bold")]
ask = urwid.Edit(("I say", "What is your name?\n"))
reply = urwid.Text("")
button_inst = urwid.Button("Exit")
div = urwid.Divider()
pile = urwid.Pile([ask, div, reply, div, button_inst])
top = urwid.Filler(pile, valign="top")
def on_ask_change(_edit: urwid.Edit, new_edit_text: str) -> None:
reply.set_text(("I say", f"Nice to meet you, {new_edit_text}"))
def on_exit_clicked(_button: urwid.Button) -> typing.NoReturn:
raise urwid.ExitMainLoop()
urwid.connect_signal(ask, "change", on_ask_change)
urwid.connect_signal(button_inst, "click", on_exit_clicked)
urwid.MainLoop(top, palette).run()
| 729 | Python | .py | 17 | 40.823529 | 67 | 0.707977 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,196 | smenu.py.xdotool | urwid_urwid/docs/tutorial/smenu.py.xdotool | windowsize --usehints $RXVTWINDOWID 24 11
key --window $RXVTWINDOWID Down Down Down
key --window $RXVTWINDOWID Return
| 118 | Python | .py | 3 | 38.333333 | 41 | 0.817391 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,197 | qa.py | urwid_urwid/docs/tutorial/qa.py | from __future__ import annotations
import urwid
def exit_on_q(key: str) -> None:
if key in {"q", "Q"}:
raise urwid.ExitMainLoop()
class QuestionBox(urwid.Filler):
def keypress(self, size, key: str) -> str | None:
if key != "enter":
return super().keypress(size, key)
self.original_widget = urwid.Text(
f"Nice to meet you,\n{edit.edit_text}.\n\nPress Q to exit.",
)
return None
edit = urwid.Edit("What is your name?\n")
fill = QuestionBox(edit)
loop = urwid.MainLoop(fill, unhandled_input=exit_on_q)
loop.run()
| 589 | Python | .py | 17 | 29 | 72 | 0.633628 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,198 | highcolors.py | urwid_urwid/docs/tutorial/highcolors.py | from __future__ import annotations
import urwid
def exit_on_q(key):
if key in {"q", "Q"}:
raise urwid.ExitMainLoop()
palette = [
("banner", "", "", "", "#ffa", "#60d"),
("streak", "", "", "", "g50", "#60a"),
("inside", "", "", "", "g38", "#808"),
("outside", "", "", "", "g27", "#a06"),
("bg", "", "", "", "g7", "#d06"),
]
placeholder = urwid.SolidFill()
loop = urwid.MainLoop(placeholder, palette, unhandled_input=exit_on_q)
loop.screen.set_terminal_properties(colors=256)
loop.widget = urwid.AttrMap(placeholder, "bg")
loop.widget.original_widget = urwid.Filler(urwid.Pile([]))
div = urwid.Divider()
outside = urwid.AttrMap(div, "outside")
inside = urwid.AttrMap(div, "inside")
txt = urwid.Text(("banner", " Hello World "), align="center")
streak = urwid.AttrMap(txt, "streak")
pile = loop.widget.base_widget # .base_widget skips the decorations
for item in (outside, inside, streak, inside, outside):
pile.contents.append((item, pile.options()))
loop.run()
| 1,005 | Python | .py | 26 | 35.961538 | 70 | 0.634398 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
1,199 | adventure.py | urwid_urwid/docs/tutorial/adventure.py | from __future__ import annotations
import typing
import urwid
if typing.TYPE_CHECKING:
from collections.abc import Callable, Hashable, MutableSequence
class ActionButton(urwid.Button):
def __init__(
self,
caption: str | tuple[Hashable, str] | list[str | tuple[Hashable, str]],
callback: Callable[[ActionButton], typing.Any],
) -> None:
super().__init__("", on_press=callback)
self._w = urwid.AttrMap(urwid.SelectableIcon(caption, 1), None, focus_map="reversed")
class Place(urwid.WidgetWrap[ActionButton]):
def __init__(self, name: str, choices: MutableSequence[urwid.Widget]) -> None:
super().__init__(ActionButton([" > go to ", name], self.enter_place))
self.heading = urwid.Text(["\nLocation: ", name, "\n"])
self.choices = choices
# create links back to ourself
for child in choices:
getattr(child, "choices", []).insert(0, self)
def enter_place(self, button: ActionButton) -> None:
game.update_place(self)
class Thing(urwid.WidgetWrap[ActionButton]):
def __init__(self, name: str) -> None:
super().__init__(ActionButton([" * take ", name], self.take_thing))
self.name = name
def take_thing(self, button: ActionButton) -> None:
self._w = urwid.Text(f" - {self.name} (taken)")
game.take_thing(self)
def exit_program(button: ActionButton) -> typing.NoReturn:
raise urwid.ExitMainLoop()
map_top = Place(
"porch",
[
Place(
"kitchen",
[
Place("refrigerator", []),
Place("cupboard", [Thing("jug")]),
],
),
Place(
"garden",
[
Place(
"tree",
[
Thing("lemon"),
Thing("bird"),
],
),
],
),
Place(
"street",
[
Place("store", [Thing("sugar")]),
Place(
"lake",
[Place("beach", [])],
),
],
),
],
)
class AdventureGame:
def __init__(self) -> None:
self.log = urwid.SimpleFocusListWalker([])
self.top = urwid.ListBox(self.log)
self.inventory = set()
self.update_place(map_top)
def update_place(self, place: Place) -> None:
if self.log: # disable interaction with previous place
self.log[-1] = urwid.WidgetDisable(self.log[-1])
self.log.append(urwid.Pile([place.heading, *place.choices]))
self.top.focus_position = len(self.log) - 1
self.place = place
def take_thing(self, thing: Thing) -> None:
self.inventory.add(thing.name)
if self.inventory >= {"sugar", "lemon", "jug"}:
response = urwid.Text("You can make lemonade!\n")
done = ActionButton(" - Joy", exit_program)
self.log[:] = [response, done]
else:
self.update_place(self.place)
game = AdventureGame()
urwid.MainLoop(game.top, palette=[("reversed", "standout", "")]).run()
| 3,190 | Python | .py | 88 | 26.465909 | 93 | 0.540734 | urwid/urwid | 2,793 | 312 | 124 | LGPL-2.1 | 9/5/2024, 5:08:50 PM (Europe/Amsterdam) |
Subsets and Splits