core, setup: huge cleaning:

- moved directories from src and frontends/src to sat and sat_frontends, which is the recommanded naming convention
- move twisted directory to root
- removed all hacks from setup.py, and added missing dependencies, it is now clean
- use https URL for website in setup.py
- removed "Environment :: X11 Applications :: GTK", as wix is deprecated and removed
- renamed sat.sh to sat and fixed its installation
- added python_requires to specify Python version needed
- replaced glib2reactor which use deprecated code by gtk3reactor

sat can now be installed directly from virtualenv without using --system-site-packages anymore \o/
This commit is contained in:
Goffi 2018-04-02 19:44:50 +02:00
commit 80ef13612b
10 changed files with 42 additions and 269 deletions

View file

View file

@ -0,0 +1,113 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Libervia: a Salut à Toi frontend
Copyright (C) 2013-2016 Adrien Cossa <souliane@mailoo.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
# Map the messages recipient types to their properties.
RECIPIENT_TYPES = {"To": {"desc": "Direct recipients", "optional": False},
"Cc": {"desc": "Carbon copies", "optional": True},
"Bcc": {"desc": "Blind carbon copies", "optional": True}}
# Rich text buttons icons and descriptions
RICH_BUTTONS = {
"bold": {"tip": "Bold", "icon": "media/icons/dokuwiki/toolbar/16/bold.png"},
"italic": {"tip": "Italic", "icon": "media/icons/dokuwiki/toolbar/16/italic.png"},
"underline": {"tip": "Underline", "icon": "media/icons/dokuwiki/toolbar/16/underline.png"},
"code": {"tip": "Code", "icon": "media/icons/dokuwiki/toolbar/16/mono.png"},
"strikethrough": {"tip": "Strikethrough", "icon": "media/icons/dokuwiki/toolbar/16/strike.png"},
"heading": {"tip": "Heading", "icon": "media/icons/dokuwiki/toolbar/16/hequal.png"},
"numberedlist": {"tip": "Numbered List", "icon": "media/icons/dokuwiki/toolbar/16/ol.png"},
"list": {"tip": "List", "icon": "media/icons/dokuwiki/toolbar/16/ul.png"},
"link": {"tip": "Link", "icon": "media/icons/dokuwiki/toolbar/16/linkextern.png"},
"horizontalrule": {"tip": "Horizontal rule", "icon": "media/icons/dokuwiki/toolbar/16/hr.png"},
"image": {"tip": "Image", "icon": "media/icons/dokuwiki/toolbar/16/image.png"},
}
# Define here your rich text syntaxes, the key must match the ones used in button.
# Tupples values must have 3 elements : prefix to the selection or cursor
# position, sample text to write if the marker is not applied on a selection,
# suffix to the selection or cursor position.
# FIXME: must not be hard-coded like this
RICH_SYNTAXES = {"markdown": {"bold": ("**", "bold", "**"),
"italic": ("*", "italic", "*"),
"code": ("`", "code", "`"),
"heading": ("\n# ", "Heading 1", "\n## Heading 2\n"),
"link": ("[desc](", "link", ")"),
"list": ("\n* ", "item", "\n + subitem\n"),
"horizontalrule": ("\n***\n", "", ""),
"image": ("![desc](", "path", ")"),
},
"bbcode": {"bold": ("[b]", "bold", "[/b]"),
"italic": ("[i]", "italic", "[/i]"),
"underline": ("[u]", "underline", "[/u]"),
"code": ("[code]", "code", "[/code]"),
"strikethrough": ("[s]", "strikethrough", "[/s]"),
"link": ("[url=", "link", "]desc[/url]"),
"list": ("\n[list] [*]", "item 1", " [*]item 2 [/list]\n"),
"image": ("[img alt=\"desc\]", "path", "[/img]"),
},
"dokuwiki": {"bold": ("**", "bold", "**"),
"italic": ("//", "italic", "//"),
"underline": ("__", "underline", "__"),
"code": ("<code>", "code", "</code>"),
"strikethrough": ("<del>", "strikethrough", "</del>"),
"heading": ("\n==== ", "Heading 1", " ====\n=== Heading 2 ===\n"),
"link": ("[[", "link", "|desc]]"),
"list": ("\n * ", "item\n", "\n * subitem\n"),
"horizontalrule": ("\n----\n", "", ""),
"image": ("{{", "path", " |desc}}"),
},
"XHTML": {"bold": ("<b>", "bold", "</b>"),
"italic": ("<i>", "italic", "</i>"),
"underline": ("<u>", "underline", "</u>"),
"code": ("<pre>", "code", "</pre>"),
"strikethrough": ("<s>", "strikethrough", "</s>"),
"heading": ("\n<h3>", "Heading 1", "</h3>\n<h4>Heading 2</h4>\n"),
"link": ("<a href=\"", "link", "\">desc</a>"),
"list": ("\n<ul><li>", "item 1", "</li><li>item 2</li></ul>\n"),
"horizontalrule": ("\n<hr/>\n", "", ""),
"image": ("<img src=\"", "path", "\" alt=\"desc\"/>"),
}
}
# Define here the commands that are supported by the WYSIWYG edition.
# Keys must be the same than the ones used in RICH_SYNTAXES["XHTML"].
# Values will be used to call execCommand(cmd, False, arg), they can be:
# - a string used for cmd and arg is assumed empty
# - a tuple (cmd, prompt, arg) with cmd the name of the command,
# prompt the text to display for asking a user input and arg is the
# value to use directly without asking the user if prompt is empty.
COMMANDS = {"bold": "bold",
"italic": "italic",
"underline": "underline",
"code": ("formatBlock", "", "pre"),
"strikethrough": "strikeThrough",
"heading": ("heading", "Please specify the heading level (h1, h2, h3...)", ""),
"link": ("createLink", "Please specify an URL", ""),
"list": "insertUnorderedList",
"horizontalrule": "insertHorizontalRule",
"image": ("insertImage", "Please specify an image path", ""),
}
# These values should be equal to the ones in plugin_misc_text_syntaxes
# FIXME: should the plugin import them from here to avoid duplicity? Importing
# the plugin's values from here is not possible because Libervia would fail.
PARAM_KEY_COMPOSITION = "Composition"
PARAM_NAME_SYNTAX = "Syntax"

View file

