pass<EOL>

Custom fake event handler called by :py:meth:`Menu.on_enter()` for every layer.

Useful for adding and removing event handlers per layer.


pass<EOL>

Custom fake event handler called by :py:meth:`Menu.on_exit()` for every layer.

Useful for adding and removing event handlers per layer.


Uses :py:meth:`PengWindow.set2d()` to enable a 2D OpenGL state.


Uses :py:meth:`PengWindow.set3d()` to enable a 3D OpenGL state.


if name not in self.world.views:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self.viewname = viewname<EOL>self.view = self.world.getView(self.viewname)<EOL>

Sets the view used to the specified ``name``\ .

The name must be known to the world or else a :py:exc:`ValueError` is raised.


self.cam = self.view.cam<EOL>super(LayerWorld,self).predraw()<EOL>

Sets up the attributes used by :py:class:`Layer3D()` and calls :py:meth:`Layer3D.predraw()`\ .


Draws the view using the :py:meth:`World.render3d()` method.


return self.view.on_menu_enter(old)<EOL>

Passes the event through to the WorldView to allow for custom behavior.


return self.view.on_menu_exit(new)<EOL>


self.lang = lang<EOL>self.peng.cfg["<STR_LIT>"] = lang<EOL>if lang not in self.cache:<EOL><INDENT>self.cache[lang]={}<EOL><DEDENT>self.doAction("<STR_LIT>")<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.lang,"<STR_LIT>":self})<EOL>

Sets the default language for all domains.

For recommendations regarding the format of the language code, see
:py:class:`TranslationManager`\ .

Note that the ``lang`` parameter of both :py:meth:`translate()` and
:py:meth:`translate_lazy()` will override this setting.

Also note that the code won't be checked for existence or plausibility.
This may cause the fallback strings to be displayed instead if the language
does not exist.

Calling this method will cause the ``setlang`` action and the
:peng3d:event`peng3d:i18n.set_lang` event to be triggered. Note that both
action and event will be triggered even if the language did not actually change.

This method also automatically updates the :confval:`i18n.lang` config value.


rsrc = self.peng.cfg["<STR_LIT>"].format(domain=domain,lang="<STR_LIT:*>")<EOL>pattern = self.peng.rsrcMgr.resourceNameToPath(rsrc,self.peng.cfg["<STR_LIT>"])<EOL>files = glob.iglob(pattern)<EOL>langs = set()<EOL>r = re.compile(self.peng.cfg["<STR_LIT>"])<EOL>for f in files:<EOL><INDENT>m = r.fullmatch(f)<EOL>if m is not None:<EOL><INDENT>langs.add(m.group("<STR_LIT>"))<EOL><DEDENT><DEDENT>return list(langs)<EOL>

Generates a list of languages based on files found on disk.

The optional ``domain`` argument may specify a domain to use when checking
for files. By default, all domains are checked.

This internally uses the :py:mod:`glob` built-in module and the
:confval:`i18n.lang.format` config option to find suitable filenames.
It then applies the regex in :confval:`i18n.discover_regex` to extract the
language code.


if z_index is None:<EOL><INDENT>z_index = layer.z_index<EOL><DEDENT>i = <NUM_LIT:0><EOL>for l,z in self.layers:<EOL><INDENT>if z>z_index:<EOL><INDENT>break<EOL><DEDENT>i+=<NUM_LIT:1><EOL><DEDENT>self._layers[layer.name]=layer<EOL>self.layers.insert(i,[layer,z_index])<EOL>

Adds the given layer at the given Z Index.

If ``z_index`` is not given, the Z Index specified by the layer will be used.


return self._layers[name]<EOL>

Returns the layer corresponding to the given name.

:raises KeyError: If there is no Layer with the given name.


if name not in self._layers:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._layers[name].on_redraw()<EOL>

Redraws the given layer.

:raises ValueError: If there is no Layer with the given name.


super(LayeredWidget,self).draw()<EOL>for layer,_ in self.layers:<EOL><INDENT>layer._draw()<EOL><DEDENT>

Draws all layers of this LayeredWidget.

This should normally be unneccessary, since it is recommended that layers use Vertex Lists instead of OpenGL Immediate Mode.


for layer,_ in self.layers:<EOL><INDENT>layer.delete()<EOL><DEDENT>self.layers = []<EOL>self._layers = {}<EOL>super(LayeredWidget,self).delete()<EOL>

Deletes all layers within this LayeredWidget before deleting itself.

Recommended to call if you are removing the widget, but not yet exiting the interpreter.


pass<EOL>

Called by the parent widget if this Layer should be redrawn.

Note that it is recommended to call the Baseclass Variant of this Method first when overwriting it.
See :py:meth:`WidgetLayer.on_redraw` for more information.


pass<EOL>

Called before calling the :py:meth:`draw()` Method.

Useful for setting up OpenGL state.


pass<EOL>

Called to draw the layer.

Note that using this function is discouraged, use Pyglet Vertex Lists instead.

If you want to call this method manually, call :py:meth:`_draw()` instead.
This will make sure that :py:meth:`predraw()` and :py:meth:`postdraw()` are called.


pass<EOL>

Called after calling the :py:meth:`draw()` Method.

Useful for unsetting OpenGL state.


Registers a vertex list for proper deletion once this Layer gets destroyed.

This prevents visual artifacts from forming during deletion of a layer.


for vlist in self._vlists:<EOL><INDENT>vlist.delete()<EOL><DEDENT>self._vlists = []<EOL>

Deletes this Layer.

Currently only deletes VertexLists registered with :py:meth:`regVList()`\ .


super(WidgetLayer,self).on_redraw()<EOL>if not self._initialized:<EOL><INDENT>self.initialize()<EOL>self._initialized = True<EOL><DEDENT>

Called when the Layer should be redrawn.

If a subclass uses the :py:meth:`initialize()` Method, it is very important to also call the Super Class Method to prevent crashes.


pass<EOL>

Called just before :py:meth:`on_redraw()` is called the first time.


Property to be used for setting and getting the border of the layer.

Note that setting this property causes an immediate redraw.


Property to be used for setting and getting the offset of the layer.

Note that setting this property causes an immediate redraw.


<EOL>sx,sy = self.widget.pos[<NUM_LIT:0>]+self.border[<NUM_LIT:0>]+self.offset[<NUM_LIT:0>],                       self.widget.pos[<NUM_LIT:1>]+self.border[<NUM_LIT:1>]+self.offset[<NUM_LIT:1>]<EOL>ex,ey = self.widget.pos[<NUM_LIT:0>]+self.widget.size[<NUM_LIT:0>]-self.border[<NUM_LIT:0>]+self.offset[<NUM_LIT:0>],   self.widget.pos[<NUM_LIT:1>]+self.widget.size[<NUM_LIT:1>]-self.border[<NUM_LIT:1>]+self.offset[<NUM_LIT:1>]<EOL>return sx,sy,ex,ey<EOL>

Returns the absolute position and size of the layer.

This method is intended for use in vertex position calculation, as the border and offset have already been applied.

The returned value is a 4-tuple of ``(sx,sy,ex,ey)``\ .
The two values starting with an s are the "start" position, or the lower-left corner.
The second pair of values signify the "end" position, or upper-right corner.


return self.widget.size[<NUM_LIT:0>]-self.border[<NUM_LIT:0>]*<NUM_LIT:2>,self.widget.size[<NUM_LIT:1>]-self.border[<NUM_LIT:1>]*<NUM_LIT:2><EOL>

Returns the size of the layer, with the border size already subtracted.


self.imgs[name]=self.widget.peng.resourceMgr.getTex(*rsrc)<EOL>

Adds an image to the internal registry.

``rsrc`` should be a 2-tuple of ``(resource_name,category)``\ .


if name not in self.imgs:<EOL><INDENT>raise ValueError("<STR_LIT>"%name)<EOL><DEDENT>elif self.cur_img==name:<EOL><INDENT>return<EOL><DEDENT>self.cur_img = name<EOL>self.on_redraw()<EOL>

Switches the active image to the given name.

:raises ValueError: If there is no such image


<EOL>x,y,_,_ = self.getPos()<EOL>sx,sy = self.getSize()<EOL>self._label.x = x+sx/<NUM_LIT><EOL>self._label.y = y+sy/<NUM_LIT><EOL>self._label.width = sx<EOL>self._label._update()<EOL>

Re-draws the text by calculating its position.

Currently, the text will always be centered on the position of the layer.


return self._label.text<EOL>

Property for accessing the text of the label.


<EOL>x,y,_,_ = self.getPos()<EOL>sx,sy = self.getSize()<EOL>if self.font_name is not None:<EOL><INDENT>self._label.font_name = self.font_name<EOL><DEDENT>if self.font_size is not None:<EOL><INDENT>self._label.font_size = self.font_size<EOL><DEDENT>if self.font_color is not None:<EOL><INDENT>self._label.color = self.font_color<EOL><DEDENT>self._label.x = x+sx/<NUM_LIT><EOL>self._label.y = y+sy/<NUM_LIT><EOL>self._label.width = sx<EOL>self._label._update()<EOL>


return self._label.text<EOL>

Property for accessing the text of the label.

Note that depending on the type of format, this property may not exactly represent the original text as it is converted internally.


self.styles[name]=func<EOL>

Adds a style to the layer.

Note that styles must be registered seperately for each layer.

``name`` is the (string) name of the style.

``func`` will be called with its arguments as ``(bg,o,i,s,h)``\ , see :py:meth:`getColors()` for more information.


bg = self.widget.submenu.bg[:<NUM_LIT:3>] if isinstance(self.widget.submenu.bg,list) or isinstance(self.widget.submenu.bg,tuple) else [<NUM_LIT>,<NUM_LIT>,<NUM_LIT>]<EOL>bg = bg if self.color_bg is None else self.color_bg<EOL>o,i = bg, [min(bg[<NUM_LIT:0>]+<NUM_LIT:8>,<NUM_LIT:255>),min(bg[<NUM_LIT:1>]+<NUM_LIT:8>,<NUM_LIT:255>),min(bg[<NUM_LIT:2>]+<NUM_LIT:8>,<NUM_LIT:255>)]<EOL>s,h = [max(bg[<NUM_LIT:0>]-<NUM_LIT>,<NUM_LIT:0>),max(bg[<NUM_LIT:1>]-<NUM_LIT>,<NUM_LIT:0>),max(bg[<NUM_LIT:2>]-<NUM_LIT>,<NUM_LIT:0>)], [min(bg[<NUM_LIT:0>]+<NUM_LIT:12>,<NUM_LIT:255>),min(bg[<NUM_LIT:1>]+<NUM_LIT:12>,<NUM_LIT:255>),min(bg[<NUM_LIT:2>]+<NUM_LIT:12>,<NUM_LIT:255>)]<EOL>o = o if self.color_o is None else self.color_o<EOL>i = i if self.color_i is None else self.color_i<EOL>s = s if self.color_s is None else self.color_s<EOL>h = h if self.color_h is None else self.color_h<EOL>return bg,o,i,s,h<EOL>

Overrideable function that generates the colors to be used by various styles.

Should return a 5-tuple of ``(bg,o,i,s,h)``\ .

``bg`` is the base color of the background.

``o`` is the outer color, it is usually the same as the background color.

``i`` is the inner color, it is usually lighter than the background color.

``s`` is the shadow color, it is usually quite a bit darker than the background.

``h`` is the highlight color, it is usually quite a bit lighter than the background.

The returned values may also be statically overridden by setting the :py:attr:`color_<var>` attribute to anything but ``None``\ .


sx,sy,ex,ey = self.getPos()<EOL>b = self.bborder<EOL>v1 = sx,            ey<EOL>v2 = sx+b[<NUM_LIT:0>],       ey<EOL>v3 = ex-b[<NUM_LIT:2>],       ey<EOL>v4 = ex,            ey<EOL>v5 = sx,            ey-b[<NUM_LIT:1>]<EOL>v6 = sx+b[<NUM_LIT:0>],       ey-b[<NUM_LIT:1>]<EOL>v7 = ex-b[<NUM_LIT:2>],       ey-b[<NUM_LIT:3>]<EOL>v8 = ex,            ey-b[<NUM_LIT:3>]<EOL>v9 = sx,            sy+b[<NUM_LIT:5>]<EOL>v10= sx+b[<NUM_LIT:4>],       sy+b[<NUM_LIT:5>]<EOL>v11= ex-b[<NUM_LIT:6>],       sy+b[<NUM_LIT:7>]<EOL>v12= ex,            sy+b[<NUM_LIT:7>]<EOL>v13= sx,            sy<EOL>v14= sx+b[<NUM_LIT:4>],       sy<EOL>v15= ex-b[<NUM_LIT:6>],       sy<EOL>v16= ex,            sy<EOL>q1 = v5 +v6 +v2 +v1<EOL>q2 = v6 +v7 +v3 +v2<EOL>q3 = v7 +v8 +v4 +v3<EOL>q4 = v9 +v10+v6 +v5<EOL>q5 = v10+v11+v7 +v6<EOL>q6 = v11+v12+v8 +v7<EOL>q7 = v13+v14+v10+v9<EOL>q8 = v14+v15+v11+v10<EOL>q9 = v15+v16+v12+v11<EOL>return q1+q2+q3+q4+q5+q6+q7+q8+q9<EOL>

Called to generate the vertices used by this layer.

The length of the output of this method should be three times the :py:attr:`n_vertices` attribute.

See the source code of this method for more information about the order of the vertices.


<EOL>raise NotImplementedError("<STR_LIT>"%self.__class__.__name__)<EOL>

Method that is called to stretch the colors.

Note that this should be implemented by subclasses if plausible and reasonable.


return self.change_on_press and self.widget.pressed<EOL>

Read-only helper property to be used by styles for determining if the layer should be rendered as pressed or not.

Note that this property may not represent the actual pressed state, it will always be False if ``change_on_press`` is disabled.


return self.change_on_press and self.widget.is_hovering<EOL>

Read-only helper property to be used by styles for determining if the layer should be rendered as hovered or not.

Note that this property may not represent the actual hovering state, it will always be False if ``change_on_press`` is disabled.


return self._nmin<EOL>

Property representing the minimal value of the progressbar. Typically ``0``\ .


return self._nmax<EOL>