@ -0,0 +1,239 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# CSS color parsing
# Copyright (C) 2009-2018 Jérome-Poisson
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.log import getLogger
log = getLogger(__name__)
CSS_COLORS = {
u"black": u"000000",
u"silver": u"c0c0c0",
u"gray": u"808080",
u"white": u"ffffff",
u"maroon": u"800000",
u"red": u"ff0000",
u"purple": u"800080",
u"fuchsia": u"ff00ff",
u"green": u"008000",
u"lime": u"00ff00",
u"olive": u"808000",
u"yellow": u"ffff00",
u"navy": u"000080",
u"blue": u"0000ff",
u"teal": u"008080",
u"aqua": u"00ffff",
u"orange": u"ffa500",
u"aliceblue": u"f0f8ff",
u"antiquewhite": u"faebd7",
u"aquamarine": u"7fffd4",
u"azure": u"f0ffff",
u"beige": u"f5f5dc",
u"bisque": u"ffe4c4",
u"blanchedalmond": u"ffebcd",
u"blueviolet": u"8a2be2",
u"brown": u"a52a2a",
u"burlywood": u"deb887",
u"cadetblue": u"5f9ea0",
u"chartreuse": u"7fff00",
u"chocolate": u"d2691e",
u"coral": u"ff7f50",
u"cornflowerblue": u"6495ed",
u"cornsilk": u"fff8dc",
u"crimson": u"dc143c",
u"darkblue": u"00008b",
u"darkcyan": u"008b8b",
u"darkgoldenrod": u"b8860b",
u"darkgray": u"a9a9a9",
u"darkgreen": u"006400",
u"darkgrey": u"a9a9a9",
u"darkkhaki": u"bdb76b",
u"darkmagenta": u"8b008b",
u"darkolivegreen": u"556b2f",
u"darkorange": u"ff8c00",
u"darkorchid": u"9932cc",
u"darkred": u"8b0000",
u"darksalmon": u"e9967a",
u"darkseagreen": u"8fbc8f",
u"darkslateblue": u"483d8b",
u"darkslategray": u"2f4f4f",
u"darkslategrey": u"2f4f4f",
u"darkturquoise": u"00ced1",
u"darkviolet": u"9400d3",
u"deeppink": u"ff1493",
u"deepskyblue": u"00bfff",
u"dimgray": u"696969",
u"dimgrey": u"696969",
u"dodgerblue": u"1e90ff",
u"firebrick": u"b22222",
u"floralwhite": u"fffaf0",
u"forestgreen": u"228b22",
u"gainsboro": u"dcdcdc",
u"ghostwhite": u"f8f8ff",
u"gold": u"ffd700",
u"goldenrod": u"daa520",
u"greenyellow": u"adff2f",
u"grey": u"808080",
u"honeydew": u"f0fff0",
u"hotpink": u"ff69b4",
u"indianred": u"cd5c5c",
u"indigo": u"4b0082",
u"ivory": u"fffff0",
u"khaki": u"f0e68c",
u"lavender": u"e6e6fa",
u"lavenderblush": u"fff0f5",
u"lawngreen": u"7cfc00",
u"lemonchiffon": u"fffacd",
u"lightblue": u"add8e6",
u"lightcoral": u"f08080",
u"lightcyan": u"e0ffff",
u"lightgoldenrodyellow": u"fafad2",
u"lightgray": u"d3d3d3",
u"lightgreen": u"90ee90",
u"lightgrey": u"d3d3d3",
u"lightpink": u"ffb6c1",
u"lightsalmon": u"ffa07a",
u"lightseagreen": u"20b2aa",
u"lightskyblue": u"87cefa",
u"lightslategray": u"778899",
u"lightslategrey": u"778899",
u"lightsteelblue": u"b0c4de",
u"lightyellow": u"ffffe0",
u"limegreen": u"32cd32",
u"linen": u"faf0e6",
u"mediumaquamarine": u"66cdaa",
u"mediumblue": u"0000cd",
u"mediumorchid": u"ba55d3",
u"mediumpurple": u"9370db",
u"mediumseagreen": u"3cb371",
u"mediumslateblue": u"7b68ee",
u"mediumspringgreen": u"00fa9a",
u"mediumturquoise": u"48d1cc",
u"mediumvioletred": u"c71585",
u"midnightblue": u"191970",
u"mintcream": u"f5fffa",
u"mistyrose": u"ffe4e1",
u"moccasin": u"ffe4b5",
u"navajowhite": u"ffdead",
u"oldlace": u"fdf5e6",
u"olivedrab": u"6b8e23",
u"orangered": u"ff4500",
u"orchid": u"da70d6",
u"palegoldenrod": u"eee8aa",
u"palegreen": u"98fb98",
u"paleturquoise": u"afeeee",
u"palevioletred": u"db7093",
u"papayawhip": u"ffefd5",
u"peachpuff": u"ffdab9",
u"peru": u"cd853f",
u"pink": u"ffc0cb",
u"plum": u"dda0dd",
u"powderblue": u"b0e0e6",
u"rosybrown": u"bc8f8f",
u"royalblue": u"4169e1",
u"saddlebrown": u"8b4513",
u"salmon": u"fa8072",
u"sandybrown": u"f4a460",
u"seagreen": u"2e8b57",
u"seashell": u"fff5ee",
u"sienna": u"a0522d",
u"skyblue": u"87ceeb",
u"slateblue": u"6a5acd",
u"slategray": u"708090",
u"slategrey": u"708090",
u"snow": u"fffafa",
u"springgreen": u"00ff7f",
u"steelblue": u"4682b4",
u"tan": u"d2b48c",
u"thistle": u"d8bfd8",
u"tomato": u"ff6347",
u"turquoise": u"40e0d0",
u"violet": u"ee82ee",
u"wheat": u"f5deb3",
u"whitesmoke": u"f5f5f5",
u"yellowgreen": u"9acd32",
u"rebeccapurple": u"663399"
}
DEFAULT = u"000000"
def parse(raw_value, as_string=True):
"""parse CSS color value and return normalised value
@param raw_value(unicode): CSS value
@param as_string(bool): if True return a string,
else return a tuple of int
@return (unicode, tuple): normalised value
if as_string is True, value is 3 or 4 hex words (e.g. u"ff00aabb")
else value is a 3 or 4 tuple of int (e.g.: (255, 0, 170, 187)).
If present, the 4th value is the alpha channel
If value can't be parsed, a warning message is logged, and DEFAULT is returned
"""
raw_value = raw_value.strip().lower()
if raw_value.startswith(u'#'):
# we have a hexadecimal value
str_value = raw_value[1:]
if len(raw_value) in (3,4):
str_value = u''.join([2*v for v in str_value])
elif raw_value.startswith(u'rgb'):
left_p = raw_value.find(u'(')
right_p = raw_value.find(u')')
rgb_values = [v.strip() for v in raw_value[left_p+1:right_p].split(',')]
expected_len = 4 if raw_value.startswith(u'rgba') else 3
if len(rgb_values) != expected_len:
log.warning(u"incorrect value: {}".format(raw_value))
str_value = DEFAULT
else:
int_values = []
for rgb_v in rgb_values:
p_idx = rgb_v.find(u'%')
if p_idx == -1:
# base 10 value
try:
int_v = int(rgb_v)
if int_v > 255:
raise ValueError(u"value exceed 255")
int_values.append(int_v)
except ValueError:
log.warning(u"invalid int: {}".format(rgb_v))
int_values.append(0)
else:
# percentage
try:
int_v = int(int(rgb_v[:p_idx]) / 100.0 * 255)
if int_v > 255:
raise ValueError(u"value exceed 255")
int_values.append(int_v)
except ValueError:
log.warning(u"invalid percent value: {}".format(rgb_v))
int_values.append(0)
str_value = u''.join([u"{:02x}".format(v) for v in int_values])
elif raw_value.startswith(u'hsl'):
log.warning(u"hue-saturation-lightness not handled yet") # TODO
str_value = DEFAULT
else:
try:
str_value = CSS_COLORS[raw_value]
except KeyError:
log.warning(u"unrecognised format: {}".format(raw_value))
str_value = DEFAULT
if as_string:
return str_value
else:
return tuple([int(str_value[i]+str_value[i+1], 16) for i in xrange(0, len(str_value), 2)])

View file

@ -0,0 +1,79 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""This library help manage general games (e.g. card games) and it is shared by the frontends"""
SUITS_ORDER = ['pique', 'coeur', 'trefle', 'carreau', 'atout'] # I have switched the usual order 'trefle' and 'carreau' because card are more easy to see if suit colour change (black, red, black, red)
VALUES_ORDER = [str(i) for i in xrange(1, 11)] + ["valet", "cavalier", "dame", "roi"]
class TarotCard(object):
"""This class is used to represent a car logically"""
def __init__(self, tuple_card):
"""@param tuple_card: tuple (suit, value)"""
self.suit, self.value = tuple_card
self.bout = self.suit == "atout" and self.value in ["1", "21", "excuse"]
if self.bout or self.value == "roi":
self.points = 4.5
elif self.value == "dame":
self.points = 3.5
elif self.value == "cavalier":
self.points = 2.5
elif self.value == "valet":
self.points = 1.5
else:
self.points = 0.5
def get_tuple(self):
return (self.suit, self.value)
@staticmethod
def from_tuples(tuple_list):
result = []
for card_tuple in tuple_list:
result.append(TarotCard(card_tuple))
return result
def __cmp__(self, other):
if other is None:
return 1
if self.suit != other.suit:
idx1 = SUITS_ORDER.index(self.suit)
idx2 = SUITS_ORDER.index(other.suit)
return idx1.__cmp__(idx2)
if self.suit == 'atout':
if self.value == other.value == 'excuse':
return 0
if self.value == 'excuse':
return -1
if other.value == 'excuse':
return 1
return int(self.value).__cmp__(int(other.value))
# at this point we have the same suit which is not 'atout'
idx1 = VALUES_ORDER.index(self.value)
idx2 = VALUES_ORDER.index(other.value)
return idx1.__cmp__(idx2)
def __str__(self):
return "[%s,%s]" % (self.suit, self.value)
# These symbols are diplayed by Libervia next to the player's nicknames
SYMBOLS = {"Radiocol": [u"♬"], "Tarot": [u"♠", u"♣", u"♥", u"♦"]}

View file

@ -0,0 +1,45 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""This module is only used launch callbacks when host is ready, used for early initialisation stuffs"""
listeners = []
def addListener(cb):
"""Add a listener which will be called when host is ready
@param cb: callback which will be called when host is ready with host as only argument
"""
listeners.append(cb)
def callListeners(host):
"""Must be called by frontend when host is ready.
The call will launch all the callbacks, then remove the listeners list.
@param host(QuickApp): the instancied QuickApp subclass
"""
global listeners
while True:
try:
cb = listeners.pop(0)
cb(host)
except IndexError:
break
del listeners

126
sat_frontends/tools/jid.py Normal file
View file

@ -0,0 +1,126 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# hack to use this module with pyjamas
try:
unicode('') # XXX: unicode doesn't exist in pyjamas
# normal version
class BaseJID(unicode):
def __new__(cls, jid_str):
self = unicode.__new__(cls, cls._normalize(jid_str))
return self
def __init__(self, jid_str):
pass
def _parse(self):
"""Find node domain and resource"""
node_end = self.find('@')
if node_end < 0:
node_end = 0
domain_end = self.find('/')
if domain_end == 0:
raise ValueError("a jid can't start with '/'")
if domain_end == -1:
domain_end = len(self)
self.node = self[:node_end] or None
self.domain = self[(node_end + 1) if node_end else 0:domain_end]
self.resource = self[domain_end + 1:] or None
except (TypeError, AttributeError): # Error raised is not the same depending on pyjsbuild options
# pyjamas version
class BaseJID(object):
def __init__(self, jid_str):
self.__internal_str = JID._normalize(jid_str)
def __str__(self):
return self.__internal_str
def __getattr__(self, name):
return getattr(self.__internal_str, name)
def __eq__(self, other):
if not isinstance(other, JID):
return False
return (self.node == other.node
and self.domain == other.domain
and self.resource == other.resource)
def __hash__(self):
return hash('JID<{}>'.format(self.__internal_str))
def find(self, *args):
return self.__internal_str.find(*args)
def _parse(self):
"""Find node domain and resource"""
node_end = self.__internal_str.find('@')
if node_end < 0:
node_end = 0
domain_end = self.__internal_str.find('/')
if domain_end == 0:
raise ValueError("a jid can't start with '/'")
if domain_end == -1:
domain_end = len(self.__internal_str)
self.node = self.__internal_str[:node_end] or None
self.domain = self.__internal_str[(node_end + 1) if node_end else 0:domain_end]
self.resource = self.__internal_str[domain_end + 1:] or None
class JID(BaseJID):
"""This class help manage JID (Node@Domaine/Resource)"""
def __init__(self, jid_str):
super(JID, self).__init__(jid_str)
self._parse()
@staticmethod
def _normalize(jid_str):
"""Naive normalization before instantiating and parsing the JID"""
if not jid_str:
return jid_str
tokens = jid_str.split('/')
tokens[0] = tokens[0].lower() # force node and domain to lower-case
return '/'.join(tokens)
@property
def bare(self):
if not self.node:
return JID(self.domain)
return JID(u"{}@{}".format(self.node, self.domain))
def is_valid(self):
"""
@return: True if the JID is XMPP compliant
"""
# TODO: implement real check, according to the RFC http://tools.ietf.org/html/rfc6122
return self.domain != ""
def newResource(entity, resource):
"""Build a new JID from the given entity and resource.
@param entity (JID): original JID
@param resource (unicode): new resource
@return: a new JID instance
"""
return JID(u"%s/%s" % (entity.bare, resource))

View file