Property representing the maximum value of the progressbar. Typically ``100`` to represent percentages easily.


return self._n<EOL>

Property representing the current value of the progressbar.

Changing this property will activate the ``progresschange`` action.


return self.n<EOL>


assert isinstance(name,basestring) <EOL>if name in self.categories:<EOL><INDENT>raise KeyError("<STR_LIT>"%name)<EOL><DEDENT>self.categories[name]=[nmin,n,nmax]<EOL>self.redraw()<EOL>

Adds a category with the given name.

If the category already exists, a :py:exc:`KeyError` will be thrown. Use
:py:meth:`updateCategory()` instead if you want to update a category.


<EOL>if name not in self.categories:<EOL><INDENT>raise KeyError("<STR_LIT>"%name)<EOL><DEDENT>if nmin is not None:<EOL><INDENT>self.categories[name][<NUM_LIT:0>]=nmin<EOL><DEDENT>if n is not None:<EOL><INDENT>self.categories[name][<NUM_LIT:1>]=n<EOL><DEDENT>if nmax is not None:<EOL><INDENT>self.categories[name][<NUM_LIT:2>]=nmax<EOL><DEDENT>self.redraw()<EOL>self.doAction("<STR_LIT>")<EOL>

Smartly updates the given category.

Only values that are given will be updated, others will be left unchanged.

If the category does not exist, a :py:exc:`KeyError` will be thrown. Use
:py:meth:`addCategory()` instead if you want to add a category.


if name not in self.categories:<EOL><INDENT>raise KeyError("<STR_LIT>"%name)<EOL><DEDENT>del self.categories[name]<EOL>self.redraw()<EOL>

Deletes the category with the given name.

If the category does not exist, a :py:exc:`KeyError` will be thrown.


return (self.n-self.nmin)/max((self.nmax-self.nmin),<NUM_LIT:1>)<EOL>

Helper property containing the percentage this slider is "filled".

This property is read-only.


<EOL>sx,sy = self.size<EOL>x,y = self.pos<EOL>self._label.font_name = self.font_name<EOL>self._label.font_size = self.font_size<EOL>self._label.font_color = self.font_color<EOL>self._label.x = int(x+sx/<NUM_LIT>)<EOL>self._label.y = int(y+sy/<NUM_LIT>)<EOL>self._label.width = self.size[<NUM_LIT:0>]<EOL>self._label.height = self.size[<NUM_LIT:1>]<EOL>self._label._update()<EOL>

Re-draws the text by calculating its position.

Currently, the text will always be centered on the position of the label.


return self._label.text<EOL>


<EOL>sx,sy = self.size<EOL>x,y = self.pos<EOL>x = x+self.bg.border[<NUM_LIT:0>]<EOL>y = y+sy/<NUM_LIT>-self._text.font_size/<NUM_LIT><EOL>w = self.size[<NUM_LIT:0>]<EOL>h = self.size[<NUM_LIT:1>]<EOL>self._text.x,self._text.y = x,y<EOL>self._text.width,self._text.height=w,h<EOL>self._default.x,self._default.y = x,y<EOL>self._default.width,self._default.height=w,h<EOL>self._text._update() <EOL>self._default._update()<EOL>

Re-draws the label by calculating its position.

Currently, the label will always be centered on the position of the label.


return self._text.text<EOL>


return self._default.text<EOL>

Property for accessing the default text.


sx,sy = self.widget.size<EOL>x,y = self.widget.pos<EOL>bx,by = self.border<EOL>return sx,sy,x,y,bx,by<EOL>

Helper function converting the actual widget position and size into a usable and offsetted form.

This function should return a 6-tuple of ``(sx,sy,x,y,bx,by)`` where sx and sy are the size, x and y the position and bx and by are the border size.

All values should be in pixels and already include all offsets, as they are used directly for generation of vertex data.

This method can also be overridden to limit the background to a specific part of its widget.


bg = self.submenu.bg[:<NUM_LIT:3>] if isinstance(self.submenu.bg,list) or isinstance(self.submenu.bg,tuple) else [<NUM_LIT>,<NUM_LIT>,<NUM_LIT>]<EOL>o,i = bg, [min(bg[<NUM_LIT:0>]+<NUM_LIT:8>,<NUM_LIT:255>),min(bg[<NUM_LIT:1>]+<NUM_LIT:8>,<NUM_LIT:255>),min(bg[<NUM_LIT:2>]+<NUM_LIT:8>,<NUM_LIT:255>)]<EOL>s,h = [max(bg[<NUM_LIT:0>]-<NUM_LIT>,<NUM_LIT:0>),max(bg[<NUM_LIT:1>]-<NUM_LIT>,<NUM_LIT:0>),max(bg[<NUM_LIT:2>]-<NUM_LIT>,<NUM_LIT:0>)], [min(bg[<NUM_LIT:0>]+<NUM_LIT:12>,<NUM_LIT:255>),min(bg[<NUM_LIT:1>]+<NUM_LIT:12>,<NUM_LIT:255>),min(bg[<NUM_LIT:2>]+<NUM_LIT:12>,<NUM_LIT:255>)]<EOL>return bg,o,i,s,h<EOL>

Overrideable function that generates the colors to be used by various borderstyles.

Should return a 5-tuple of ``(bg,o,i,s,h)``\ .

``bg`` is the base color of the background.

``o`` is the outer color, it is usually the same as the background color.

``i`` is the inner color, it is usually lighter than the background color.

``s`` is the shadow color, it is usually quite a bit darker than the background.

``h`` is the highlight color, it is usually quite a bit lighter than the background.


self.borderstyles[name]=func<EOL>

Adds a borderstyle to the background object.

Note that borderstyles must be registered seperately for each background object.

``name`` is the (string) name of the borderstyle.

``func`` will be called with its arguments as ``(bg,o,i,s,h)``\ , see :py:meth:`getColors()` for more information.


Read-only helper property to be used by borderstyles for determining if the widget should be rendered as pressed or not.

Note that this property may not represent the actual pressed state, it will always be False if ``change_on_press`` is disabled.


Read-only helper property to be used by borderstyles for determining if the widget should be rendered as hovered or not.

Note that this property may not represent the actual hovering state, it will always be False if ``change_on_press`` is disabled.


<EOL>sx,sy = self.size<EOL>x,y = self.pos<EOL>self._label.x = x+sx/<NUM_LIT><EOL>self._label.y = y+sy/<NUM_LIT><EOL>self._label._update()<EOL>

Re-draws the label by calculating its position.

Currently, the label will always be centered on the Button.


return self._label.text<EOL>

Property for accessing the label of this Button.


<EOL>sx,sy = self.size<EOL>x,y = self.pos<EOL>self._label.anchor_x = "<STR_LIT:left>"<EOL>self._label.x = x+sx/<NUM_LIT>+sx<EOL>self._label.y = y+sy/<NUM_LIT>+sy*<NUM_LIT><EOL>self._label._update()<EOL>

Re-calculates the position of the Label.


self.submenus[submenu.name] = submenu<EOL>

Adds a :py:class:`SubMenu` to this Menu.

Note that nothing will be displayed unless a submenu is activated.


if submenu not in self.submenus:<EOL><INDENT>raise ValueError("<STR_LIT>"%submenu)<EOL><DEDENT>elif submenu == self.activeSubMenu:<EOL><INDENT>return <EOL><DEDENT>old = self.activeSubMenu<EOL>self.activeSubMenu = submenu<EOL>if old is not None:<EOL><INDENT>self.submenus[old].on_exit(submenu)<EOL>self.submenus[old].doAction("<STR_LIT>")<EOL><DEDENT>self.submenu.on_enter(old)<EOL>self.submenu.doAction("<STR_LIT>")<EOL>

Changes the submenu that is displayed.

:raises ValueError: if the name was not previously registered


super(GUIMenu,self).draw()<EOL>self.submenu.draw()<EOL>

Draws each menu layer and the active submenu.

Note that the layers are drawn first and may be overridden by the submenu and widgets.


return self.submenus[self.activeSubMenu]<EOL>

Property containing the :py:class:`SubMenu` instance that is currently active.


<EOL>self.window.set2d()<EOL>if isinstance(self.bg,Layer):<EOL><INDENT>self.bg._draw()<EOL><DEDENT>elif hasattr(self.bg,"<STR_LIT>") and callable(self.bg.draw):<EOL><INDENT>self.bg.draw()<EOL><DEDENT>elif isinstance(self.bg,list) or isinstance(self.bg,tuple):<EOL><INDENT>self.bg_vlist.draw(GL_QUADS)<EOL><DEDENT>elif callable(self.bg):<EOL><INDENT>self.bg()<EOL><DEDENT>elif isinstance(self.bg,Background):<EOL><INDENT>if not self.bg.initialized:<EOL><INDENT>self.bg.init_bg()<EOL>self.bg.redraw_bg()<EOL>self.bg.initialized=True<EOL><DEDENT><DEDENT>elif self.bg=="<STR_LIT:blank>":<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self.window.set2d()<EOL>for widget in self.widgets.values():<EOL><INDENT>if widget.do_redraw:<EOL><INDENT>widget.on_redraw()<EOL>widget.do_redraw = False<EOL><DEDENT><DEDENT>self.batch2d.draw()<EOL>for widget in self.widgets.values():<EOL><INDENT>widget.draw()<EOL><DEDENT>

Draws the submenu and its background.

Note that this leaves the OpenGL state set to 2d drawing.


self.widgets[widget.name]=widget<EOL>


return self.widgets[name]<EOL>


<EOL>if isinstance(widget,BasicWidget):<EOL><INDENT>widget = widget.name<EOL><DEDENT>if widget not in self.widgets:<EOL><INDENT>return<EOL><DEDENT>w = self.widgets[widget]<EOL>w.delete()<EOL>del self.widgets[widget]<EOL>del widget<EOL>del w<EOL>

Deletes the widget by the given name.

Note that this feature is currently experimental as there seems to be a memory leak with this method.


self.bg = bg<EOL>if isinstance(bg,list) or isinstance(bg,tuple):<EOL><INDENT>if len(bg)==<NUM_LIT:3> and isinstance(bg,list):<EOL><INDENT>bg.append(<NUM_LIT:255>)<EOL><DEDENT>self.bg_vlist.colors = bg*<NUM_LIT:4><EOL><DEDENT>elif bg in ["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"]:<EOL><INDENT>self.bg = ContainerButtonBackground(self,borderstyle=bg)<EOL>self.on_resize(self.window.width,self.window.height)<EOL><DEDENT>

Sets the background of the submenu.

The background may be a RGB or RGBA color to fill the background with.

Alternatively, a :py:class:`peng3d.layer.Layer` instance or other object with a ``.draw()`` method may be supplied.
It is also possible to supply any other method or function that will get called.

Also, the strings ``flat``\ , ``gradient``\ , ``oldshadow`` and ``material`` may be given, resulting in a background that looks similar to buttons.

Lastly, the string ``"blank"`` may be passed to skip background drawing.


self.predraw()<EOL>GUIMenu.draw(self)<EOL>self.postdraw()<EOL>


self.bg = bg<EOL>if isinstance(bg,list) or isinstance(bg,tuple):<EOL><INDENT>if len(bg)==<NUM_LIT:3> and isinstance(bg,list):<EOL><INDENT>bg.append(<NUM_LIT:255>)<EOL><DEDENT>self.bg_vlist.colors = bg*<NUM_LIT:4><EOL><DEDENT>elif bg in ["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"]:<EOL><INDENT>self.bg = ContainerButtonBackground(self,borderstyle=bg,batch=self.batch2d)<EOL>self.redraw()<EOL><DEDENT>

Sets the background of the Container.

Similar to :py:meth:`peng3d.gui.SubMenu.setBackground()`\ , but only effects the region covered by the Container.


if self is widget: <EOL><INDENT>return<EOL><DEDENT>self.widgets[widget.name]=widget<EOL>

Adds a widget to this container.

Note that trying to add the Container to itself will be ignored.


if not self.visible:<EOL><INDENT>return<EOL><DEDENT>if not isinstance(self.submenu,Container):<EOL><INDENT>glEnable(GL_SCISSOR_TEST)<EOL>glScissor(*self.pos+self.size)<EOL><DEDENT>SubMenu.draw(self)<EOL>if not isinstance(self.submenu,Container):<EOL><INDENT>glDisable(GL_SCISSOR_TEST)<EOL><DEDENT>

Draws the submenu and its background.

Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.


x,y = self.pos<EOL>sx,sy = self.size<EOL>self.bg_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy]<EOL>self.stencil_vlist.vertices = [x,y, x+sx,y, x+sx,y+sy, x,y+sy]<EOL>if isinstance(self.bg,Background):<EOL><INDENT>if not self.bg.initialized:<EOL><INDENT>self.bg.init_bg()<EOL>self.bg.initialized=True<EOL><DEDENT>self.bg.redraw_bg()<EOL><DEDENT>

Redraws the background and any child widgets.


pass<EOL>

Dummy method defined for compatibility with :py:class:`peng3d.gui.SubMenu`, simply does nothing.


pass<EOL>


n = self._scrollbar.n<EOL>self.offset_y = -n <EOL>sx=<NUM_LIT> <EOL>sy=self.size[<NUM_LIT:1>]<EOL>x=self.size[<NUM_LIT:0>]-sx<EOL>y=<NUM_LIT:0> <EOL>self._scrollbar._size = sx,sy<EOL>self._scrollbar._pos = x,y<EOL>self._scrollbar._nmax = self.content_height<EOL>super(ScrollableContainer,self).on_redraw()<EOL>

Redraws the background and contents, including scrollbar.

This method will also check the scrollbar for any movement and will be automatically called on movement of the slider.


for name,fname in self.WIDGETS.items():<EOL><INDENT>if name in kwargs and kwargs[name] is not None:<EOL><INDENT>assert hasattr(self,fname)<EOL>assert callable(getattr(self,fname))<EOL>getattr(self,fname)(kwargs[name])<EOL><DEDENT><DEDENT>

Called by the initializer to add all widgets.

Widgets are discovered by searching through the :py:attr:`WIDGETS` class attribute.
If a key in :py:attr:`WIDGETS` is also found in the keyword arguments and
not none, the function with the name given in the value of the key will
be called with its only argument being the value of the keyword argument.