@ -0,0 +1,90 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# SAT helpers methods for plugins
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class InputHistory(object):
def _updateInputHistory(self, text=None, step=None, callback=None, mode=""):
"""Update the lists of previously sent messages. Several lists can be
handled as they are stored in a dictionary, the argument "mode" being
used as the entry key. There's also a temporary list to allow you play
with previous entries before sending a new message. Parameters values
can be combined: text is None and step is None to initialize a main
list and the temporary one, step is None to update a list and
reinitialize the temporary one, step is not None to update
the temporary list between two messages.
@param text: text to be saved.
@param step: step to move the temporary index.
@param callback: method to display temporary entries.
@param mode: the dictionary key for main lists.
"""
if not hasattr(self, "input_histories"):
self.input_histories = {}
history = self.input_histories.setdefault(mode, [])
if step is None and text is not None:
# update the main list
if text in history:
history.remove(text)
history.append(text)
length = len(history)
if step is None or length == 0:
# prepare the temporary list and index
self.input_history_tmp = history[:]
self.input_history_tmp.append("")
self.input_history_index = length
if step is None:
return
# update the temporary list
if text is not None:
# save the current entry
self.input_history_tmp[self.input_history_index] = text
# move to another entry if possible
index_tmp = self.input_history_index + step
if index_tmp >= 0 and index_tmp < len(self.input_history_tmp):
if callback is not None:
callback(self.input_history_tmp[index_tmp])
self.input_history_index = index_tmp
class FlagsHandler(object):
"""Small class to handle easily option flags
the instance is initialized with an iterable
then attribute return True if flag is set, False else.
WARNING: If a flag is checked, it is removed (i.e. unset)
this is done to use bool(flags_handler) to check if all flags
have been used
"""
def __init__(self, flags):
self.flags = set(flags or [])
def __getattr__(self, flag):
try:
self.flags.remove(flag)
except KeyError:
return False
else:
return True
def __len__(self):
return len(self.flags)
def __iter__(self):
return self.flags.__iter__()

View file

@ -0,0 +1,99 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# SAT helpers methods for plugins
# Copyright (C) 2013-2016 Adrien Cossa (souliane@mailoo.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
# Regexp from http://daringfireball.net/2010/07/improved_regex_for_matching_urls
RE_URL = re.compile(r"""(?i)\b((?:[a-z]{3,}://|(www|ftp)\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/|mailto:|xmpp:)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?]))""")
# TODO: merge this class with an other module or at least rename it (strings is not a good name)
def getURLParams(url):
"""This comes from pyjamas.Location.makeUrlDict with a small change
to also parse full URLs, and parameters with no value specified
(in that case the default value "" is used).
@param url: any URL with or without parameters
@return: a dictionary of the parameters, if any was given, or {}
"""
dict_ = {}
if "/" in url:
# keep the part after the last "/"
url = url[url.rindex("/") + 1:]
if url.startswith("?"):
# remove the first "?"
url = url[1:]
pairs = url.split("&")
for pair in pairs:
if len(pair) < 3:
continue
kv = pair.split("=", 1)
dict_[kv[0]] = kv[1] if len(kv) > 1 else ""
return dict_
def addURLToText(string, new_target=True):
"""Check a text for what looks like an URL and make it clickable.
@param string (unicode): text to process
@param new_target (bool): if True, make the link open in a new window
"""
# XXX: report any change to libervia.browser.strings.addURLToText
def repl(match):
url = match.group(0)
if not re.match(r"""[a-z]{3,}://|mailto:|xmpp:""", url):
url = "http://" + url
target = ' target="_blank"' if new_target else ''
return '<a href="%s"%s class="url">%s</a>' % (url, target, match.group(0))
return RE_URL.sub(repl, string)
def addURLToImage(string):
"""Check a XHTML text for what looks like an imageURL and make it clickable.
@param string (unicode): text to process
"""
# XXX: report any change to libervia.browser.strings.addURLToImage
def repl(match):
url = match.group(1)
return '<a href="%s" target="_blank">%s</a>' % (url, match.group(0))
pattern = r"""<img[^>]* src="([^"]+)"[^>]*>"""
return re.sub(pattern, repl, string)
def fixXHTMLLinks(xhtml):
"""Add http:// if the scheme is missing and force opening in a new window.
@param string (unicode): XHTML Content
"""
subs = []
for match in re.finditer(r'<a( \w+="[^"]*")* ?/?>', xhtml):
tag = match.group(0)
url = re.search(r'href="([^"]*)"', tag)
if url and not url.group(1).startswith("#"): # skip internal anchor
if not re.search(r'target="([^"]*)"', tag): # no target
subs.append((tag, '<a target="_blank"%s' % tag[2:]))
if not re.match(r"^\w+://", url.group(1)): # no scheme
subs.append((url.group(0), 'href="http://%s"' % url.group(1)))
for url, new_url in subs:
xhtml = xhtml.replace(url, new_url)
return xhtml

View file

@ -0,0 +1,48 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# SAT: a jabber client
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""This library help manage XML used in SàT frontends """
# we don't import minidom as a different class can be used in frontends
# (e.g. NativeDOM in Libervia)
def inlineRoot(doc):
""" make the root attribute inline
@param root_node: minidom's Document compatible class
@return: plain XML
"""
root_elt = doc.documentElement
if root_elt.hasAttribute('style'):
styles_raw = root_elt.getAttribute('style')
styles = styles_raw.split(';')
new_styles = []
for style in styles:
try:
key, value = style.split(':')
except ValueError:
continue
if key.strip().lower() == 'display':
value = 'inline'
new_styles.append('%s: %s' % (key.strip(), value.strip()))
root_elt.setAttribute('style', "; ".join(new_styles))
else:
root_elt.setAttribute('style', 'display: inline')
return root_elt.toxml()

View file

@ -0,0 +1,858 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# SàT frontend tools
# Copyright (C) 2009-2018 Jérôme Poisson (goffi@goffi.org)
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from sat.core.i18n import _
from sat.core.log import getLogger
log = getLogger(__name__)
from sat_frontends.quick_frontend.constants import Const as C
from sat.core import exceptions
class_map = {}
CLASS_PANEL = 'panel'
CLASS_DIALOG = 'dialog'
CURRENT_LABEL = 'current_label'
class InvalidXMLUI(Exception):
pass
class ClassNotRegistedError(Exception):
pass
# FIXME: this method is duplicated in frontends.tools.xmlui.getText
def getText(node):
"""Get child text nodes
@param node: dom Node
@return: joined unicode text of all nodes
"""
data = []
for child in node.childNodes:
if child.nodeType == child.TEXT_NODE:
data.append(child.wholeText)
return u"".join(data)
class Widget(object):
"""base Widget"""
pass
class EmptyWidget(Widget):
"""Just a placeholder widget"""
pass
class TextWidget(Widget):
"""Non interactive text"""
pass
class LabelWidget(Widget):
"""Non interactive text"""
pass
class JidWidget(Widget):
"""Jabber ID"""
pass
class DividerWidget(Widget):
"""Separator"""
pass
class StringWidget(Widget):
"""Input widget wich require a string
often called Edit in toolkits
"""
pass
class JidInputWidget(Widget):
"""Input widget wich require a string
often called Edit in toolkits
"""
pass
class PasswordWidget(Widget):
"""Input widget with require a masked string"""
pass
class TextBoxWidget(Widget):
"""Input widget with require a long, possibly multilines string
often called TextArea in toolkits
"""
pass
class BoolWidget(Widget):
"""Input widget with require a boolean value
often called CheckBox in toolkits
"""
pass
class IntWidget(Widget):
"""Input widget with require an integer"""
pass
class ButtonWidget(Widget):
"""A clickable widget"""
pass
class ListWidget(Widget):
"""A widget able to show/choose one or several strings in a list"""
pass
class JidsListWidget(Widget):
"""A widget able to show/choose one or several strings in a list"""
pass
class Container(Widget):
"""Widget which can contain other ones with a specific layout"""
@classmethod
def _xmluiAdapt(cls, instance):
"""Make cls as instance.__class__
cls must inherit from original instance class
Usefull when you get a class from UI toolkit
"""
assert instance.__class__ in cls.__bases__
instance.__class__ = type(cls.__name__, cls.__bases__, dict(cls.__dict__))
class PairsContainer(Container):
"""Widgets are disposed in rows of two (usually label/input)"""
pass
class LabelContainer(Container):
"""Widgets are associated with label or empty widget"""
pass
class TabsContainer(Container):
"""A container which several other containers in tabs
Often called Notebook in toolkits
"""
pass
class VerticalContainer(Container):
"""Widgets are disposed vertically"""
pass
class AdvancedListContainer(Container):
"""Widgets are disposed in rows with advaned features"""
pass
class Dialog(object):
"""base dialog"""
def __init__(self, _xmlui_parent):
self._xmlui_parent = _xmlui_parent
def _xmluiValidated(self, data=None):
if data is None:
data = {}
self._xmluiSetData(C.XMLUI_STATUS_VALIDATED, data)
self._xmluiSubmit(data)
def _xmluiCancelled(self):
data = {C.XMLUI_DATA_CANCELLED: C.BOOL_TRUE}
self._xmluiSetData(C.XMLUI_STATUS_CANCELLED, data)
self._xmluiSubmit(data)
def _xmluiSubmit(self, data):
if self._xmlui_parent.submit_id is None:
log.debug(_("Nothing to submit"))
else:
self._xmlui_parent.submit(data)
def _xmluiSetData(self, status, data):
pass
class MessageDialog(Dialog):
"""Dialog with a OK/Cancel type configuration"""
pass
class NoteDialog(Dialog):
"""Short message which doesn't need user confirmation to disappear"""
pass
class ConfirmDialog(Dialog):
"""Dialog with a OK/Cancel type configuration"""
def _xmluiSetData(self, status, data):
if status == C.XMLUI_STATUS_VALIDATED:
data[C.XMLUI_DATA_ANSWER] = C.BOOL_TRUE
elif status == C.XMLUI_STATUS_CANCELLED:
data[C.XMLUI_DATA_ANSWER] = C.BOOL_FALSE
class FileDialog(Dialog):
"""Dialog with a OK/Cancel type configuration"""
pass
class XMLUIBase(object):
"""Base class to construct SàT XML User Interface
This class must not be instancied directly
"""
def __init__(self, host, parsed_dom, title=None, flags=None, callback=None, profile=C.PROF_KEY_NONE):
"""Initialise the XMLUI instance
@param host: %(doc_host)s
@param parsed_dom: main parsed dom
@param title: force the title, or use XMLUI one if None
@param flags: list of string which can be:
- NO_CANCEL: the UI can't be cancelled
- FROM_BACKEND: the UI come from backend (i.e. it's not the direct result of user operation)
@param callback(callable, None): if not None, will be used with launchAction:
- if None is used, default behaviour will be used (closing the dialog and calling host.actionManager)
- if a callback is provided, it will be used instead, so you'll have to manage
dialog closing or new xmlui to display, or other action (you can call host.actionManager)
"""
self.host = host
top=parsed_dom.documentElement
self.session_id = top.getAttribute("session_id") or None
self.submit_id = top.getAttribute("submit") or None
self.xmlui_title = title or top.getAttribute("title") or u""
if flags is None:
flags = []
self.flags = flags
self.callback = callback or self._defaultCb
self.profile = profile
@property
def user_action(self):
return "FROM_BACKEND" not in self.flags
def _defaultCb(self, data, cb_id, profile):
# TODO: when XMLUI updates will be managed, the _xmluiClose
# must be called only if there is not update
self._xmluiClose()
self.host.actionManager(data, profile=profile)
def _isAttrSet(self, name, node):
"""Return widget boolean attribute status
@param name: name of the attribute (e.g. "read_only")
@param node: Node instance
@return (bool): True if widget's attribute is set (C.BOOL_TRUE)
"""
read_only = node.getAttribute(name) or C.BOOL_FALSE
return read_only.lower().strip() == C.BOOL_TRUE
def _getChildNode(self, node, name):
"""Return the first child node with the given name
@param node: Node instance
@param name: name of the wanted node
@return: The found element or None
"""
for child in node.childNodes:
if child.nodeName == name:
return child
return None
def submit(self, data):
self._xmluiClose()
if self.submit_id is None:
raise ValueError("Can't submit is self.submit_id is not set")
if "session_id" in data:
raise ValueError("session_id must no be used in data, it is automaticaly filled with self.session_id if present")
if self.session_id is not None:
data["session_id"] = self.session_id
self._xmluiLaunchAction(self.submit_id, data)
def _xmluiLaunchAction(self, action_id, data):
self.host.launchAction(action_id, data, callback=self.callback, profile=self.profile)
def _xmluiClose(self):
"""Close the window/popup/... where the constructor XMLUI is
this method must be overrided
"""
raise NotImplementedError
class ValueGetter(object):
"""dict like object which return values of widgets"""
def __init__(self, widgets, attr='value'):
self.attr = attr
self.widgets = widgets
def __getitem__(self, name):
return getattr(self.widgets[name], self.attr)
def __getattr__(self, name):
return self.__getitem__(name)
def keys(self):
return self.widgets.keys()
class XMLUIPanel(XMLUIBase):
"""XMLUI Panel
New frontends can inherit this class to easily implement XMLUI
@property widget_factory: factory to create frontend-specific widgets
@property dialog_factory: factory to create frontend-specific dialogs
"""
widget_factory = None
def __init__(self, host, parsed_dom, title=None, flags=None, callback=None, ignore=None, whitelist=None, profile=C.PROF_KEY_NONE):
"""
@param title(unicode, None): title of the
@property widgets(dict): widget name => widget map
@property widget_value(ValueGetter): retrieve widget value from it's name
"""
super(XMLUIPanel, self).__init__(host, parsed_dom, title=title, flags=flags, callback=callback, profile=profile)
self.ctrl_list = {} # input widget, used mainly for forms
self.widgets = {} # allow to access any named widgets
self.widget_value = ValueGetter(self.widgets)
self._main_cont = None
if ignore is None:
ignore = []
self._ignore = ignore
if whitelist is not None:
if ignore:
raise exceptions.InternalError('ignore and whitelist must not be used at the same time')
self._whitelist = whitelist
else:
self._whitelist = None
self.constructUI(parsed_dom)
def escape(self, name):
"""Return escaped name for forms"""
return u"%s%s" % (C.SAT_FORM_PREFIX, name)
@property
def main_cont(self):
return self._main_cont
@main_cont.setter
def main_cont(self, value):
if self._main_cont is not None:
raise ValueError(_("XMLUI can have only one main container"))
self._main_cont = value
def _parseChilds(self, _xmlui_parent, current_node, wanted = ('container',), data = None):
"""Recursively parse childNodes of an element
@param _xmlui_parent: widget container with '_xmluiAppend' method
@param current_node: element from which childs will be parsed
@param wanted: list of tag names that can be present in the childs to be SàT XMLUI compliant
@param data(None, dict): additionnal data which are needed in some cases
"""
for node in current_node.childNodes:
if data is None:
data = {}
if wanted and not node.nodeName in wanted:
raise InvalidXMLUI('Unexpected node: [%s]' % node.nodeName)
if node.nodeName == "container":
type_ = node.getAttribute('type')
if _xmlui_parent is self and type_ != 'vertical':
# main container is not a VerticalContainer and we want one, so we create one to wrap it
_xmlui_parent = self.widget_factory.createVerticalContainer(self)
self.main_cont = _xmlui_parent
if type_ == "tabs":
cont = self.widget_factory.createTabsContainer(_xmlui_parent)
self._parseChilds(_xmlui_parent, node, ('tab',), {'tabs_cont': cont})
elif type_ == "vertical":
cont = self.widget_factory.createVerticalContainer(_xmlui_parent)
self._parseChilds(cont, node, ('widget', 'container'))
elif type_ == "pairs":
cont = self.widget_factory.createPairsContainer(_xmlui_parent)
self._parseChilds(cont, node, ('widget', 'container'))
elif type_ == "label":
cont = self.widget_factory.createLabelContainer(_xmlui_parent)
self._parseChilds(cont, node, ('widget', 'container'), {CURRENT_LABEL: None})
elif type_ == "advanced_list":
try:
columns = int(node.getAttribute('columns'))
except (TypeError, ValueError):
raise exceptions.DataError("Invalid columns")
selectable = node.getAttribute('selectable') or 'no'
auto_index = node.getAttribute('auto_index') == C.BOOL_TRUE
data = {'index': 0} if auto_index else None
cont = self.widget_factory.createAdvancedListContainer(_xmlui_parent, columns, selectable)
callback_id = node.getAttribute("callback") or None
if callback_id is not None:
if selectable == 'no':
raise ValueError("can't have selectable=='no' and callback_id at the same time")
cont._xmlui_callback_id = callback_id
cont._xmluiOnSelect(self.onAdvListSelect)
self._parseChilds(cont, node, ('row',), data)
else:
log.warning(_("Unknown container [%s], using default one") % type_)
cont = self.widget_factory.createVerticalContainer(_xmlui_parent)
self._parseChilds(cont, node, ('widget', 'container'))
try:
xmluiAppend = _xmlui_parent._xmluiAppend
except (AttributeError, TypeError): # XXX: TypeError is here because pyjamas raise a TypeError instead of an AttributeError
if _xmlui_parent is self:
self.main_cont = cont
else:
raise Exception(_("Internal Error, container has not _xmluiAppend method"))
else:
xmluiAppend(cont)
elif node.nodeName == 'tab':
name = node.getAttribute('name')
label = node.getAttribute('label')
selected = C.bool(node.getAttribute('selected') or C.BOOL_FALSE)
if not name or not 'tabs_cont' in data:
raise InvalidXMLUI
if self.type == 'param':
self._current_category = name #XXX: awful hack because params need category and we don't keep parent
tab_cont = data['tabs_cont']
new_tab = tab_cont._xmluiAddTab(label or name, selected)
self._parseChilds(new_tab, node, ('widget', 'container'))
elif node.nodeName == 'row':
try:
index = str(data['index'])
except KeyError:
index = node.getAttribute('index') or None
else:
data['index'] += 1
_xmlui_parent._xmluiAddRow(index)
self._parseChilds(_xmlui_parent, node, ('widget', 'container'))
elif node.nodeName == "widget":
name = node.getAttribute("name")
if name and (name in self._ignore or self._whitelist is not None and name not in self._whitelist):
# current widget is ignored, but there may be already a label
if CURRENT_LABEL in data:
# if so, we remove it from parent
_xmlui_parent._xmluiRemove(data.pop(CURRENT_LABEL))
continue
type_ = node.getAttribute("type")
value_elt = self._getChildNode(node, "value")
if value_elt is not None:
value = getText(value_elt)
else:
value = node.getAttribute("value") if node.hasAttribute('value') else u''
if type_=="empty":
ctrl = self.widget_factory.createEmptyWidget(_xmlui_parent)
if CURRENT_LABEL in data:
data[CURRENT_LABEL] = None
elif type_=="text":
ctrl = self.widget_factory.createTextWidget(_xmlui_parent, value)
elif type_=="label":
ctrl = self.widget_factory.createLabelWidget(_xmlui_parent, value)
data[CURRENT_LABEL] = ctrl
elif type_=="jid":
ctrl = self.widget_factory.createJidWidget(_xmlui_parent, value)
elif type_=="divider":
style = node.getAttribute("style") or 'line'
ctrl = self.widget_factory.createDividerWidget(_xmlui_parent, style)
elif type_=="string":
ctrl = self.widget_factory.createStringWidget(_xmlui_parent, value, self._isAttrSet("read_only", node))
self.ctrl_list[name] = ({'type':type_, 'control':ctrl})
elif type_=="jid_input":
ctrl = self.widget_factory.createJidInputWidget(_xmlui_parent, value, self._isAttrSet("read_only", node))
self.ctrl_list[name] = ({'type':type_, 'control':ctrl})
elif type_=="password":
ctrl = self.widget_factory.createPasswordWidget(_xmlui_parent, value, self._isAttrSet("read_only", node))
self.ctrl_list[name] = ({'type':type_, 'control':ctrl})
elif type_=="textbox":
ctrl = self.widget_factory.createTextBoxWidget(_xmlui_parent, value, self._isAttrSet("read_only", node))
self.ctrl_list[name] = ({'type':type_, 'control':ctrl})
elif type_=="bool":
ctrl = self.widget_factory.createBoolWidget(_xmlui_parent, value==C.BOOL_TRUE, self._isAttrSet("read_only", node))
self.ctrl_list[name] = ({'type':type_, 'control':ctrl})
elif type_ == "int":
ctrl = self.widget_factory.createIntWidget(_xmlui_parent, value, self._isAttrSet("read_only", node))
self.ctrl_list[name] = ({'type':type_, 'control':ctrl})
elif type_ == "list":
style = [] if node.getAttribute("multi") == 'yes' else ['single']
for attr in (u'noselect', u'extensible', u'reducible', u'inline'):
if node.getAttribute(attr) == 'yes':
style.append(attr)
_options = [(option.getAttribute("value"), option.getAttribute("label")) for option in node.getElementsByTagName("option")]
_selected = [option.getAttribute("value") for option in node.getElementsByTagName("option") if option.getAttribute('selected') == C.BOOL_TRUE]
ctrl = self.widget_factory.createListWidget(_xmlui_parent, _options, _selected, style)
self.ctrl_list[name] = ({'type': type_, 'control': ctrl})
elif type_ == "jids_list":
style = []
jids = [getText(jid_) for jid_ in node.getElementsByTagName("jid")]
ctrl = self.widget_factory.createJidsListWidget(_xmlui_parent, jids, style)
self.ctrl_list[name] = ({'type': type_, 'control': ctrl})
elif type_=="button":
callback_id = node.getAttribute("callback")
ctrl = self.widget_factory.createButtonWidget(_xmlui_parent, value, self.onButtonPress)
ctrl._xmlui_param_id = (callback_id, [field.getAttribute('name') for field in node.getElementsByTagName("field_back")])
else:
log.error(_("FIXME FIXME FIXME: widget type [%s] is not implemented") % type_)
raise NotImplementedError(_("FIXME FIXME FIXME: type [%s] is not implemented") % type_)
if name:
self.widgets[name] = ctrl
if self.type == 'param' and type_ not in ('text', 'button'):
try:
ctrl._xmluiOnChange(self.onParamChange)
ctrl._param_category = self._current_category
except (AttributeError, TypeError): # XXX: TypeError is here because pyjamas raise a TypeError instead of an AttributeError
if not isinstance(ctrl, (EmptyWidget, TextWidget, LabelWidget, JidWidget)):
log.warning(_("No change listener on [%s]") % ctrl)
elif type_ != 'text':
callback = node.getAttribute("internal_callback") or None
if callback:
fields = [field.getAttribute('name') for field in node.getElementsByTagName("internal_field")]
cb_data = self.getInternalCallbackData(callback, node)
ctrl._xmlui_param_internal = (callback, fields, cb_data)
if type_ == 'button':
ctrl._xmluiOnClick(self.onChangeInternal)
else:
ctrl._xmluiOnChange(self.onChangeInternal)
ctrl._xmlui_name = name
_xmlui_parent._xmluiAppend(ctrl)
if CURRENT_LABEL in data and not isinstance(ctrl, LabelWidget):
# this key is set in LabelContainer, when present
# we can associate the label with the widget it is labelling
data.pop(CURRENT_LABEL)._xmlui_for_name = name
else:
raise NotImplementedError(_('Unknown tag [%s]') % node.nodeName)
def constructUI(self, parsed_dom, post_treat=None):
"""Actually construct the UI
@param parsed_dom: main parsed dom
@param post_treat: frontend specific treatments to do once the UI is constructed
@return: constructed widget
"""
top=parsed_dom.documentElement
self.type = top.getAttribute("type")
if top.nodeName != "sat_xmlui" or not self.type in ['form', 'param', 'window', 'popup']:
raise InvalidXMLUI
if self.type == 'param':
self.param_changed = set()
self._parseChilds(self, parsed_dom.documentElement)
if post_treat is not None:
post_treat()
def _xmluiSetParam(self, name, value, category):
self.host.bridge.setParam(name, value, category, profile_key=self.profile)
##EVENTS##
def onParamChange(self, ctrl):
"""Called when type is param and a widget to save is modified
@param ctrl: widget modified
"""
assert self.type == "param"
self.param_changed.add(ctrl)
def onAdvListSelect(self, ctrl):
data = {}
widgets = ctrl._xmluiGetSelectedWidgets()
for wid in widgets:
try:
name = self.escape(wid._xmlui_name)
value = wid._xmluiGetValue()
data[name] = value
except (AttributeError, TypeError): # XXX: TypeError is here because pyjamas raise a TypeError instead of an AttributeError
pass
idx = ctrl._xmluiGetSelectedIndex()
if idx is not None:
data['index'] = idx
callback_id = ctrl._xmlui_callback_id
if callback_id is None:
log.info(_("No callback_id found"))
return
self._xmluiLaunchAction(callback_id, data)
def onButtonPress(self, button):
"""Called when an XMLUI button is clicked
Launch the action associated to the button
@param button: the button clicked
"""
callback_id, fields = button._xmlui_param_id
if not callback_id: # the button is probably bound to an internal action
return
data = {}
for field in fields:
escaped = self.escape(field)
ctrl = self.ctrl_list[field]
if isinstance(ctrl['control'], ListWidget):
data[escaped] = u'\t'.join(ctrl['control']._xmluiGetSelectedValues())
else:
data[escaped] = ctrl['control']._xmluiGetValue()
self._xmluiLaunchAction(callback_id, data)
def onChangeInternal(self, ctrl):
"""Called when a widget that has been bound to an internal callback is changed.
This is used to perform some UI actions without communicating with the backend.
See sat.tools.xml_tools.Widget.setInternalCallback for more details.
@param ctrl: widget modified
"""
action, fields, data = ctrl._xmlui_param_internal
if action not in ('copy', 'move', 'groups_of_contact'):
raise NotImplementedError(_("FIXME: XMLUI internal action [%s] is not implemented") % action)
def copy_move(source, target):
"""Depending of 'action' value, copy or move from source to target."""
if isinstance(target, ListWidget):
if isinstance(source, ListWidget):
values = source._xmluiGetSelectedValues()
else:
values = [source._xmluiGetValue()]
if action == 'move':
source._xmluiSetValue('')
values = [value for value in values if value]
if values:
target._xmluiAddValues(values, select=True)
else:
if isinstance(source, ListWidget):
value = u', '.join(source._xmluiGetSelectedValues())
else:
value = source._xmluiGetValue()
if action == 'move':
source._xmluiSetValue('')
target._xmluiSetValue(value)
def groups_of_contact(source, target):
"""Select in target the groups of the contact which is selected in source."""
assert isinstance(source, ListWidget)
assert isinstance(target, ListWidget)
try:
contact_jid_s = source._xmluiGetSelectedValues()[0]
except IndexError:
return
target._xmluiSelectValues(data[contact_jid_s])
pass
source = None
for field in fields:
widget = self.ctrl_list[field]['control']
if not source:
source = widget
continue
if action in ('copy', 'move'):
copy_move(source, widget)
elif action == 'groups_of_contact':
groups_of_contact(source, widget)
source = None
def getInternalCallbackData(self, action, node):
"""Retrieve from node the data needed to perform given action.
@param action (string): a value from the one that can be passed to the
'callback' parameter of sat.tools.xml_tools.Widget.setInternalCallback
@param node (DOM Element): the node of the widget that triggers the callback
"""
# TODO: it would be better to not have a specific way to retrieve
# data for each action, but instead to have a generic method to
# extract any kind of data structure from the 'internal_data' element.
try: # data is stored in the first 'internal_data' element of the node
data_elts = node.getElementsByTagName('internal_data')[0].childNodes
except IndexError:
return None
data = {}
if action == 'groups_of_contact': # return a dict(key: string, value: list[string])
for elt in data_elts:
jid_s = elt.getAttribute('name')
data[jid_s] = []
for value_elt in elt.childNodes:
data[jid_s].append(value_elt.getAttribute('name'))
return data
def onFormSubmitted(self, ignore=None):
"""An XMLUI form has been submited
call the submit action associated with this form
"""
selected_values = []
for ctrl_name in self.ctrl_list:
escaped = self.escape(ctrl_name)
ctrl = self.ctrl_list[ctrl_name]
if isinstance(ctrl['control'], ListWidget):
selected_values.append((escaped, u'\t'.join(ctrl['control']._xmluiGetSelectedValues())))
else:
selected_values.append((escaped, ctrl['control']._xmluiGetValue()))
if self.submit_id is not None:
data = dict(selected_values)
self.submit(data)
else:
log.warning(_("The form data is not sent back, the type is not managed properly"))
self._xmluiClose()
def onFormCancelled(self, ignore=None):
"""Called when a form is cancelled"""
log.debug(_("Cancelling form"))
if self.submit_id is not None:
data = {C.XMLUI_DATA_CANCELLED: C.BOOL_TRUE}
self.submit(data)
else:
log.warning(_("The form data is not sent back, the type is not managed properly"))
self._xmluiClose()
def onSaveParams(self, ignore=None):
"""Params are saved, we send them to backend
self.type must be param
"""
assert self.type == 'param'
for ctrl in self.param_changed:
if isinstance(ctrl, ListWidget):
value = u'\t'.join(ctrl._xmluiGetSelectedValues())
else:
value = ctrl._xmluiGetValue()
param_name = ctrl._xmlui_name.split(C.SAT_PARAM_SEPARATOR)[1]
self._xmluiSetParam(param_name, value, ctrl._param_category)
self._xmluiClose()
def show(self, *args, **kwargs):
pass
class XMLUIDialog(XMLUIBase):
dialog_factory = None
def __init__(self, host, parsed_dom, title=None, flags=None, callback=None, ignore=None, profile=C.PROF_KEY_NONE):
super(XMLUIDialog, self).__init__(host, parsed_dom, title=title, flags=flags, callback=callback, profile=profile)
top=parsed_dom.documentElement
dlg_elt = self._getChildNode(top, "dialog")
if dlg_elt is None:
raise ValueError("Invalid XMLUI: no Dialog element found !")
dlg_type = dlg_elt.getAttribute("type") or C.XMLUI_DIALOG_MESSAGE
try:
mess_elt = self._getChildNode(dlg_elt, C.XMLUI_DATA_MESS)
message = getText(mess_elt)
except (TypeError, AttributeError): # XXX: TypeError is here because pyjamas raise a TypeError instead of an AttributeError
message = ""
level = dlg_elt.getAttribute(C.XMLUI_DATA_LVL) or C.XMLUI_DATA_LVL_INFO
if dlg_type == C.XMLUI_DIALOG_MESSAGE:
self.dlg = self.dialog_factory.createMessageDialog(self, self.xmlui_title, message, level)
elif dlg_type == C.XMLUI_DIALOG_NOTE:
self.dlg = self.dialog_factory.createNoteDialog(self, self.xmlui_title, message, level)
elif dlg_type == C.XMLUI_DIALOG_CONFIRM:
try:
buttons_elt = self._getChildNode(dlg_elt, "buttons")
buttons_set = buttons_elt.getAttribute("set") or C.XMLUI_DATA_BTNS_SET_DEFAULT
except (TypeError, AttributeError): # XXX: TypeError is here because pyjamas raise a TypeError instead of an AttributeError
buttons_set = C.XMLUI_DATA_BTNS_SET_DEFAULT
self.dlg = self.dialog_factory.createConfirmDialog(self, self.xmlui_title, message, level, buttons_set)
elif dlg_type == C.XMLUI_DIALOG_FILE:
try:
file_elt = self._getChildNode(dlg_elt, "file")
filetype = file_elt.getAttribute("type") or C.XMLUI_DATA_FILETYPE_DEFAULT
except (TypeError, AttributeError): # XXX: TypeError is here because pyjamas raise a TypeError instead of an AttributeError
filetype = C.XMLUI_DATA_FILETYPE_DEFAULT
self.dlg = self.dialog_factory.createFileDialog(self, self.xmlui_title, message, level, filetype)
else:
raise ValueError("Unknown dialog type [%s]" % dlg_type)
def show(self):
self.dlg._xmluiShow()
def _xmluiClose(self):
self.dlg._xmluiClose()
def registerClass(type_, class_):
"""Register the class to use with the factory
@param type_: one of:
CLASS_PANEL: classical XMLUI interface
CLASS_DIALOG: XMLUI dialog
@param class_: the class to use to instanciate given type
"""
assert type_ in (CLASS_PANEL, CLASS_DIALOG)
class_map[type_] = class_
def create(host, xml_data, title=None, flags=None, dom_parse=None, dom_free=None, callback=None, ignore=None, whitelist=None, profile=C.PROF_KEY_NONE):
"""
@param dom_parse: methode equivalent to minidom.parseString (but which must manage unicode), or None to use default one
@param dom_free: method used to free the parsed DOM
@param ignore(list[unicode], None): name of widgets to ignore
widgets with name in this list and their label will be ignored
@param whitelist(list[unicode], None): name of widgets to keep
when not None, only widgets in this list and their label will be kept
mutually exclusive with ignore
"""
if dom_parse is None:
from xml.dom import minidom
dom_parse = lambda xml_data: minidom.parseString(xml_data.encode('utf-8'))
dom_free = lambda parsed_dom: parsed_dom.unlink()
else:
dom_parse = dom_parse
dom_free = dom_free or (lambda parsed_dom: None)
parsed_dom = dom_parse(xml_data)
top=parsed_dom.documentElement
ui_type = top.getAttribute("type")
try:
if ui_type != C.XMLUI_DIALOG:
cls = class_map[CLASS_PANEL]
else:
cls = class_map[CLASS_DIALOG]
except KeyError:
raise ClassNotRegistedError(_("You must register classes with registerClass before creating a XMLUI"))
xmlui = cls(host, parsed_dom,
title = title,
flags = flags,
callback = callback,
ignore = ignore,
whitelist = whitelist,
profile = profile)
dom_free(parsed_dom)
return xmlui