For more complex usage scenarios, it is also possible to override this method
in a subclass, but the original method should always be called to ensure
compatibility with classes relying on this feature.


<EOL>self.wlabel_main = text.Label("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw/<NUM_LIT:2>,sh/<NUM_LIT:2>-bh/<NUM_LIT:2>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label=label_main,<EOL>)<EOL>self.wlabel_main.size = lambda sw,sh: (sw,self.wlabel_main._label.font_size)<EOL>self.addWidget(self.wlabel_main)<EOL>

Adds the main label of the dialog.

This widget can be triggered by setting the label ``label_main`` to a string.

This widget will be centered on the screen.


<EOL>self.wbtn_ok = button.Button("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw/<NUM_LIT:2>,sh/<NUM_LIT:2>-bh/<NUM_LIT:2>-bh*<NUM_LIT:2>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label=label_ok,<EOL>borderstyle=self.borderstyle<EOL>)<EOL>self.wbtn_ok.size = lambda sw,sh: (self.wbtn_ok._label.font_size*<NUM_LIT:8>,self.wbtn_ok._label.font_size*<NUM_LIT:2>)<EOL>self.addWidget(self.wbtn_ok)<EOL>def f():<EOL><INDENT>self.doAction("<STR_LIT>")<EOL>self.exitDialog()<EOL><DEDENT>self.wbtn_ok.addAction("<STR_LIT>",f)<EOL>

Adds an OK button to allow the user to exit the dialog.

This widget can be triggered by setting the label ``label_ok`` to a string.

This widget will be mostly centered on the screen, but below the main label
by the double of its height.


<EOL>return self.wlabel_main.label<EOL>

Property that proxies the ``label_main`` label.

Setting this property will cause the ``label_main_change`` action to trigger.

Note that trying to access this property if the widget is not used may cause
an error.


return self.wbtn_ok.label<EOL>

Property that proxies the ``label_ok`` label.

Setting this property will cause the ``label_ok_change`` action to trigger.

Note that trying to access this property if the widget is not used may cause
an error.


if self.prev_submenu is not None:<EOL><INDENT>self.menu.changeSubMenu(self.prev_submenu)<EOL><DEDENT>self.prev_submenu = None<EOL>

Helper method that exits the dialog.

This method will cause the previously active submenu to activate.


<EOL>self.menu.changeSubMenu(self.name)<EOL>

Helper method to enter the dialog.

Calling this method will simply cause the dialog to become the active submenu.

Note that is not necessary to call this method over :py:meth:`changeSubMenu()`\ ,
as the storing of the previous submenu is done elsewhere.


<EOL>self.wbtn_confirm = button.Button("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw-<NUM_LIT:4>,sh/<NUM_LIT:2>-bh/<NUM_LIT:2>-bh*<NUM_LIT:2>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label=label_confirm,<EOL>borderstyle=self.borderstyle<EOL>)<EOL>self.wbtn_confirm.size = lambda sw,sh: (self.wbtn_confirm._label.font_size*<NUM_LIT:8>,self.wbtn_confirm._label.font_size*<NUM_LIT:2>)<EOL>self.addWidget(self.wbtn_confirm)<EOL>def f():<EOL><INDENT>self.doAction("<STR_LIT>")<EOL>self.exitDialog()<EOL><DEDENT>self.wbtn_confirm.addAction("<STR_LIT>",f)<EOL>

Adds a confirm button to let the user confirm whatever action they were presented with.

This widget can be triggered by setting the label ``label_confirm`` to a string.

This widget will be positioned slightly below the main label and to the left
of the cancel button.


<EOL>self.wbtn_cancel = button.Button("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>+<NUM_LIT:4>,sh/<NUM_LIT:2>-bh/<NUM_LIT:2>-bh*<NUM_LIT:2>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label=label_cancel,<EOL>borderstyle=self.borderstyle<EOL>)<EOL>self.wbtn_cancel.size = lambda sw,sh: (self.wbtn_cancel._label.font_size*<NUM_LIT:8>,self.wbtn_cancel._label.font_size*<NUM_LIT:2>)<EOL>self.addWidget(self.wbtn_cancel)<EOL>def f():<EOL><INDENT>self.doAction("<STR_LIT>")<EOL>self.exitDialog()<EOL><DEDENT>self.wbtn_cancel.addAction("<STR_LIT>",f)<EOL>

Adds a cancel button to let the user cancel whatever choice they were given.

This widget can be triggered by setting the label ``label_cancel`` to a string.

This widget will be positioned slightly below the main label and to the right
of the confirm button.


return self.wbtn_confirm.label<EOL>

Property that proxies the ``label_confirm`` label.

Setting this property will cause the ``label_confirm_change`` action to trigger.

Note that trying to access this property if the widget is not used may cause
an error.


return self.wbtn_cancel.label<EOL>

Property that proxies the ``label_cancel`` label.

Setting this property will cause the ``label_cancel_change`` action to trigger.

Note that trying to access this property if the widget is not used may cause
an error.


<EOL>self.wprogressbar = slider.Progressbar("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw/<NUM_LIT:2>,self.wlabel_main.pos[<NUM_LIT:1>]-bh*<NUM_LIT>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>borderstyle=self.borderstyle<EOL>)<EOL>self.addWidget(self.wprogressbar)<EOL>self.wprogresslabel = text.Label("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw/<NUM_LIT:2>,self.wprogressbar.pos[<NUM_LIT:1>]+<NUM_LIT:8>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label="<STR_LIT>", <EOL>)<EOL>self.wprogresslabel.size = lambda sw,sh: (sw,self.wprogresslabel._label.font_size)<EOL>self.addWidget(self.wprogresslabel)<EOL>self.wprogressbar.size = lambda sw,sh: (sw*<NUM_LIT>,self.wprogresslabel._label.font_size+<NUM_LIT:10>)<EOL>self._label_progressbar = label_progressbar<EOL>if getattr(label_progressbar,"<STR_LIT>",False):<EOL><INDENT>def f():<EOL><INDENT>self.label_progressbar = str(label_progressbar)<EOL><DEDENT>self.peng.i18n.addAction("<STR_LIT>",f)<EOL><DEDENT>self.wprogressbar.addAction("<STR_LIT>",self.update_progressbar)<EOL>self.update_progressbar()<EOL>

Adds a progressbar and label displaying the progress within a certain task.

This widget can be triggered by setting the label ``label_progressbar`` to
a string.

The progressbar will be displayed centered and below the main label.
The progress label will be displayed within the progressbar.

The label of the progressbar may be a string containing formatting codes
which will be resolved via the ``format()`` method.

Currently, there are six keys available:

``n`` and ``value`` are the current progress rounded to 4 decimal places.

``nmin`` is the minimum progress value rounded to 4 decimal places.

``nmax`` is the maximum progress value rounded to 4 decimal places.

``p`` and ``percent`` are the percentage value that the progressbar is completed
rounded to 4 decimal places.

By default, the progressbar label will be ``{percent}%`` displaying the percentage
the progressbar is complete.


n,nmin,nmax = self.wprogressbar.n,self.wprogressbar.nmin,self.wprogressbar.nmax<EOL>if (nmax-nmin)==<NUM_LIT:0>:<EOL><INDENT>percent = <NUM_LIT:0> <EOL><DEDENT>else:<EOL><INDENT>percent = max(min((n-nmin)/(nmax-nmin),<NUM_LIT:1.>),<NUM_LIT:0.>)*<NUM_LIT:100><EOL><DEDENT>dat = {"<STR_LIT:value>":round(n,<NUM_LIT:4>),"<STR_LIT:n>":round(n,<NUM_LIT:4>),"<STR_LIT>":round(nmin,<NUM_LIT:4>),"<STR_LIT>":round(nmax,<NUM_LIT:4>),"<STR_LIT>":round(percent,<NUM_LIT:4>),"<STR_LIT:p>":round(percent,<NUM_LIT:4>)}<EOL>txt = self._label_progressbar.format(**dat)<EOL>self.wprogresslabel.label = txt<EOL>

Updates the progressbar by re-calculating the label.

It is not required to manually call this method since setting any of the
properties of this class will automatically trigger a re-calculation.


return self.wprogressbar.n<EOL>

Property that proxies the ``progress_n`` label.

Setting this property will cause the progressbar label to be recalculated.

Additionally, if the supplied value is higher than the maximum value and
:py:attr:`auto_exit` is true, the dialog will exit.


return self.wprogressbar.nmin<EOL>

Property that proxies the ``progress_nmin`` label.

Setting this property will cause the progressbar label to be recalculated.

Note that setting this property if the widget has not been initialized may
cause various errors to occur.


return self.wprogressbar.nmax<EOL>

Property that proxies the ``progress_nmax`` label.

Setting this property will cause the progressbar label to be recalculated.

Note that setting this property if the widget has not been initialized may
cause various errors to occur.


return self.wprogresslabel.label<EOL>

Property that proxies the ``label_progressbar`` label.

Setting this property will cause the progressbar label to be recalculated.

Note that setting this property if the widget has not been initialized may
cause various errors to occur.


<EOL>self.wprogressbar = slider.AdvancedProgressbar("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw/<NUM_LIT:2>,self.wlabel_main.pos[<NUM_LIT:1>]-bh*<NUM_LIT>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>borderstyle=self.borderstyle<EOL>)<EOL>self.addWidget(self.wprogressbar)<EOL>self.wprogresslabel = text.Label("<STR_LIT>",self,self.window,self.peng,<EOL>pos=lambda sw,sh, bw,bh: (sw/<NUM_LIT:2>-bw/<NUM_LIT:2>,self.wprogressbar.pos[<NUM_LIT:1>]+<NUM_LIT:8>),<EOL>size=[<NUM_LIT:0>,<NUM_LIT:0>],<EOL>label="<STR_LIT>", <EOL>)<EOL>self.wprogresslabel.size = lambda sw,sh: (sw,self.wprogresslabel._label.font_size)<EOL>self.addWidget(self.wprogresslabel)<EOL>self.wprogressbar.size = lambda sw,sh: (sw*<NUM_LIT>,self.wprogresslabel._label.font_size+<NUM_LIT:10>)<EOL>self._label_progressbar = label_progressbar<EOL>if getattr(label_progressbar,"<STR_LIT>",False):<EOL><INDENT>def f():<EOL><INDENT>self.label_progressbar = str(label_progressbar)<EOL><DEDENT>self.peng.i18n.addAction("<STR_LIT>",f)<EOL><DEDENT>self.wprogressbar.addAction("<STR_LIT>",self.update_progressbar)<EOL>self.update_progressbar()<EOL>


return self.wprogressbar.addCategory(*args,**kwargs)<EOL>

Proxy for :py:meth:`~peng3d.gui.slider.AdvancedProgressbar.addCategory()`\ .


return self.wprogressbar.updateCategory(*args,**kwargs)<EOL>

Proxy for :py:meth:`~peng3d.gui.slider.AdvancedProgressbar.updateCategory()`\ .


return self.wprogressbar.deleteCategory(*args,**kwargs)<EOL>

Proxy for :py:meth:`~peng3d.gui.slider.AdvancedProgressbar.deleteCategory()`\ .


pass<EOL>

Called just before the background will be drawn the first time.

Commonly used to initialize vertex lists.

It is recommended to add all vertex lists to the ``submenu.batch2d`` Batch to speed up rendering and preventing glitches with grouping.


pass<EOL>

Method called by the parent widget every time its :py:meth:`Widget.redraw()` method is called.


Registers a vertex list to the internal list.

This allows the class to clean itself up properly during deletion, as the background would still be visible after deletion otherwise.


return self.widget.submenu<EOL>

Property for accessing the parent widget's submenu.


return self.widget.window<EOL>

Property for accessing the parent widget's window.


return self.widget.peng<EOL>

Property for accessing the parent widget's instance of :py:class:`peng3d.peng.Peng`\ .


return self.widget.pressed<EOL>

Read-only helper property for easier access.

Equivalent to ``widget.pressed``\ .


return self.widget.is_hovering<EOL>

Read-only helper property for easier access.

Equivalent to ``widget.is_hovering``\ .


Registers event handlers used by this widget, e.g. mouse click/motion and window resize.

This will allow the widget to redraw itself upon resizing of the window in case the position needs to be adjusted.


if isinstance(self._pos,list) or isinstance(self._pos,tuple):<EOL><INDENT>r = self._pos<EOL><DEDENT>elif callable(self._pos):<EOL><INDENT>w,h = self.submenu.size[:]<EOL>r = self._pos(w,h,*self.size)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>ox,oy = self.submenu.pos<EOL>r = r[<NUM_LIT:0>]+ox,r[<NUM_LIT:1>]+oy<EOL>return _WatchingList(r,self._wlredraw_pos)<EOL>

Property that will always be a 2-tuple representing the position of the widget.

Note that this method may call the method given as ``pos`` in the initializer.

The returned object will actually be an instance of a helper class to allow for setting only the x/y coordinate.

This property also respects any :py:class:`Container` set as its parent, any offset will be added automatically.

Note that setting this property will override any callable set permanently.


if isinstance(self._size,list) or isinstance(self._size,tuple):<EOL><INDENT>s = self._size<EOL><DEDENT>elif callable(self._size):<EOL><INDENT>w,h = self.submenu.size[:]<EOL>s = self._size(w,h)<EOL><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>s = s[:]<EOL>if s[<NUM_LIT:0>]==-<NUM_LIT:1>:<EOL><INDENT>s[<NUM_LIT:0>]=self.getMinSize()[<NUM_LIT:0>]<EOL><DEDENT>if s[<NUM_LIT:1>]==-<NUM_LIT:1>:<EOL><INDENT>s[<NUM_LIT:1>]=self.getMinSize()[<NUM_LIT:1>]<EOL><DEDENT>s = [max(s[<NUM_LIT:0>],<NUM_LIT:0>),max(s[<NUM_LIT:1>],<NUM_LIT:0>)]<EOL>return _WatchingList(s,self._wlredraw_size)<EOL>

Similar to :py:attr:`pos` but for the size instead.


if not isinstance(self.submenu,Container):<EOL><INDENT>return self.submenu.name == self.submenu.menu.activeSubMenu and self.submenu.menu.name == self.window.activeMenu and self.enabled<EOL><DEDENT>else:<EOL><INDENT>return self.submenu.clickable and self.enabled<EOL><DEDENT>

Property used for determining if the widget should be clickable by the user.

This is only true if the submenu of this widget is active and this widget is enabled.

The widget may be either disabled by setting this property or the :py:attr:`enabled` attribute.


return self._enabled<EOL>

Property used for storing whether or not this widget is enabled.

May influence rendering and behavior.

Note that the widget will be immediately redrawn if this property is changed.


<EOL>if self.pressed:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif self.is_hovering:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif not self.enabled:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>

Returns the current state of the widget.

One of ``"pressed"``\ , ``"hover"``\ , ``"disabled"`` or ``"idle"``\ .
Note that some information may be lost by getting this state,
for example it is not possible to know if the widget is hovered or not
if ``"pressed"`` is returned. However, this should not be a problem for
most intended uses of this method.


if self.do_redraw:<EOL><INDENT>self.on_redraw()<EOL>self.do_redraw = False<EOL><DEDENT>

Draws all vertex lists associated with this widget.


<EOL>self.do_redraw = True<EOL>

Triggers a redraw of the widget.

Note that the redraw may not be executed instantly, but rather batched together on the next frame.
If an instant and synchronous redraw is needed, use :py:meth:`on_redraw()` instead.


pass<EOL>

Callback to be overridden by subclasses called if redrawing the widget seems necessary.

Note that this method should not be called manually, see :py:meth:`redraw()` instead.


<EOL>del self.bg.widget<EOL>del self.bg<EOL>del self._pos<EOL>del self._size<EOL>self.actions = {}<EOL>for e_type,e_handlers in self.peng.eventHandlers.items():<EOL><INDENT>if True or e_type in eh:<EOL><INDENT>to_del = []<EOL>for e_handler in e_handlers:<EOL><INDENT>if isinstance(e_handler,weakref.ref): <EOL><INDENT>if super(weakref.WeakMethod,e_handler).__call__() is self: <EOL><INDENT>to_del.append(e_handler) <EOL><DEDENT><DEDENT>elif e_handler is self: <EOL><INDENT>to_del.append(e_handler)<EOL><DEDENT><DEDENT>for d in to_del:<EOL><INDENT>try:<EOL><INDENT>del e_handlers[e_handlers.index(d)]<EOL><DEDENT>except Exception:<EOL><INDENT>import traceback;traceback.print_exc()<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Deletes resources of this widget that require manual cleanup.

Currently removes all actions, event handlers and the background.

The background itself should automatically remove all vertex lists to avoid visual artifacts.

Note that this method is currently experimental, as it seems to have a memory leak.


self.bg = bg<EOL>self.redraw()<EOL>

Sets the background of the widget.

This may cause the background to be initialized.


if self.bg is not None:<EOL><INDENT>if not self.bg.initialized:<EOL><INDENT>self.bg.init_bg()<EOL>self.bg.initialized=True<EOL><DEDENT>self.bg.redraw_bg()<EOL><DEDENT>super(Widget,self).on_redraw()<EOL>

Draws the background and the widget itself.

Subclasses should use ``super()`` to call this method, or rendering may glitch out.


Registers needed keybinds and schedules the :py:meth:`update` Method.

You can control what keybinds are used via the :confval:`controls.controls.forward` etc. Configuration Values.


if not self.enabled:<EOL><INDENT>return<EOL><DEDENT>speed = self.movespeed<EOL>d = dt * speed <EOL>dx, dy, dz = self.get_motion_vector()<EOL>dx, dy, dz = dx * d, dy * d, dz * d<EOL>x,y,z = self.actor._pos<EOL>newpos = dx+x, dy+y, dz+z<EOL>self.actor.pos = newpos<EOL>

Should be called regularly to move the actor.

This method does nothing if the :py:attr:`enabled` property is set to false.

Note that this method is called automatically and should not be manually called.


if any(self.move):<EOL><INDENT>x, y = self.actor._rot<EOL>strafe = math.degrees(math.atan2(*self.move))<EOL>y_angle = math.radians(y)<EOL>x_angle = math.radians(x + strafe)<EOL>dy = <NUM_LIT:0.0><EOL>dx = math.cos(x_angle)<EOL>dz = math.sin(x_angle)<EOL><DEDENT>else:<EOL><INDENT>dy = <NUM_LIT:0.0><EOL>dx = <NUM_LIT:0.0><EOL>dz = <NUM_LIT:0.0><EOL><DEDENT>return (dx, dy, dz)<EOL>

Returns the movement vector according to held buttons and the rotation.

:return: 3-Tuple of ``(dx,dy,dz)``
:rtype: tuple


self.world.registerEventHandler("<STR_LIT>",self.on_mouse_motion)<EOL>self.world.registerEventHandler("<STR_LIT>",self.on_mouse_drag)<EOL>

Registers the motion and drag handlers.

Note that because of the way pyglet treats mouse dragging, there is also an handler registered to the on_mouse_drag event.


Registers the up and down handlers.

Also registers a scheduled function every 60th of a second, causing pyglet to redraw your window with 60fps.


if not self.enabled:<EOL><INDENT>return<EOL><DEDENT>dy = self.speed * dt * self.move<EOL>x,y,z = self.actor._pos<EOL>newpos = x,dy+y,z<EOL>self.actor.pos = newpos<EOL>

Should be called regularly to move the actor.

This method does nothing if the :py:attr:`enabled` property is set to False.

This method is called automatically and should not be called manually.


speed = self.movespeed<EOL>d = dt * speed <EOL>dx, dy, dz = self.get_motion_vector()<EOL>dx, dy, dz = dx * d, dy * d, dz * d<EOL>x,y,z = self._pos<EOL>newpos = dx+x, dy+y, dz+z<EOL>self.pos = newpos<EOL>

Internal method used for moving the player.

:param float dt: Time delta since the last call to this method


if any(self.move):<EOL><INDENT>x, y = self._rot<EOL>strafe = math.degrees(math.atan2(*self.move))<EOL>y_angle = math.radians(y)<EOL>x_angle = math.radians(x + strafe)<EOL>dy = <NUM_LIT:0.0><EOL>dx = math.cos(x_angle)<EOL>dz = math.sin(x_angle)<EOL><DEDENT>else:<EOL><INDENT>dy = <NUM_LIT:0.0><EOL>dx = <NUM_LIT:0.0><EOL>dz = <NUM_LIT:0.0><EOL><DEDENT>return (dx, dy, dz)<EOL>


pass<EOL>

Method to be overridden by subclasses for registering event handlers.

Automatically called upon object creation.


return self._enabled and self.actor.controlleroptions["<STR_LIT>"]<EOL>

Property allowing to get and set if this controller should be active.

When getting this property, the result of ANDing the internal flag and the actor flag is returned.

When setting, only the local internal flag is set, allowing other controllers to still work.

:raises AssertionError: when the supplied value is not of type bool


self.controllers.append(controller)<EOL>

Adds a controller to the actor.

A controller can control its actor and can act as a bridge between actor and user inputs.

Controllers may be added anytime during the lifetime of an actor.


if self.model is not None:<EOL><INDENT>self.model.cleanup(self)<EOL><DEDENT>self.model = model<EOL>model.create(self)<EOL>

Sets the model this actor should use when drawing.

This method also automatically initializes the new model and removes the old, if any.


if self.model is None:<EOL><INDENT>raise RuntimeError("<STR_LIT>")<EOL><DEDENT>self.model.setAnimation(self,animation,transition,force)<EOL>

Sets the animation the model of this actor should show.

``animation`` is the name of the animation to switch to.

``transition`` can be used to override the transition between the animations.

``force`` can be used to force reset the animation even if it is already running.

If there is no model set for this actor, a :py:exc:`RuntimeError` will be raised.


if self.model is not None:<EOL><INDENT>self.model.draw(self)<EOL><DEDENT>

Called by :py:meth:`World.render3d()` to render this actor.

By default, this method calls the draw method of its model, if any.

For custom render behavior, it is recommended to extend this method or modify the model.


pass<EOL>

Fake event handler called if the location of this actor changes.

This handler is called after the location has changed.

:param list old: The previous position


return self._pos<EOL>

Property allowing access to the position of this actor.

This actor is read-write but calls :py:meth:`on_move()` if it is set.


x, y = self._rot<EOL>y_angle = math.radians(y)<EOL>x_angle = math.radians(x)<EOL>m = math.cos(y_angle)<EOL>dy = math.sin(y_angle)<EOL>dy = <NUM_LIT:0.0><EOL>dx = math.cos(x_angle)<EOL>dz = math.sin(x_angle)<EOL>dx,dy,dz = dx*dist,dy*dist,dz*dist<EOL>x,y,z = self._pos<EOL>self.pos = x+dx,y+dy,z+dz<EOL>return dx,dy,dz<EOL>

Moves the actor using standard trigonometry along the current rotational vector.

:param float dist: Distance to move

.. todo::

   Test this method, also with negative distances


pass<EOL>

Fake event handler called if the rotation of this actor changes.

This handler is called after the rotation has been made.

:param tuple old: Old rotation before rotating


return self._rot<EOL>

Property for accessing the rotation of this actor.

Rotation is a tuple of ``(x,y)`` where y is clamped to -90 and 90.
x rolls over at 360, resulting in a seamless experience for players.

This property may also be written to, this calls :py:meth:`on_rotate()`\ .


keybind = keybind.lower()<EOL>if mod:<EOL><INDENT>if keybind not in self.keybinds:<EOL><INDENT>self.keybinds[keybind]=[]<EOL><DEDENT>self.keybinds[keybind].append(kbname)<EOL><DEDENT>else:<EOL><INDENT>if keybind not in self.keybinds_nm:<EOL><INDENT>self.keybinds_nm[keybind]=[]<EOL><DEDENT>self.keybinds_nm[keybind].append(kbname)<EOL><DEDENT>self.kbname[kbname]=handler<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.peng,"<STR_LIT>":keybind,"<STR_LIT>":kbname,"<STR_LIT>":handler,"<STR_LIT>":mod})<EOL>

Adds a keybind to the internal registry.

Keybind names should be of the format ``namespace:category.subcategory.name``\ e.g. ``peng3d:actor.player.controls.forward`` for the forward key combo for the player actor.

:param str keybind: Keybind string, as described above
:param str kbname: Name of the keybind, may be used to later change the keybinding without re-registering
:param function handler: Function or any other callable called with the positional arguments ``(symbol,modifiers,release)`` if the keybind is pressed or released
:param int mod: If the keybind should respect modifiers


for key,value in self.keybinds.items():<EOL><INDENT>if kbname in value:<EOL><INDENT>del value[value.index(kbname)]<EOL>break<EOL><DEDENT><DEDENT>if combo not in self.keybinds:<EOL><INDENT>self.keybinds[combo]=[]<EOL><DEDENT>self.keybinds[combo].append(kbname)<EOL>self.peng.sendEvent("<STR_LIT>",{"<STR_LIT>":self.peng,"<STR_LIT>":kbname,"<STR_LIT>":combo})<EOL>

Changes a keybind of a specific keybindname.

:param str kbname: Same as kbname of :py:meth:`add()`
:param str combo: New key combination


modifier = MODNAME2MODIFIER[modname.lower()]<EOL>return modifiers&modifier<EOL>

Helper method to simplify checking if a modifier is held.

:param str modname: Name of the modifier, see :py:data:`MODNAME2MODIFIER`
:param int modifiers: Bitmask to check in, same as the modifiers argument of the on_key_press etc. handlers


Handles a key combination and dispatches associated events.

First, all keybind handlers registered via :py:meth:`add` will be handled,
then the pyglet event :peng3d:pgevent:`on_key_combo` with params ``(combo,symbol,modifiers,release,mod)`` is sent to the :py:class:`Peng()` instance.

Also sends the events :peng3d:event:`peng3d:keybind.combo`\, :peng3d:event:`peng3d:keybind.combo.press` and :peng3d:event`peng3d:keybind.combo.release`\ .

:params str combo: Key combination pressed
:params int symbol: Key pressed, passed from the same argument within pyglet
:params int modifiers: Modifiers held while the key was pressed
:params bool release: If the combo was released
:params bool mod: If the combo was sent without mods


def decorate(wrapped):<EOL><INDENT>if sys.version_info[<NUM_LIT:0>] == <NUM_LIT:2>:<EOL><INDENT>arg_names, varargs, _, defaults = inspect.getargspec(wrapped)<EOL><DEDENT>else:<EOL><INDENT>arg_names, varargs, _, defaults = inspect.getfullargspec(wrapped)[:<NUM_LIT:4>]<EOL><DEDENT>if not defaults:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>first_default_index = len(arg_names) - len(defaults)<EOL>if name is FIRST_DEFAULT_ARG:<EOL><INDENT>first_kwonly_index = first_default_index<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>first_kwonly_index = arg_names.index(name)<EOL><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>" % (<EOL>getattr(wrapped, '<STR_LIT>', '<STR_LIT:?>'), name))<EOL><DEDENT><DEDENT>if first_kwonly_index < first_default_index:<EOL><INDENT>raise ValueError("<STR_LIT>" % (name,))<EOL><DEDENT>kwonly_defaults = defaults[-(len(arg_names)-first_kwonly_index):]<EOL>kwonly_args = tuple(zip(arg_names[first_kwonly_index:], kwonly_defaults))<EOL>required_kwonly_args = frozenset(arg for arg, default in kwonly_args if default is KWONLY_REQUIRED)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>if required_kwonly_args:<EOL><INDENT>missing_kwonly_args = required_kwonly_args.difference(kwargs.keys())<EOL>if missing_kwonly_args:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>getattr(wrapped, '<STR_LIT>', '<STR_LIT:?>'), len(missing_kwonly_args),<EOL>'<STR_LIT:U+002CU+0020>'.join(sorted(missing_kwonly_args))))<EOL><DEDENT><DEDENT>if len(args) > first_kwonly_index:<EOL><INDENT>if varargs is None:<EOL><INDENT>raise TypeError("<STR_LIT>" % (<EOL>getattr(wrapped, '<STR_LIT>', '<STR_LIT:?>'), first_kwonly_index, len(args)))<EOL><DEDENT>kwonly_args_from_kwargs = tuple(kwargs.pop(arg, default) for arg, default in kwonly_args)<EOL>args = args[:first_kwonly_index] + kwonly_args_from_kwargs + args[first_kwonly_index:]<EOL><DEDENT>return wrapped(*args, **kwargs)<EOL><DEDENT>return update_wrapper(wrapper, wrapped)<EOL><DEDENT>return decorate<EOL>

Emulates keyword-only arguments under python2. Works with both python2 and python3.
    With this decorator you can convert all or some of the default arguments of your function
    into kwonly arguments. Use ``KWONLY_REQUIRED`` as the default value of required kwonly args.

    :param name: The name of the first default argument to be treated as a keyword-only argument. This default
    argument along with all default arguments that follow this one will be treated as keyword only arguments.

    You can also pass here the ``FIRST_DEFAULT_ARG`` constant in order to select the first default argument. This
    way you turn all default arguments into keyword-only arguments. As a shortcut you can use the
    ``@kwonly_defaults`` decorator (without any parameters) instead of ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``.

        >>> from kwonly_args import first_kwonly_arg, KWONLY_REQUIRED, FIRST_DEFAULT_ARG, kwonly_defaults
        >>>
        >>> # this decoration converts the ``d1`` and ``d2`` default args into kwonly args
        >>> @first_kwonly_arg('d1')
        >>> def func(a0, a1, d0='d0', d1='d1', d2='d2', *args, **kwargs):
        >>>     print(a0, a1, d0, d1, d2, args, kwargs)
        >>>
        >>> func(0, 1, 2, 3, 4)
        0 1 2 d1 d2 (3, 4) {}
        >>>
        >>> func(0, 1, 2, 3, 4, d2='my_param')
        0 1 2 d1 my_param (3, 4) {}
        >>>
        >>> # d0 is an optional deyword argument, d1 is required
        >>> def func(d0='d0', d1=KWONLY_REQUIRED):
        >>>     print(d0, d1)
        >>>
        >>> # The ``FIRST_DEFAULT_ARG`` constant automatically selects the first default argument so it
        >>> # turns all default arguments into keyword-only ones. Both d0 and d1 are keyword-only arguments.
        >>> @first_kwonly_arg(FIRST_DEFAULT_ARG)
        >>> def func(a0, a1, d0='d0', d1='d1'):
        >>>     print(a0, a1, d0, d1)
        >>>
        >>> # ``@kwonly_defaults`` is a shortcut for the ``@first_kwonly_arg(FIRST_DEFAULT_ARG)``
        >>> # in the previous example. This example has the same effect as the previous one.
        >>> @kwonly_defaults
        >>> def func(a0, a1, d0='d0', d1='d1'):
        >>>     print(a0, a1, d0, d1)


for attr_name in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>attr_value = getattr(wrapped, attr_name, None)<EOL>if attr_value is not None:<EOL><INDENT>setattr(wrapper, attr_name, attr_value)<EOL><DEDENT><DEDENT>wrapper.__dict__.update(getattr(wrapped, '<STR_LIT>', {}))<EOL>return wrapper<EOL>

To be used under python2.4 because functools.update_wrapper() is available only from python2.5+


version_dir = path.abspath(path.dirname(module_file))<EOL>version_file = path.join(version_dir, "<STR_LIT>")<EOL>return version_dir, version_file<EOL>

For the given module file (usually found by:

    from package import __file__ as module_file

in the caller, return the location of
the current RELEASE-VERSION file and the file
itself.


try:<EOL><INDENT>if not items:<EOL><INDENT>from .example import ExampleCommand<EOL>from .version import Version<EOL>items = [(ExampleCommand.NAME, ExampleCommand),<EOL>(Version.NAME, Version)]<EOL><DEDENT>main("<STR_LIT>", items=items)<EOL><DEDENT>except Stop as stop:<EOL><INDENT>print(stop)<EOL>sys.exit(stop.rc)<EOL><DEDENT>except SystemExit:<EOL><INDENT>raise<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>print("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>except Exception:<EOL><INDENT>traceback.print_exc()<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT>

External entry point which calls main() and
if Stop is raised, calls sys.exit()


def main(fw_name, args=None, items=None):

global DEBUG_LEVEL<EOL>global FRAMEWORK_NAME<EOL>debug_name = "<STR_LIT>" % fw_name.upper()<EOL>if debug_name in os.environ:<EOL><INDENT>try:<EOL><INDENT>DEBUG_LEVEL = int(os.environ.get(debug_name))<EOL><DEDENT>except ValueError:<EOL><INDENT>DEBUG_LEVEL = <NUM_LIT:10>  <EOL><DEDENT><DEDENT>FRAMEWORK_NAME = fw_name<EOL>if args is None:<EOL><INDENT>args = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>if items is None:<EOL><INDENT>items = list(globals().items())<EOL><DEDENT>yaclifw_parser, sub_parsers = parsers()<EOL>for name, MyCommand in sorted(items):<EOL><INDENT>if not isinstance(MyCommand, type):<EOL><INDENT>continue<EOL><DEDENT>if not issubclass(MyCommand, Command):<EOL><INDENT>continue<EOL><DEDENT>if MyCommand.NAME == "<STR_LIT>":<EOL><INDENT>continue<EOL><DEDENT>MyCommand(sub_parsers)<EOL><DEDENT>ns = yaclifw_parser.parse_args(args)<EOL>ns.func(ns)<EOL>if hasattr(ns, '<STR_LIT>'):<EOL><INDENT>if callable(ns.callback):<EOL><INDENT>ns.callback()<EOL><DEDENT>else:<EOL><INDENT>raise Stop(<NUM_LIT:3>, "<STR_LIT>")<EOL><DEDENT><DEDENT>

Reusable entry point. Arguments are parsed
via the argparse-subcommands configured via
each Command class found in globals(). Stop
exceptions are propagated to callers.

The name of the framework will be used in logging
and similar.


def smart_space(match):<EOL><INDENT>before = match.group(<NUM_LIT:1>)<EOL>after = match.group(<NUM_LIT:2>)<EOL>space = '<STR_LIT:U+0020>'<EOL>if before == '<STR_LIT:>>' or after == '<STR_LIT:<>':<EOL><INDENT>space = '<STR_LIT>'<EOL><DEDENT>return before + space + after<EOL><DEDENT>html = re.sub(<EOL>r'<STR_LIT>',<EOL>smart_space,<EOL>html,<EOL>)<EOL>return html.strip()<EOL>

Remove insignificant whitespace from the html.

>>> print collapse_html('''\\
...

...         Heading
...

... ''')

Heading

>>> print collapse_html('''\\
...

...         Paragraph with
...         multiple lines.
...

... ''')

Paragraph with multiple lines.


subprocess.call(<EOL>[<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>docx_path,<EOL>file_path,<EOL>],<EOL>)<EOL>

This will convert ``file_path`` to docx and place the converted file at
``docx_path``


if not new_ext.startswith(os.extsep):<EOL><INDENT>new_ext = os.extsep + new_ext<EOL><DEDENT>index = file_path.rfind(os.extsep)<EOL>return file_path[:index] + new_ext<EOL>

>>> replace_ext('one/two/three.four.doc', '.html')
'one/two/three.four.html'
>>> replace_ext('one/two/three.four.DOC', '.html')
'one/two/three.four.html'
>>> replace_ext('one/two/three.four.DOC', 'html')
'one/two/three.four.html'


if is_header(el, meta_data):<EOL><INDENT>return False<EOL><DEDENT>return _is_li(el)<EOL>

The only real distinction between an ``li`` tag and a ``p`` tag is that an
``li`` tag has an attribute called numPr which holds the list id and ilvl
(indentation level)


return '<STR_LIT>' != etree.tostring(p, encoding=unicode, method='<STR_LIT:text>').strip()<EOL>

It is possible for a ``p`` tag in document.xml to not have any content. If
this is the case we do not want that tag interfering with things like
lists. Detect if this tag has any content.


def is_last_li(li, meta_data, current_numId):

if not is_li(li, meta_data):<EOL><INDENT>return False<EOL><DEDENT>w_namespace = get_namespace(li, '<STR_LIT:w>')<EOL>next_el = li<EOL>while True:<EOL><INDENT>if next_el is None:<EOL><INDENT>return True<EOL><DEDENT>next_el = next_el.getnext()<EOL>if not is_li(next_el, meta_data):<EOL><INDENT>continue<EOL><DEDENT>new_numId = get_numId(next_el, w_namespace)<EOL>if current_numId != new_numId:<EOL><INDENT>return True<EOL><DEDENT>return False<EOL><DEDENT>

Determine if ``li`` is the last list item for a given list


yield li<EOL>w_namespace = get_namespace(li, '<STR_LIT:w>')<EOL>current_numId = get_numId(li, w_namespace)<EOL>starting_ilvl = get_ilvl(li, w_namespace)<EOL>el = li<EOL>while True:<EOL><INDENT>el = el.getnext()<EOL>if el is None:<EOL><INDENT>break<EOL><DEDENT>if not has_text(el):<EOL><INDENT>continue<EOL><DEDENT>if _is_top_level_upper_roman(el, meta_data):<EOL><INDENT>break<EOL><DEDENT>if (<EOL>is_li(el, meta_data) and<EOL>(starting_ilvl > get_ilvl(el, w_namespace))):<EOL><INDENT>break<EOL><DEDENT>new_numId = get_numId(el, w_namespace)<EOL>if new_numId is None or new_numId == -<NUM_LIT:1>:<EOL><INDENT>yield el<EOL>continue<EOL><DEDENT>if current_numId != new_numId:<EOL><INDENT>break<EOL><DEDENT>if is_last_li(el, meta_data, current_numId):<EOL><INDENT>yield el<EOL>break<EOL><DEDENT>yield el<EOL><DEDENT>

Find consecutive li tags that have content that have the same list id.


ilvls = li.xpath('<STR_LIT>', namespaces=li.nsmap)<EOL>if len(ilvls) == <NUM_LIT:0>:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>return int(ilvls[<NUM_LIT:0>].get('<STR_LIT>' % w_namespace))<EOL>

The ilvl on an li tag tells the li tag at what level of indentation this
tag is at. This is used to determine if the li tag needs to be nested or
not.


numIds = li.xpath('<STR_LIT>', namespaces=li.nsmap)<EOL>if len(numIds) == <NUM_LIT:0>:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>return numIds[<NUM_LIT:0>].get('<STR_LIT>' % w_namespace)<EOL>

The numId on an li tag maps to the numbering dictionary along side the ilvl
to determine what the list should look like (unordered, digits, lower
alpha, etc)


list_types = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>el = etree.Element(list_types.get(list_type, '<STR_LIT>'))<EOL>list_type_conversions = {<EOL>'<STR_LIT>': DEFAULT_LIST_NUMBERING_STYLE,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': DEFAULT_LIST_NUMBERING_STYLE,<EOL>'<STR_LIT>': DEFAULT_LIST_NUMBERING_STYLE,<EOL>'<STR_LIT>': DEFAULT_LIST_NUMBERING_STYLE,<EOL>}<EOL>if list_type != '<STR_LIT>':<EOL><INDENT>el.set(<EOL>'<STR_LIT>',<EOL>list_type_conversions.get(list_type, DEFAULT_LIST_NUMBERING_STYLE),<EOL>)<EOL><DEDENT>return el<EOL>

Based on the passed in list_type create a list objects (ol/ul). In the
future this function will also deal with what the numbering of an ordered
list should look like.


if tc is None:<EOL><INDENT>return None<EOL><DEDENT>v_merges = tc.xpath('<STR_LIT>', namespaces=tc.nsmap)<EOL>if len(v_merges) != <NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>v_merge = v_merges[<NUM_LIT:0>]<EOL>return v_merge<EOL>

vMerge is what docx uses to denote that a table cell is part of a rowspan.
The first cell to have a vMerge is the start of the rowspan, and the vMerge
will be denoted with 'restart'. If it is anything other than restart then
it is a continuation of another rowspan.


w_namespace = get_namespace(tc, '<STR_LIT:w>')<EOL>grid_spans = tc.xpath('<STR_LIT>', namespaces=tc.nsmap)<EOL>if len(grid_spans) != <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>grid_span = grid_spans[<NUM_LIT:0>]<EOL>return int(grid_span.get('<STR_LIT>' % w_namespace))<EOL>

gridSpan is what docx uses to denote that a table cell has a colspan. This
is much more simple than rowspans in that there is a one-to-one mapping
from gridSpan to colspan.


current = <NUM_LIT:0><EOL>for td in tr.xpath('<STR_LIT>', namespaces=tr.nsmap):<EOL><INDENT>if index == current:<EOL><INDENT>return td<EOL><DEDENT>current += get_grid_span(td)<EOL><DEDENT>

When calculating the rowspan for a given cell it is required to find all
table cells 'below' the initial cell with a v_merge. This function will
return the td element at the passed in index, taking into account colspans.


@ensure_tag(['<STR_LIT:b>', '<STR_LIT:i>', '<STR_LIT:u>'])<EOL>def style_is_false(style):

if style is None:<EOL><INDENT>return False<EOL><DEDENT>w_namespace = get_namespace(style, '<STR_LIT:w>')<EOL>return style.get('<STR_LIT>' % w_namespace) != '<STR_LIT:false>'<EOL>

For bold, italics and underline. Simply checking to see if the various tags
are present will not suffice. If the tag is present and set to False then
the style should not be present.


w_namespace = get_namespace(r, '<STR_LIT:w>')<EOL>rpr = r.find('<STR_LIT>' % w_namespace)<EOL>if rpr is None:<EOL><INDENT>return False<EOL><DEDENT>bold = rpr.find('<STR_LIT>' % w_namespace)<EOL>return style_is_false(bold)<EOL>

The function will return True if the r tag passed in is considered bold.


w_namespace = get_namespace(r, '<STR_LIT:w>')<EOL>rpr = r.find('<STR_LIT>' % w_namespace)<EOL>if rpr is None:<EOL><INDENT>return False<EOL><DEDENT>italics = rpr.find('<STR_LIT>' % w_namespace)<EOL>return style_is_false(italics)<EOL>

The function will return True if the r tag passed in is considered
italicized.


w_namespace = get_namespace(r, '<STR_LIT:w>')<EOL>rpr = r.find('<STR_LIT>' % w_namespace)<EOL>if rpr is None:<EOL><INDENT>return False<EOL><DEDENT>underline = rpr.find('<STR_LIT>' % w_namespace)<EOL>return style_is_false(underline)<EOL>

The function will return True if the r tag passed in is considered
underlined.


w_namespace = get_namespace(p, '<STR_LIT:w>')<EOL>styles = p.xpath('<STR_LIT>', namespaces=p.nsmap)<EOL>if len(styles) == <NUM_LIT:0>:<EOL><INDENT>return False<EOL><DEDENT>style = styles[<NUM_LIT:0>]<EOL>return style.get('<STR_LIT>' % w_namespace) == '<STR_LIT>'<EOL>

Certain p tags are denoted as ``Title`` tags. This function will return
True if the passed in p tag is considered a title.


w_namespace = get_namespace(r, '<STR_LIT:w>')<EOL>valid_elements = (<EOL>'<STR_LIT>' % w_namespace,<EOL>'<STR_LIT>' % w_namespace,<EOL>'<STR_LIT>' % w_namespace,<EOL>'<STR_LIT>' % w_namespace,<EOL>)<EOL>for el in r:<EOL><INDENT>if el.tag in valid_elements:<EOL><INDENT>yield el<EOL><DEDENT><DEDENT>

It turns out that r tags can contain both t tags and drawing tags. Since we
need both, this function will return them in the order in which they are
found.


r_tags = p.xpath('<STR_LIT>', namespaces=p.nsmap)<EOL>tags_are_bold = [<EOL>is_bold(r) or is_underlined(r) for r in r_tags<EOL>]<EOL>tags_are_italics = [<EOL>is_italics(r) for r in r_tags<EOL>]<EOL>return all(tags_are_bold), all(tags_are_italics)<EOL>

Checks to see if the whole p tag will end up being bold or italics. Returns
a tuple (boolean, boolean). The first boolean will be True if the whole
line is bold, False otherwise. The second boolean will be True if the whole
line is italics, False otherwise.


if tree is None:<EOL><INDENT>return {}<EOL><DEDENT>w_namespace = get_namespace(tree, '<STR_LIT:w>')<EOL>num_ids = {}<EOL>result = defaultdict(dict)<EOL>for list_type in tree.findall('<STR_LIT>' % w_namespace):<EOL><INDENT>list_id = list_type.get('<STR_LIT>' % w_namespace)<EOL>abstract_number = list_type.find('<STR_LIT>' % w_namespace)<EOL>num_ids[abstract_number.get('<STR_LIT>' % w_namespace)] = list_id<EOL><DEDENT>for abstract_number in tree.findall('<STR_LIT>' % w_namespace):<EOL><INDENT>abstract_num_id = abstract_number.get('<STR_LIT>' % w_namespace)<EOL>if abstract_num_id not in num_ids:<EOL><INDENT>continue<EOL><DEDENT>for lvl in abstract_number.findall('<STR_LIT>' % w_namespace):<EOL><INDENT>ilvl = int(lvl.get('<STR_LIT>' % w_namespace))<EOL>lvl_format = lvl.find('<STR_LIT>' % w_namespace)<EOL>list_style = lvl_format.get('<STR_LIT>' % w_namespace)<EOL>result[num_ids[abstract_num_id]][ilvl] = list_style<EOL><DEDENT><DEDENT>return result<EOL>

There is a separate file called numbering.xml that stores how lists should
look (unordered, digits, lower case letters, etc.). Parse that file and
return a dictionary of what each combination should be based on list Id and
level of indentation.


<EOL>headers = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>}<EOL>if tree is None:<EOL><INDENT>return {}<EOL><DEDENT>w_namespace = get_namespace(tree, '<STR_LIT:w>')<EOL>result = {}<EOL>for el in tree:<EOL><INDENT>style_id = el.get('<STR_LIT>' % w_namespace)<EOL>el_result = {<EOL>'<STR_LIT>': False,<EOL>'<STR_LIT>': None,<EOL>'<STR_LIT>': None,<EOL>}<EOL>name = el.find('<STR_LIT>' % w_namespace)<EOL>if name is None:<EOL><INDENT>continue<EOL><DEDENT>value = name.get('<STR_LIT>' % w_namespace).lower()<EOL>if value in headers:<EOL><INDENT>el_result['<STR_LIT>'] = headers[value]<EOL><DEDENT>rpr = el.find('<STR_LIT>' % w_namespace)<EOL>if rpr is None:<EOL><INDENT>continue<EOL><DEDENT>size = rpr.find('<STR_LIT>' % w_namespace)<EOL>if size is None:<EOL><INDENT>el_result['<STR_LIT>'] = None<EOL><DEDENT>else:<EOL><INDENT>el_result['<STR_LIT>'] = size.get('<STR_LIT>' % w_namespace)<EOL><DEDENT>based_on = el.find('<STR_LIT>' % w_namespace)<EOL>if based_on is None:<EOL><INDENT>el_result['<STR_LIT>'] = None<EOL><DEDENT>else:<EOL><INDENT>el_result['<STR_LIT>'] = based_on.get('<STR_LIT>' % w_namespace)<EOL><DEDENT>result[style_id] = el_result<EOL><DEDENT>return result<EOL>

Some things that are considered lists are actually supposed to be H tags
(h1, h2, etc.) These can be denoted by their styleId


def get_relationship_info(tree, media, image_sizes):

if tree is None:<EOL><INDENT>return {}<EOL><DEDENT>result = {}<EOL>for el in tree.iter():<EOL><INDENT>el_id = el.get('<STR_LIT>')<EOL>if el_id is None:<EOL><INDENT>continue<EOL><DEDENT>target = el.get('<STR_LIT>')<EOL>if any(<EOL>target.lower().endswith(ext) for<EOL>ext in IMAGE_EXTENSIONS_TO_SKIP):<EOL><INDENT>continue<EOL><DEDENT>if target in media:<EOL><INDENT>image_size = image_sizes.get(el_id)<EOL>target = convert_image(media[target], image_size)<EOL><DEDENT>result[el_id] = cgi.escape(target)<EOL><DEDENT>return result<EOL>

There is a separate file holds the targets to links as well as the targets
for images. Return a dictionary based on the relationship id and the
target.


if image_handler is None:<EOL><INDENT>def image_handler(image_id, relationship_dict):<EOL><INDENT>return relationship_dict.get(image_id)<EOL><DEDENT><DEDENT>document_xml = None<EOL>numbering_xml = None<EOL>relationship_xml = None<EOL>styles_xml = None<EOL>parser = etree.XMLParser(strip_cdata=False)<EOL>path, _ = os.path.split(f.filename)<EOL>media = {}<EOL>image_sizes = {}<EOL>for item in f.infolist():<EOL><INDENT>if item.filename == '<STR_LIT>':<EOL><INDENT>xml = f.read(item.filename)<EOL>document_xml = etree.fromstring(xml, parser)<EOL><DEDENT>elif item.filename == '<STR_LIT>':<EOL><INDENT>xml = f.read(item.filename)<EOL>numbering_xml = etree.fromstring(xml, parser)<EOL><DEDENT>elif item.filename == '<STR_LIT>':<EOL><INDENT>xml = f.read(item.filename)<EOL>styles_xml = etree.fromstring(xml, parser)<EOL><DEDENT>elif item.filename == '<STR_LIT>':<EOL><INDENT>xml = f.read(item.filename)<EOL>try:<EOL><INDENT>relationship_xml = etree.fromstring(xml, parser)<EOL><DEDENT>except XMLSyntaxError:<EOL><INDENT>relationship_xml = etree.fromstring('<STR_LIT>', parser)<EOL><DEDENT><DEDENT>if item.filename.startswith('<STR_LIT>'):<EOL><INDENT>media[item.filename[len('<STR_LIT>'):]] = f.extract(<EOL>item.filename,<EOL>path,<EOL>)<EOL><DEDENT><DEDENT>f.close()<EOL>numbering_dict = get_numbering_info(numbering_xml)<EOL>image_sizes = get_image_sizes(document_xml)<EOL>relationship_dict = get_relationship_info(<EOL>relationship_xml,<EOL>media,<EOL>image_sizes<EOL>)<EOL>styles_dict = get_style_dict(styles_xml)<EOL>font_sizes_dict = defaultdict(int)<EOL>if DETECT_FONT_SIZE:<EOL><INDENT>font_sizes_dict = get_font_sizes_dict(document_xml, styles_dict)<EOL><DEDENT>meta_data = MetaData(<EOL>numbering_dict=numbering_dict,<EOL>relationship_dict=relationship_dict,<EOL>styles_dict=styles_dict,<EOL>font_sizes_dict=font_sizes_dict,<EOL>image_handler=image_handler,<EOL>image_sizes=image_sizes,<EOL>)<EOL>return document_xml, meta_data<EOL>

``f`` is a ``ZipFile`` that is open
Extract out the document data, numbering data and the relationship data.


def get_ordered_list_type(meta_data, numId, ilvl):

<EOL>numbering_dict = meta_data.numbering_dict<EOL>if numId not in numbering_dict:<EOL><INDENT>return DEFAULT_LIST_NUMBERING_STYLE<EOL><DEDENT>if ilvl not in numbering_dict[numId]:<EOL><INDENT>return DEFAULT_LIST_NUMBERING_STYLE<EOL><DEDENT>return meta_data.numbering_dict[numId][ilvl]<EOL>

Return the list type. If numId or ilvl not in the numbering dict then
default to returning decimal.

This function only cares about ordered lists, unordered lists get dealt
with elsewhere.


<EOL>ol_dict = {}<EOL>current_ilvl = -<NUM_LIT:1><EOL>current_numId = -<NUM_LIT:1><EOL>current_ol = None<EOL>root_ol = None<EOL>visited_nodes = []<EOL>list_contents = []<EOL>def _build_li(list_contents):<EOL><INDENT>data = '<STR_LIT>'.join(t for t in list_contents if t is not None)<EOL>return etree.XML('<STR_LIT>' % data)<EOL><DEDENT>def _build_non_li_content(el, meta_data):<EOL><INDENT>w_namespace = get_namespace(el, '<STR_LIT:w>')<EOL>if el.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>new_el, visited_nodes = build_table(el, meta_data)<EOL>return etree.tostring(new_el), visited_nodes<EOL><DEDENT>elif el.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>return get_element_content(el, meta_data), [el]<EOL><DEDENT>if has_text(el):<EOL><INDENT>raise UnintendedTag('<STR_LIT>' % el.tag)<EOL><DEDENT><DEDENT>def _merge_lists(ilvl, current_ilvl, ol_dict, current_ol):<EOL><INDENT>for i in reversed(range(ilvl, current_ilvl)):<EOL><INDENT>if i not in ol_dict:<EOL><INDENT>continue<EOL><DEDENT>if ol_dict[i] is not current_ol:<EOL><INDENT>if ol_dict[i] is current_ol:<EOL><INDENT>continue<EOL><DEDENT>ol_dict[i][-<NUM_LIT:1>].append(current_ol)<EOL>current_ol = ol_dict[i]<EOL><DEDENT><DEDENT>for key in list(ol_dict):<EOL><INDENT>if key > ilvl:<EOL><INDENT>del ol_dict[key]<EOL><DEDENT><DEDENT>return current_ol<EOL><DEDENT>for li_node in li_nodes:<EOL><INDENT>w_namespace = get_namespace(li_node, '<STR_LIT:w>')<EOL>if not is_li(li_node, meta_data):<EOL><INDENT>new_el, el_visited_nodes = _build_non_li_content(<EOL>li_node,<EOL>meta_data,<EOL>)<EOL>list_contents.append(new_el)<EOL>visited_nodes.extend(el_visited_nodes)<EOL>continue<EOL><DEDENT>if list_contents:<EOL><INDENT>li_el = _build_li(list_contents)<EOL>list_contents = []<EOL>current_ol.append(li_el)<EOL><DEDENT>list_contents.append(get_element_content(<EOL>li_node,<EOL>meta_data,<EOL>))<EOL>ilvl = get_ilvl(li_node, w_namespace)<EOL>numId = get_numId(li_node, w_namespace)<EOL>list_type = get_ordered_list_type(meta_data, numId, ilvl)<EOL>if (ilvl > current_ilvl) or (numId != current_numId):<EOL><INDENT>ol_dict[ilvl] = create_list(list_type)<EOL>current_ol = ol_dict[ilvl]<EOL>current_ilvl = ilvl<EOL>current_numId = numId<EOL><DEDENT>else:<EOL><INDENT>current_ol = _merge_lists(<EOL>ilvl=ilvl,<EOL>current_ilvl=current_ilvl,<EOL>ol_dict=ol_dict,<EOL>current_ol=current_ol,<EOL>)<EOL><DEDENT>if root_ol is None:<EOL><INDENT>root_ol = current_ol<EOL><DEDENT>if ilvl in ol_dict:<EOL><INDENT>current_ol = ol_dict[ilvl]<EOL><DEDENT>else:<EOL><INDENT>if current_ol is not root_ol:<EOL><INDENT>root_ol[-<NUM_LIT:1>].append(current_ol)<EOL>current_ol = create_list(list_type)<EOL><DEDENT><DEDENT>visited_nodes.extend(list(li_node.iter()))<EOL><DEDENT>if list_contents:<EOL><INDENT>li_el = _build_li(list_contents)<EOL>list_contents = []<EOL>current_ol.append(li_el)<EOL><DEDENT>current_ol = _merge_lists(<EOL>ilvl=<NUM_LIT:0>,<EOL>current_ilvl=current_ilvl,<EOL>ol_dict=ol_dict,<EOL>current_ol=current_ol,<EOL>)<EOL>return root_ol, visited_nodes<EOL>

Build the list structure and return the root list


@ensure_tag(['<STR_LIT>'])<EOL>def build_tr(tr, meta_data, row_spans):

<EOL>tr_el = etree.Element('<STR_LIT>')<EOL>w_namespace = get_namespace(tr, '<STR_LIT:w>')<EOL>visited_nodes = []<EOL>for el in tr:<EOL><INDENT>if el in visited_nodes:<EOL><INDENT>continue<EOL><DEDENT>visited_nodes.append(el)<EOL>if el.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>v_merge = get_v_merge(el)<EOL>if (<EOL>v_merge is not None and<EOL>v_merge.get('<STR_LIT>' % w_namespace) != '<STR_LIT>'):<EOL><INDENT>continue<EOL><DEDENT>texts = []<EOL>for td_content in el:<EOL><INDENT>if td_content in visited_nodes:<EOL><INDENT>continue<EOL><DEDENT>if is_li(td_content, meta_data):<EOL><INDENT>li_nodes = get_single_list_nodes_data(<EOL>td_content,<EOL>meta_data,<EOL>)<EOL>list_el, list_visited_nodes = build_list(<EOL>li_nodes,<EOL>meta_data,<EOL>)<EOL>visited_nodes.extend(list_visited_nodes)<EOL>texts.append(etree.tostring(list_el))<EOL><DEDENT>elif td_content.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>table_el, table_visited_nodes = build_table(<EOL>td_content,<EOL>meta_data,<EOL>)<EOL>visited_nodes.extend(table_visited_nodes)<EOL>texts.append(etree.tostring(table_el))<EOL><DEDENT>elif td_content.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>visited_nodes.append(td_content)<EOL>continue<EOL><DEDENT>else:<EOL><INDENT>text = get_element_content(<EOL>td_content,<EOL>meta_data,<EOL>is_td=True,<EOL>)<EOL>texts.append(text)<EOL><DEDENT><DEDENT>data = '<STR_LIT>'.join(t for t in texts if t is not None)<EOL>td_el = etree.XML('<STR_LIT>' % data)<EOL>colspan = get_grid_span(el)<EOL>if colspan > <NUM_LIT:1>:<EOL><INDENT>td_el.set('<STR_LIT>', '<STR_LIT>' % colspan)<EOL><DEDENT>v_merge = get_v_merge(el)<EOL>if (<EOL>v_merge is not None and<EOL>v_merge.get('<STR_LIT>' % w_namespace) == '<STR_LIT>'):<EOL><INDENT>rowspan = next(row_spans)<EOL>td_el.set('<STR_LIT>', '<STR_LIT>' % rowspan)<EOL><DEDENT>tr_el.append(td_el)<EOL><DEDENT><DEDENT>return tr_el<EOL>

This will return a single tr element, with all tds already populated.


<EOL>table_el = etree.Element('<STR_LIT>')<EOL>w_namespace = get_namespace(table, '<STR_LIT:w>')<EOL>row_spans = get_rowspan_data(table)<EOL>for el in table:<EOL><INDENT>if el.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>tr_el = build_tr(<EOL>el,<EOL>meta_data,<EOL>row_spans,<EOL>)<EOL>table_el.append(tr_el)<EOL><DEDENT><DEDENT>visited_nodes = list(table.iter())<EOL>return table_el, visited_nodes<EOL>

This returns a table object with all rows and cells correctly populated.


@ensure_tag(['<STR_LIT:t>'])<EOL>def get_t_tag_content(<EOL>t, parent, remove_bold, remove_italics, meta_data):

if t is None or t.text is None:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>text = cgi.escape(t.text)<EOL>el_is_bold = not remove_bold and (<EOL>is_bold(parent) or<EOL>is_underlined(parent)<EOL>)<EOL>el_is_italics = not remove_italics and is_italics(parent)<EOL>if el_is_bold:<EOL><INDENT>text = '<STR_LIT>' % text<EOL><DEDENT>if el_is_italics:<EOL><INDENT>text = '<STR_LIT>' % text<EOL><DEDENT>return text<EOL>

Generate the string data that for this particular t tag.


<EOL>if not is_td and is_header(p, meta_data):<EOL><INDENT>remove_bold, remove_italics = whole_line_styled(p)<EOL><DEDENT>p_text = '<STR_LIT>'<EOL>w_namespace = get_namespace(p, '<STR_LIT:w>')<EOL>if len(p) == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>content_tags = (<EOL>'<STR_LIT>' % w_namespace,<EOL>'<STR_LIT>' % w_namespace,<EOL>'<STR_LIT>' % w_namespace,<EOL>'<STR_LIT>' % w_namespace,<EOL>)<EOL>elements_with_content = []<EOL>for child in p:<EOL><INDENT>if child is None:<EOL><INDENT>break<EOL><DEDENT>if child.tag in content_tags:<EOL><INDENT>elements_with_content.append(child)<EOL><DEDENT><DEDENT>for el in elements_with_content:<EOL><INDENT>if el.tag in ('<STR_LIT>' % w_namespace, '<STR_LIT>' % w_namespace):<EOL><INDENT>p_text += get_element_content(<EOL>el,<EOL>meta_data,<EOL>remove_bold=remove_bold,<EOL>remove_italics=remove_italics,<EOL>)<EOL><DEDENT>elif el.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>p_text += build_hyperlink(el, meta_data)<EOL><DEDENT>elif el.tag == '<STR_LIT>' % w_namespace:<EOL><INDENT>p_text += get_text_run_content(<EOL>el,<EOL>meta_data,<EOL>remove_bold=remove_bold,<EOL>remove_italics=remove_italics,<EOL>)<EOL><DEDENT>else:<EOL><INDENT>raise SyntaxNotSupported(<EOL>'<STR_LIT>' % el.tag<EOL>)<EOL><DEDENT><DEDENT>return p_text<EOL>

P tags are made up of several runs (r tags) of text. This function takes a
p tag and constructs the text that should be part of the p tag.

image_handler should be a callable that returns the desired ``src``
attribute for a given image.


for el in tree.iter():<EOL><INDENT>if el.tag == tag:<EOL><INDENT>el.getparent().remove(el)<EOL><DEDENT><DEDENT>

Remove all tags that have the tag name ``tag``


def convert(file_path, image_handler=None, fall_back=None, converter=None):

file_base, extension = os.path.splitext(os.path.basename(file_path))<EOL>if extension == '<STR_LIT>' or extension == '<STR_LIT>':<EOL><INDENT>return read_html_file(file_path)<EOL><DEDENT>docx_path = replace_ext(file_path, '<STR_LIT>')<EOL>if extension == '<STR_LIT>':<EOL><INDENT>docx_path = file_path<EOL><DEDENT>else:<EOL><INDENT>if converter is None:<EOL><INDENT>raise FileNotDocx('<STR_LIT>')<EOL><DEDENT>converter(docx_path, file_path)<EOL>if not os.path.isfile(docx_path):<EOL><INDENT>if fall_back is None:<EOL><INDENT>raise ConversionFailed('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>return fall_back(file_path)<EOL><DEDENT><DEDENT><DEDENT>try:<EOL><INDENT>zf = get_zip_file_handler(docx_path)<EOL><DEDENT>except BadZipfile:<EOL><INDENT>raise MalformedDocx('<STR_LIT>')<EOL><DEDENT>tree, meta_data = _get_document_data(zf, image_handler)<EOL>return create_html(tree, meta_data)<EOL>

``file_path`` is a path to the file on the file system that you want to be
    converted to html.
``image_handler`` is a function that takes an image_id and a
    relationship_dict to generate the src attribute for images. (see readme
    for more details)
``fall_back`` is a function that takes a ``file_path``. This function will
    only be called if for whatever reason the conversion fails.
``converter`` is a function to convert a document that is not docx to docx
    (examples in docx2html.converters)

Returns html extracted from ``file_path``


def check_response(service, args, status_code, expected_body):

try:<EOL><INDENT>code, body = service(args)<EOL><DEDENT>except ServiceException as error:<EOL><INDENT>code, body = error.args<EOL><DEDENT>reply = loads(body)<EOL>assert code == status_code<EOL>assert reply['<STR_LIT>'] == '<STR_LIT>'<EOL>assert '<STR_LIT:id>' in reply<EOL>assert '<STR_LIT:result>' in reply or '<STR_LIT:error>' in reply<EOL>assert '<STR_LIT:error>' not in reply if '<STR_LIT:result>' in reply else True<EOL>assert '<STR_LIT:result>' not in reply if '<STR_LIT:error>' in reply else True<EOL>assert reply == expected_body<EOL>

Verify response against given arguments.
    Check jsonrpc specification compilance.


return HTTPServiceProvider(service, '<STR_LIT:localhost>', <NUM_LIT>)<EOL>

Make default server with given server.

    This command doesn't bind and activate server socket.


connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)<EOL>connection.connect(addr)<EOL>connection.sendall('<STR_LIT:\r\n>'.join(body).encode())<EOL>return connection<EOL>


response = connection.recv(<NUM_LIT>)<EOL>connection.close()<EOL>return response.decode().split('<STR_LIT:\r\n>')<EOL>

Receive response from connection, close connection.


return one + two<EOL>


return one * two<EOL>


response = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:id>': None,<EOL>'<STR_LIT:error>': {<EOL>'<STR_LIT:code>': -<NUM_LIT>,<EOL>'<STR_LIT:message>': '<STR_LIT>',<EOL>},<EOL>}<EOL>raise ServiceException(<NUM_LIT>, dumps(response))<EOL>


response = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:id>': None,<EOL>'<STR_LIT:error>': {<EOL>'<STR_LIT:code>': -<NUM_LIT>,<EOL>'<STR_LIT:message>': '<STR_LIT>',<EOL>'<STR_LIT:data>': repr(error),<EOL>},<EOL>}<EOL>raise ServiceException(<NUM_LIT>, dumps(response))<EOL>

JSON-RPC invalid request error.

    :param error: request error
    :type error: Exception


response = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:id>': request_id,<EOL>'<STR_LIT:error>': {<EOL>'<STR_LIT:code>': -<NUM_LIT>,<EOL>'<STR_LIT:message>': '<STR_LIT>',<EOL>},<EOL>}<EOL>raise ServiceException(<NUM_LIT>, dumps(response))<EOL>

JSON-RPC method not found error.

    :param request_id: JSON-RPC request id
    :type request_id: int or str or None


response = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:id>': request_id,<EOL>'<STR_LIT:error>': {<EOL>'<STR_LIT:code>': -<NUM_LIT>,<EOL>'<STR_LIT:message>': '<STR_LIT>',<EOL>'<STR_LIT:data>': repr(error),<EOL>},<EOL>}<EOL>raise ServiceException(<NUM_LIT>, dumps(response))<EOL>

JSON-RPC server error.

    :param request_id: JSON-RPC request id
    :type request_id: int or str or None
    :param error: server error
    :type error: Exception


correct_version = request['<STR_LIT>'] == '<STR_LIT>'<EOL>error = '<STR_LIT>'<EOL>assert correct_version, error<EOL>


correct_method = isinstance(request['<STR_LIT>'], string_types)<EOL>error = '<STR_LIT>'<EOL>assert correct_method, error<EOL>


if '<STR_LIT>' in request:<EOL><INDENT>correct_params = isinstance(request['<STR_LIT>'], (list, dict))<EOL>error = '<STR_LIT>'<EOL>assert correct_params, error<EOL><DEDENT>


if '<STR_LIT:id>' in request:<EOL><INDENT>correct_id = isinstance(<EOL>request['<STR_LIT:id>'],<EOL>(string_types, int, None),<EOL>)<EOL>error = '<STR_LIT>'<EOL>assert correct_id, error<EOL><DEDENT>


pass<EOL>


HTTPServer.__init__(self, (self.host, self.port), HTTPRequestHandler)<EOL>self.port = self.server_port<EOL>


print(<EOL>self.report_message.format(<EOL>service=self.service,<EOL>host=self.host,<EOL>port=self.port,<EOL>)<EOL>)<EOL>sys.stdout.flush()<EOL>


def service_factory(app, host, port,<EOL>report_message='<STR_LIT>',<EOL>provider_cls=HTTPServiceProvider):

service = Service(app)<EOL>server = provider_cls(service, host, port, report_message)<EOL>server.serve_forever()<EOL>

Create service, start server.

    :param app: application to instantiate a service
    :param host: interface to bound provider
    :param port: port to bound provider
    :param report_message: message format to report port
    :param provider_cls: server class provide a service


if isinstance(app, list):<EOL><INDENT>self.app = dict((method.__name__, method) for method in app)<EOL><DEDENT>elif isinstance(app, dict):<EOL><INDENT>self.app = app<EOL><DEDENT>

Service constructor.

        :param app: application definition
        :type app: list of callable, dict of callable


args = self.load_args(arg)<EOL>self.validate(args)<EOL>method = self.get_method(args)<EOL>result = self.apply(method, args)<EOL>response = self.make_response(args, result)<EOL>return <NUM_LIT:200>, response<EOL>

Perform jsonrpc call.

        :param arg: JSON-RPC request body
        :type arg: str
        :raises: ServiceException


try:<EOL><INDENT>args = loads(arg)<EOL><DEDENT>except ValueError:<EOL><INDENT>parse_error()<EOL><DEDENT>else:<EOL><INDENT>return args<EOL><DEDENT>

Loads service args from string.

        :param arg: Request body
        :raises: ServiceException


try:<EOL><INDENT>validate_version(request)<EOL>validate_method(request)<EOL>validate_params(request)<EOL>validate_id(request)<EOL><DEDENT>except (AssertionError, KeyError) as error:<EOL><INDENT>invalid_request(error)<EOL><DEDENT>

Validate JSON-RPC request.

        :param request: RPC request object
        :type request: dict


try:<EOL><INDENT>method = self.app[args['<STR_LIT>']]<EOL><DEDENT>except KeyError:<EOL><INDENT>method_not_found(args['<STR_LIT:id>'])<EOL><DEDENT>else:<EOL><INDENT>return method<EOL><DEDENT>

Get request method for service application.


try:<EOL><INDENT>params = args['<STR_LIT>']<EOL>if isinstance(params, dict):<EOL><INDENT>result = method(**params)<EOL><DEDENT>else:<EOL><INDENT>result = method(*params)<EOL><DEDENT><DEDENT>except Exception as error:<EOL><INDENT>server_error(args['<STR_LIT:id>'], error)<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>


return dumps({<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT:id>': args['<STR_LIT:id>'],<EOL>'<STR_LIT:result>': result,<EOL>})<EOL>


def get_safe_contract(w3: Web3, address=None):

return w3.eth.contract(address,<EOL>abi=GNOSIS_SAFE_INTERFACE['<STR_LIT>'],<EOL>bytecode=GNOSIS_SAFE_INTERFACE['<STR_LIT>'])<EOL>

Get Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts.
:param w3: Web3 instance
:param address: address of the safe contract/proxy contract
:return: Safe Contract


def get_old_safe_contract(w3: Web3, address=None):

return w3.eth.contract(address,<EOL>abi=OLD_GNOSIS_SAFE_INTERFACE['<STR_LIT>'],<EOL>bytecode=OLD_GNOSIS_SAFE_INTERFACE['<STR_LIT>'])<EOL>

Get Old Gnosis Safe Master contract. It should be used to access Safe methods on Proxy contracts.
:param w3: Web3 instance
:param address: address of the safe contract/proxy contract
:return: Safe Contract


def get_paying_proxy_contract(w3: Web3, address=None):

return w3.eth.contract(address,<EOL>abi=PAYING_PROXY_INTERFACE['<STR_LIT>'],<EOL>bytecode=PAYING_PROXY_INTERFACE['<STR_LIT>'])<EOL>

Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy
If you want to call Safe methods you should use `get_safe_contract` with the Proxy address,
so you can access every method of the Safe
:param w3: Web3 instance
:param address: address of the proxy contract
:return: Paying Proxy Contract


def get_erc20_contract(w3: Web3, address=None):

return w3.eth.contract(address,<EOL>abi=ERC20_INTERFACE['<STR_LIT>'],<EOL>bytecode=ERC20_INTERFACE['<STR_LIT>'])<EOL>

Get ERC20 interface
:param w3: Web3 instance
:param address: address of the proxy contract
:return: ERC 20 contract


def generate_address_2(from_: Union[str, bytes], salt: Union[str, bytes], init_code: [str, bytes]) -> str:

from_ = HexBytes(from_)<EOL>salt = HexBytes(salt)<EOL>init_code = HexBytes(init_code)<EOL>assert len(from_) == <NUM_LIT:20>, "<STR_LIT>" % from_<EOL>assert len(salt) == <NUM_LIT:32>, "<STR_LIT>" % salt<EOL>assert len(init_code) > <NUM_LIT:0>, "<STR_LIT>" % init_code<EOL>init_code_hash = Web3.sha3(init_code)<EOL>contract_address = Web3.sha3(HexBytes('<STR_LIT>') + from_ + salt + init_code_hash)<EOL>return Web3.toChecksumAddress(contract_address[<NUM_LIT:12>:])<EOL>

Generates an address for a contract created using CREATE2.
:param from_: The address which is creating this new address (need to be 20 bytes)
:param salt: A salt (32 bytes)
:param init_code: A init code of the contract being created
:return: Address of the new contract


def get_balance(self, address: str, erc20_address: str) -> int:

return get_erc20_contract(self.w3, erc20_address).functions.balanceOf(address).call()<EOL>

Get balance of address for `erc20_address`
:param address: owner address
:param erc20_address: erc20 token address
:return: balance


def get_info(self, erc20_address: str) -> Erc20_Info:

<EOL>erc20 = get_example_erc20_contract(self.w3, erc20_address)<EOL>name = erc20.functions.name().call()<EOL>symbol = erc20.functions.symbol().call()<EOL>decimals = erc20.functions.decimals().call()<EOL>return Erc20_Info(name, symbol, decimals)<EOL>

Get erc20 information (`name`, `symbol` and `decimals`)
:param erc20_address:
:return: Erc20_Info


def get_transfer_history(self, from_block: int, to_block: Optional[int] = None,<EOL>from_address: Optional[str] = None, to_address: Optional[str] = None,<EOL>token_address: Optional[str] = None) -> List[Dict[str, any]]:

assert from_address or to_address or token_address, '<STR_LIT>'<EOL>erc20 = get_erc20_contract(self.w3)<EOL>argument_filters = {}<EOL>if from_address:<EOL><INDENT>argument_filters['<STR_LIT>'] = from_address<EOL><DEDENT>if to_address:<EOL><INDENT>argument_filters['<STR_LIT:to>'] = to_address<EOL><DEDENT>return erc20.events.Transfer.createFilter(fromBlock=from_block,<EOL>toBlock=to_block,<EOL>address=token_address,<EOL>argument_filters=argument_filters).get_all_entries()<EOL>

Get events for erc20 transfers. At least one of `from_address`, `to_address` or `token_address` must be
defined
An example of event:
{
    "args": {
        "from": "0x1Ce67Ea59377A163D47DFFc9BaAB99423BE6EcF1",
        "to": "0xaE9E15896fd32E59C7d89ce7a95a9352D6ebD70E",
        "value": 15000000000000000
    },
    "event": "Transfer",
    "logIndex": 42,
    "transactionIndex": 60,
    "transactionHash": "0x71d6d83fef3347bad848e83dfa0ab28296e2953de946ee152ea81c6dfb42d2b3",
    "address": "0xfecA834E7da9D437645b474450688DA9327112a5",
    "blockHash": "0x054de9a496fc7d10303068cbc7ee3e25181a3b26640497859a5e49f0342e7db2",
    "blockNumber": 7265022
}
:param from_block: Block to start querying from
:param to_block: Block to stop querying from
:param from_address: Address sending the erc20 transfer
:param to_address: Address receiving the erc20 transfer
:param token_address: Address of the token
:return: List of events
:throws: ReadTimeout


def send_tokens(self, to: str, amount: int, erc20_address: str, private_key: str) -> bytes:

erc20 = get_erc20_contract(self.w3, erc20_address)<EOL>account = Account.privateKeyToAccount(private_key)<EOL>tx = erc20.functions.transfer(to, amount).buildTransaction({'<STR_LIT>': account.address})<EOL>return self.ethereum_client.send_unsigned_transaction(tx, private_key=private_key)<EOL>

Send tokens to address
:param to:
:param amount:
:param erc20_address:
:param private_key:
:return: tx_hash


def trace_filter(self, from_block: int = <NUM_LIT:1>, to_block: Optional[int] = None,<EOL>from_address: Optional[List[str]] = None, to_address: Optional[List[str]] = None,<EOL>after: Optional[int] = None, count: Optional[int] = None) -> List[Dict[str, any]]:

assert from_address or to_address, '<STR_LIT>'<EOL>parameters = {}<EOL>if from_block:<EOL><INDENT>parameters['<STR_LIT>'] = '<STR_LIT>' % from_block<EOL><DEDENT>if to_block:<EOL><INDENT>parameters['<STR_LIT>'] = '<STR_LIT>' % to_block<EOL><DEDENT>if from_address:<EOL><INDENT>parameters['<STR_LIT>'] = from_address<EOL><DEDENT>if to_address:<EOL><INDENT>parameters['<STR_LIT>'] = to_address<EOL><DEDENT>if after:<EOL><INDENT>parameters['<STR_LIT>'] = after<EOL><DEDENT>if count:<EOL><INDENT>parameters['<STR_LIT:count>'] = count<EOL><DEDENT>try:<EOL><INDENT>return self._decode_traces(self.slow_w3.parity.traceFilter(parameters))<EOL><DEDENT>except ParityTraceDecodeException as exc:<EOL><INDENT>logger.warning('<STR_LIT>', exc)<EOL>return self._decode_traces(self.slow_w3.parity.traceFilter(parameters))<EOL><DEDENT>


def get_slow_provider(self, timeout: int):

if isinstance(self.w3_provider, AutoProvider):<EOL><INDENT>return HTTPProvider(endpoint_uri='<STR_LIT>',<EOL>request_kwargs={'<STR_LIT>': timeout})<EOL><DEDENT>elif isinstance(self.w3_provider, HTTPProvider):<EOL><INDENT>return HTTPProvider(endpoint_uri=self.w3_provider.endpoint_uri,<EOL>request_kwargs={'<STR_LIT>': timeout})<EOL><DEDENT>else:<EOL><INDENT>return self.w3_provider<EOL><DEDENT>

Get web3 provider for slow queries. Default `HTTPProvider` timeouts after 10 seconds
:param provider: Configured Web3 provider
:param timeout: Timeout to configure for internal requests (default is 10)
:return: A new web3 provider with the `slow_provider_timeout`


def send_unsigned_transaction(self, tx: Dict[str, any], private_key: Optional[str] = None,<EOL>public_key: Optional[str] = None, retry: bool = False,<EOL>block_identifier: Optional[str] = None) -> bytes:

if private_key:<EOL><INDENT>address = self.private_key_to_address(private_key)<EOL><DEDENT>elif public_key:<EOL><INDENT>address = public_key<EOL><DEDENT>else:<EOL><INDENT>logger.error('<STR_LIT>')<EOL>raise ValueError("<STR_LIT>")<EOL><DEDENT>if tx.get('<STR_LIT>') is None:<EOL><INDENT>tx['<STR_LIT>'] = self.get_nonce_for_account(address, block_identifier=block_identifier)<EOL><DEDENT>number_errors = <NUM_LIT:5><EOL>while number_errors >= <NUM_LIT:0>:<EOL><INDENT>try:<EOL><INDENT>if private_key:<EOL><INDENT>signed_tx = self.w3.eth.account.signTransaction(tx, private_key=private_key)<EOL>logger.debug('<STR_LIT>', tx['<STR_LIT:value>'], address, tx['<STR_LIT:to>'])<EOL>try:<EOL><INDENT>return self.send_raw_transaction(signed_tx.rawTransaction)<EOL><DEDENT>except TransactionAlreadyImported as e:<EOL><INDENT>tx_hash = signed_tx.hash<EOL>logger.error('<STR_LIT>' % (tx_hash.hex(), str(e)))<EOL>return tx_hash<EOL><DEDENT><DEDENT>elif public_key:<EOL><INDENT>tx['<STR_LIT>'] = address<EOL>return self.send_transaction(tx)<EOL><DEDENT><DEDENT>except ReplacementTransactionUnderpriced as e:<EOL><INDENT>if not retry or not number_errors:<EOL><INDENT>raise e<EOL><DEDENT>logger.error('<STR_LIT>',<EOL>address, tx['<STR_LIT>'])<EOL>tx['<STR_LIT>'] += <NUM_LIT:1><EOL><DEDENT>except InvalidNonce as e:<EOL><INDENT>if not retry or not number_errors:<EOL><INDENT>raise e<EOL><DEDENT>logger.error('<STR_LIT>',<EOL>address, tx['<STR_LIT>'])<EOL>tx['<STR_LIT>'] = self.get_nonce_for_account(address, block_identifier=block_identifier)<EOL>number_errors -= <NUM_LIT:1><EOL><DEDENT><DEDENT>

Send a tx using an unlocked public key in the node or a private key. Both `public_key` and
`private_key` cannot be `None`
:param tx:
:param private_key:
:param public_key:
:param retry: Retry if a problem with nonce is found
:param block_identifier:
:return: tx hash


def send_eth_to(self, private_key: str, to: str, gas_price: int, value: int, gas: int=<NUM_LIT>,<EOL>retry: bool = False, block_identifier=None, max_eth_to_send: int = <NUM_LIT:0>) -> bytes:

assert check_checksum(to)<EOL>if max_eth_to_send and value > self.w3.toWei(max_eth_to_send, '<STR_LIT>'):<EOL><INDENT>raise EtherLimitExceeded('<STR_LIT>' % (value, max_eth_to_send))<EOL><DEDENT>tx = {<EOL>'<STR_LIT:to>': to,<EOL>'<STR_LIT:value>': value,<EOL>'<STR_LIT>': gas,<EOL>'<STR_LIT>': gas_price,<EOL>}<EOL>return self.send_unsigned_transaction(tx, private_key=private_key, retry=retry,<EOL>block_identifier=block_identifier)<EOL>

Send ether using configured account
:param to: to
:param gas_price: gas_price
:param value: value(wei)
:param gas: gas, defaults to 22000
:param retry: Retry if a problem is found
:param block_identifier: None default, 'pending' not confirmed txs
:return: tx_hash


def check_tx_with_confirmations(self, tx_hash: str, confirmations: int) -> bool:

tx_receipt = self.w3.eth.getTransactionReceipt(tx_hash)<EOL>if not tx_receipt or tx_receipt['<STR_LIT>'] is None:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return (self.w3.eth.blockNumber - tx_receipt['<STR_LIT>']) >= confirmations<EOL><DEDENT>

Check tx hash and make sure it has the confirmations required
:param w3: Web3 instance
:param tx_hash: Hash of the tx
:param confirmations: Minimum number of confirmations required
:return: True if tx was mined with the number of confirmations required, False otherwise


@staticmethod<EOL><INDENT>def get_signing_address(hash: Union[bytes, str], v: int, r: int, s: int) -> str:<DEDENT>

encoded_64_address = ecrecover_to_pub(hash, v, r, s)<EOL>address_bytes = sha3(encoded_64_address)[-<NUM_LIT:20>:]<EOL>return checksum_encode(address_bytes)<EOL>

:return: checksum encoded address starting by 0x, for example `0x568c93675A8dEb121700A6FAdDdfE7DFAb66Ae4A`
:rtype: str


:return: Web3 contract tx prepared for `call`, `transact` or `buildTransaction`


def call(self, tx_sender_address: Optional[str] = None, tx_gas: Optional[int] = None,<EOL>block_identifier='<STR_LIT>') -> int:

parameters = {}<EOL>if tx_sender_address:<EOL><INDENT>parameters['<STR_LIT>'] = tx_sender_address<EOL><DEDENT>if tx_gas:<EOL><INDENT>parameters['<STR_LIT>'] = tx_gas<EOL><DEDENT>try:<EOL><INDENT>success = self.w3_tx.call(parameters, block_identifier=block_identifier)<EOL>if not success:<EOL><INDENT>raise InvalidInternalTx('<STR_LIT>' % success)<EOL><DEDENT>return success<EOL><DEDENT>except BadFunctionCallOutput as exc:  <EOL><INDENT>return self._parse_vm_exception(str(exc))<EOL><DEDENT>except ValueError as exc:  <EOL><INDENT>"""<STR_LIT>"""<EOL>error_dict = exc.args[<NUM_LIT:0>]<EOL>data = error_dict.get('<STR_LIT:data>')<EOL>if not data:<EOL><INDENT>raise exc<EOL><DEDENT>elif isinstance(data, str) and '<STR_LIT>' in data:<EOL><INDENT>result = HexBytes(data.replace('<STR_LIT>', '<STR_LIT>'))<EOL>return self._parse_vm_exception(str(result))<EOL><DEDENT><DEDENT>

:param tx_sender_address:
:param tx_gas: Force a gas limit
:param block_identifier:
:return: `1` if everything ok