<commit_before>"""
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations
from typing import Any, Callable, ClassVar, Dict, Iterator, List, Optional, Sequence, TYPE_CHECKING, Tuple
from functools import partial
from itertools import groupby

import asyncio
import sys
import time
import os
from .item import Item, ItemCallbackType
from ..enums import ComponentType
from ..components import (
    Component,
    ActionRow as ActionRowComponent,
    _component_factory,
    Button as ButtonComponent,
)

__all__ = (
    'View',
)

if TYPE_CHECKING:
    from ..interactions import Interaction
    from ..types.components import Component as ComponentPayload
    from ..state import ConnectionState

def _walk_all_components(components: List[Component]) -> Iterator[Component]:
    for item in components:
        if isinstance(item, ActionRowComponent):
            yield from item.children
        else:
            yield item

def _component_to_item(component: Component) -> Item:
    if isinstance(component, ButtonComponent):
        from .button import Button

        return Button.from_component(component)
    return Item.from_component(component)

class _ViewWeights:
    __slots__ = (
        'weights',
    )

    def __init__(self, children: List[Item]):
        self.weights: List[int] = [0, 0, 0, 0, 0]

        key = lambda i: sys.maxsize if i.row is None else i.row
        children = sorted(children, key=key)
        for row, group in groupby(children, key=key):
            for item in group:
                self.add_item(item)

    def find_open_space(self, item: Item) -> int:
        for index, weight in enumerate(self.weights):
            if weight + item.width <= 5:
                return index

        raise ValueError('could not find open space for item')

    def add_item(self, item: Item) -> None:
        if item.row is not None:
            total = self.weights[item.row] + item.width
            if total > 5:
                raise ValueError(f'item would not fit at row {item.row} ({total} > 5 width)')
            self.weights[item.row] = total
            item._rendered_row = item.row
        else:
            index = self.find_open_space(item)
            self.weights[index] += item.width
            item._rendered_row = index

    def remove_item(self, item: Item) -> None:
        if item._rendered_row is not None:
            self.weights[item._rendered_row] -= item.width
            item._rendered_row = None

    def clear(self) -> None:
        self.weights = [0, 0, 0, 0, 0]

class View:
    """Represents a UI view.

    This object must be inherited to create a UI within Discord.

    Parameters
    -----------
    timeout: Optional[:class:`float`]
        Timeout from last interaction with the UI before no longer accepting input.
        If ``None`` then there is no timeout.

    Attributes
    ------------
    timeout: Optional[:class:`float`]
        Timeout from last interaction with the UI before no longer accepting input.
        If ``None`` then there is no timeout.
    children: List[:class:`Item`]
        The list of children attached to this view.
    """

    __discord_ui_view__: ClassVar[bool] = True
    __view_children_items__: ClassVar[List[ItemCallbackType]] = []

    def __init_subclass__(cls) -> None:
        children: List[ItemCallbackType] = []
        for base in reversed(cls.__mro__):
            for member in base.__dict__.values():
                if hasattr(member, '__discord_ui_model_type__'):
                    children.append(member)

        if len(children) > 25:
            raise TypeError('View cannot have more than 25 children')

        cls.__view_children_items__ = children

    def __init__(self, timeout: Optional[float] = 180.0):
        self.timeout = timeout
        self.children: List[Item] = []
        for func in self.__view_children_items__:
            item: Item = func.__discord_ui_model_type__(**func.__discord_ui_model_kwargs__)
            item.callback = partial(func, self, item)
            item._view = self
            setattr(self, func.__name__, item)
            self.children.append(item)

        self.__weights = _ViewWeights(self.children)
        loop = asyncio.get_running_loop()
        self.id = os.urandom(16).hex()
        self._cancel_callback: Optional[Callable[[View], None]] = None
        self._timeout_handler: Optional[asyncio.TimerHandle] = None
        self._stopped = loop.create_future()

    def __repr__(self) -> str:
        return f'<{self.__class__.__name__} timeout={self.timeout} children={len(self.children)}>'

    def to_components(self) -> List[Dict[str, Any]]:
        def key(item: Item) -> int:
            return item._rendered_row or 0

        children = sorted(self.children, key=key)
        components: List[Dict[str, Any]] = []
        for _, group in groupby(children, key=key):
            children = [item.to_component_dict() for item in group]
            if not children:
                continue

            components.append(
                {
                    'type': 1,
                    'components': children,
                }
            )

        return components

    @property
    def _expires_at(self) -> Optional[float]:
        if self.timeout:
            return time.monotonic() + self.timeout
        return None

    def add_item(self, item: Item) -> None:
        """Adds an item to the view.

        Parameters
        -----------
        item: :class:`Item`
            The item to add to the view.

        Raises
        --------
        TypeError
            A :class:`Item` was not passed.
        ValueError
            Maximum number of children has been exceeded (25)
            or the row the item is trying to be added to is full.
        """

        if len(self.children) > 25:
            raise ValueError('maximum number of children exceeded')

        if not isinstance(item, Item):
            raise TypeError(f'expected Item not {item.__class__!r}')

        self.__weights.add_item(item)

        item._view = self
        self.children.append(item)

    def remove_item(self, item: Item) -> None:
        """Removes an item from the view.

        Parameters
        -----------
        item: :class:`Item`
            The item to remove from the view.
        """

        try:
            self.children.remove(item)
        except ValueError:
            pass
        else:
            self.__weights.remove_item(item)

    def clear_items(self) -> None:
        """Removes all items from the view."""
        self.children.clear()
        self.__weights.clear()

    async def interaction_check(self, interaction: Interaction) -> bool:
        """|coro|

        A callback that is called when an interaction happens within the view
        that checks whether the view should process item callbacks for the interaction.

        This is useful to override if for example you want to ensure that the
        interaction author is a given user.

        The default implementation of this returns ``True``.

        .. note::

            If an exception occurs within the body then the interaction
            check is considered failed.

        Parameters
        -----------
        interaction: :class:`~discord.Interaction`
            The interaction that occurred.

        Returns
        ---------
        :class:`bool`
            Whether the view children's callbacks should be called.
        """
        return True

    async def on_timeout(self) -> None:
        """|coro|

        A callback that is called when a view's timeout elapses without being explicitly stopped.
        """
        pass

    async def _scheduled_task(self, state: Any, item: Item, interaction: Interaction):
        try:
            allow = await self.interaction_check(interaction)
        except Exception:
            allow = False

        if not allow:
            return

        await item.callback(interaction)
        if not interaction.response._responded:
            await interaction.response.defer()

    def _start_listening(self, store: ViewStore) -> None:
        self._cancel_callback = partial(store.remove_view)
        if self.timeout:
            loop = asyncio.get_running_loop()
            self._timeout_handler = loop.call_later(self.timeout, self.dispatch_timeout)

    def dispatch_timeout(self):
        if not self._stopped.done():
            self._stopped.set_result(True)
        asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}')

    def dispatch(self, state: Any, item: Item, interaction: Interaction):
        asyncio.create_task(self._scheduled_task(state, item, interaction), name=f'discord-ui-view-dispatch-{self.id}')

    def refresh(self, components: List[Component]):
        # This is pretty hacky at the moment
        # fmt: off
        old_state: Dict[Tuple[int, str], Item] = {
            (item.type.value, item.custom_id): item  # type: ignore
            for item in self.children
            if item.is_dispatchable()
        }
        # fmt: on
        children: List[Item] = []
        for component in _walk_all_components(components):
            try:
                older = old_state[(component.type.value, component.custom_id)]  # type: ignore
            except (KeyError, AttributeError):
                children.append(_component_to_item(component))
            else:
                older.refresh_component(component)
                children.append(older)

        self.children = children

    def stop(self) -> None:
        """Stops listening to interaction events from this view.

        This operation cannot be undone.
        """
        if not self._stopped.done():
            self._stopped.set_result(False)

        if self._timeout_handler:
            self._timeout_handler.cancel()

        if self._cancel_callback:
            self._cancel_callback(self)
            self._cancel_callback = None

    def is_finished(self) -> bool:
        """:class:`bool`: Whether the view has finished interacting."""
        return self._stopped.done()

    def is_dispatching(self) -> bool:
        """:class:`bool`: Whether the view has been added for dispatching purposes."""
        return self._cancel_callback is not None

    def is_persistent(self) -> bool:
        """:class:`bool`: Whether the view is set up as persistent.

        A persistent view has all their components with a set ``custom_id`` and
        a :attr:`timeout` set to ``None``.
        """
        return self.timeout is None and all(item.is_persistent() for item in self.children)

    async def wait(self) -> bool:
        """Waits until the view has finished interacting.

        A view is considered finished when :meth:`stop` is called
        or it times out.

        Returns
        --------
        :class:`bool`
            If ``True``, then the view timed out. If ``False`` then
            the view finished normally.
        """
        return await self._stopped

class ViewStore:
    def __init__(self, state: ConnectionState):
        # (component_type, custom_id): (View, Item, Expiry)
        self._views: Dict[Tuple[int, str], Tuple[View, Item, Optional[float]]] = {}
        # message_id: View
        self._synced_message_views: Dict[int, View] = {}
        self._state: ConnectionState = state

    @property
    def persistent_views(self) -> Sequence[View]:
        views = {
            view.id: view
            for (_, (view, _, _)) in self._views.items()
            if view.is_persistent()
        }
        return list(views.values())

    def __verify_integrity(self):
        to_remove: List[Tuple[int, str]] = []
        now = time.monotonic()
        for (k, (_, _, expiry)) in self._views.items():
            if expiry is not None and now >= expiry:
                to_remove.append(k)

        for k in to_remove:
            del self._views[k]

    def add_view(self, view: View, message_id: Optional[int] = None):
        self.__verify_integrity()

        expiry = view._expires_at
        view._start_listening(self)
        for item in view.children:
            if item.is_dispatchable():
                self._views[(item.type.value, item.custom_id)] = (view, item, expiry)  # type: ignore

        if message_id is not None:
            self._synced_message_views[message_id] = view

    def remove_view(self, view: View):
        for item in view.children:
            if item.is_dispatchable():
                self._views.pop((item.type.value, item.custom_id), None)  # type: ignore

        for key, value in self._synced_message_views.items():
            if value.id == view.id:
                del self._synced_message_views[key]
                break

    def dispatch(self, component_type: int, custom_id: str, interaction: Interaction):
        self.__verify_integrity()
        key = (component_type, custom_id)
        value = self._views.get(key)
        if value is None:
            return

        view, item, _ = value
        self._views[key] = (view, item, view._expires_at)
        item.refresh_state(interaction)
        view.dispatch(self._state, item, interaction)

    def is_message_tracked(self, message_id: int):
        return message_id in self._synced_message_views

    def remove_message_tracking(self, message_id: int) -> Optional[View]:
        return self._synced_message_views.pop(message_id, None)

    def update_from_message(self, message_id: int, components: List[ComponentPayload]):
        # pre-req: is_message_tracked == true
        view = self._synced_message_views[message_id]
        view.refresh([_component_factory(d) for d in components])
<commit_msg>Add View.on_error callback for swallowed exceptions<commit_after>"""
The MIT License (MIT)

Copyright (c) 2015-present Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

from __future__ import annotations
from typing import Any, Callable, ClassVar, Dict, Iterator, List, Optional, Sequence, TYPE_CHECKING, Tuple
from functools import partial
from itertools import groupby

import traceback
import asyncio
import sys
import time
import os
from .item import Item, ItemCallbackType
from ..enums import ComponentType
from ..components import (
    Component,
    ActionRow as ActionRowComponent,
    _component_factory,
    Button as ButtonComponent,
)

__all__ = (
    'View',
)

if TYPE_CHECKING:
    from ..interactions import Interaction
    from ..types.components import Component as ComponentPayload
    from ..state import ConnectionState

def _walk_all_components(components: List[Component]) -> Iterator[Component]:
    for item in components:
        if isinstance(item, ActionRowComponent):
            yield from item.children
        else:
            yield item

def _component_to_item(component: Component) -> Item:
    if isinstance(component, ButtonComponent):
        from .button import Button

        return Button.from_component(component)
    return Item.from_component(component)

class _ViewWeights:
    __slots__ = (
        'weights',
    )

    def __init__(self, children: List[Item]):
        self.weights: List[int] = [0, 0, 0, 0, 0]

        key = lambda i: sys.maxsize if i.row is None else i.row
        children = sorted(children, key=key)
        for row, group in groupby(children, key=key):
            for item in group:
                self.add_item(item)

    def find_open_space(self, item: Item) -> int:
        for index, weight in enumerate(self.weights):
            if weight + item.width <= 5:
                return index

        raise ValueError('could not find open space for item')

    def add_item(self, item: Item) -> None:
        if item.row is not None:
            total = self.weights[item.row] + item.width
            if total > 5:
                raise ValueError(f'item would not fit at row {item.row} ({total} > 5 width)')
            self.weights[item.row] = total
            item._rendered_row = item.row
        else:
            index = self.find_open_space(item)
            self.weights[index] += item.width
            item._rendered_row = index

    def remove_item(self, item: Item) -> None:
        if item._rendered_row is not None:
            self.weights[item._rendered_row] -= item.width
            item._rendered_row = None

    def clear(self) -> None:
        self.weights = [0, 0, 0, 0, 0]

class View:
    """Represents a UI view.

    This object must be inherited to create a UI within Discord.

    Parameters
    -----------
    timeout: Optional[:class:`float`]
        Timeout from last interaction with the UI before no longer accepting input.
        If ``None`` then there is no timeout.

    Attributes
    ------------
    timeout: Optional[:class:`float`]
        Timeout from last interaction with the UI before no longer accepting input.
        If ``None`` then there is no timeout.
    children: List[:class:`Item`]
        The list of children attached to this view.
    """

    __discord_ui_view__: ClassVar[bool] = True
    __view_children_items__: ClassVar[List[ItemCallbackType]] = []

    def __init_subclass__(cls) -> None:
        children: List[ItemCallbackType] = []
        for base in reversed(cls.__mro__):
            for member in base.__dict__.values():
                if hasattr(member, '__discord_ui_model_type__'):
                    children.append(member)

        if len(children) > 25:
            raise TypeError('View cannot have more than 25 children')

        cls.__view_children_items__ = children

    def __init__(self, timeout: Optional[float] = 180.0):
        self.timeout = timeout
        self.children: List[Item] = []
        for func in self.__view_children_items__:
            item: Item = func.__discord_ui_model_type__(**func.__discord_ui_model_kwargs__)
            item.callback = partial(func, self, item)
            item._view = self
            setattr(self, func.__name__, item)
            self.children.append(item)

        self.__weights = _ViewWeights(self.children)
        loop = asyncio.get_running_loop()
        self.id = os.urandom(16).hex()
        self._cancel_callback: Optional[Callable[[View], None]] = None
        self._timeout_handler: Optional[asyncio.TimerHandle] = None
        self._stopped = loop.create_future()

    def __repr__(self) -> str:
        return f'<{self.__class__.__name__} timeout={self.timeout} children={len(self.children)}>'

    def to_components(self) -> List[Dict[str, Any]]:
        def key(item: Item) -> int:
            return item._rendered_row or 0

        children = sorted(self.children, key=key)
        components: List[Dict[str, Any]] = []
        for _, group in groupby(children, key=key):
            children = [item.to_component_dict() for item in group]
            if not children:
                continue

            components.append(
                {
                    'type': 1,
                    'components': children,
                }
            )

        return components

    @property
    def _expires_at(self) -> Optional[float]:
        if self.timeout:
            return time.monotonic() + self.timeout
        return None

    def add_item(self, item: Item) -> None:
        """Adds an item to the view.

        Parameters
        -----------
        item: :class:`Item`
            The item to add to the view.

        Raises
        --------
        TypeError
            A :class:`Item` was not passed.
        ValueError
            Maximum number of children has been exceeded (25)
            or the row the item is trying to be added to is full.
        """

        if len(self.children) > 25:
            raise ValueError('maximum number of children exceeded')

        if not isinstance(item, Item):
            raise TypeError(f'expected Item not {item.__class__!r}')

        self.__weights.add_item(item)

        item._view = self
        self.children.append(item)

    def remove_item(self, item: Item) -> None:
        """Removes an item from the view.

        Parameters
        -----------
        item: :class:`Item`
            The item to remove from the view.
        """

        try:
            self.children.remove(item)
        except ValueError:
            pass
        else:
            self.__weights.remove_item(item)

    def clear_items(self) -> None:
        """Removes all items from the view."""
        self.children.clear()
        self.__weights.clear()

    async def interaction_check(self, interaction: Interaction) -> bool:
        """|coro|

        A callback that is called when an interaction happens within the view
        that checks whether the view should process item callbacks for the interaction.

        This is useful to override if for example you want to ensure that the
        interaction author is a given user.

        The default implementation of this returns ``True``.

        .. note::

            If an exception occurs within the body then the interaction
            check then :meth:`on_error` is called and it is considered
            a failure.

        Parameters
        -----------
        interaction: :class:`~discord.Interaction`
            The interaction that occurred.

        Returns
        ---------
        :class:`bool`
            Whether the view children's callbacks should be called.
        """
        return True

    async def on_timeout(self) -> None:
        """|coro|

        A callback that is called when a view's timeout elapses without being explicitly stopped.
        """
        pass

    async def on_error(self, error: Exception, item: Item, interaction: Interaction) -> None:
        """|coro|

        A callback that is called when an item's callback or :meth:`interaction_check`
        fails with an error.

        The default implementation prints the traceback to stderr.

        Parameters
        -----------
        error: :class:`Exception`
            The exception that was raised.
        item: :class:`Item`
            The item that failed the dispatch.
        interaction: :class:`~discord.Interaction`
            The interaction that led to the failure.
        """
        print(f'Ignoring exception in view {self} for item {item}:', file=sys.stderr)
        traceback.print_exception(error.__class__, error, error.__traceback__, file=sys.stderr)

    async def _scheduled_task(self, state: Any, item: Item, interaction: Interaction):
        try:
            allow = await self.interaction_check(interaction)
            if not allow:
                return

            await item.callback(interaction)
            if not interaction.response._responded:
                await interaction.response.defer()
        except Exception as e:
            return await self.on_error(e, item, interaction)

    def _start_listening(self, store: ViewStore) -> None:
        self._cancel_callback = partial(store.remove_view)
        if self.timeout:
            loop = asyncio.get_running_loop()
            self._timeout_handler = loop.call_later(self.timeout, self.dispatch_timeout)

    def dispatch_timeout(self):
        if not self._stopped.done():
            self._stopped.set_result(True)
        asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}')

    def dispatch(self, state: Any, item: Item, interaction: Interaction):
        asyncio.create_task(self._scheduled_task(state, item, interaction), name=f'discord-ui-view-dispatch-{self.id}')

    def refresh(self, components: List[Component]):
        # This is pretty hacky at the moment
        # fmt: off
        old_state: Dict[Tuple[int, str], Item] = {
            (item.type.value, item.custom_id): item  # type: ignore
            for item in self.children
            if item.is_dispatchable()
        }
        # fmt: on
        children: List[Item] = []
        for component in _walk_all_components(components):
            try:
                older = old_state[(component.type.value, component.custom_id)]  # type: ignore
            except (KeyError, AttributeError):
                children.append(_component_to_item(component))
            else:
                older.refresh_component(component)
                children.append(older)

        self.children = children

    def stop(self) -> None:
        """Stops listening to interaction events from this view.

        This operation cannot be undone.
        """
        if not self._stopped.done():
            self._stopped.set_result(False)

        if self._timeout_handler:
            self._timeout_handler.cancel()

        if self._cancel_callback:
            self._cancel_callback(self)
            self._cancel_callback = None

    def is_finished(self) -> bool:
        """:class:`bool`: Whether the view has finished interacting."""
        return self._stopped.done()

    def is_dispatching(self) -> bool:
        """:class:`bool`: Whether the view has been added for dispatching purposes."""
        return self._cancel_callback is not None

    def is_persistent(self) -> bool:
        """:class:`bool`: Whether the view is set up as persistent.

        A persistent view has all their components with a set ``custom_id`` and
        a :attr:`timeout` set to ``None``.
        """
        return self.timeout is None and all(item.is_persistent() for item in self.children)

    async def wait(self) -> bool:
        """Waits until the view has finished interacting.

        A view is considered finished when :meth:`stop` is called
        or it times out.

        Returns
        --------
        :class:`bool`
            If ``True``, then the view timed out. If ``False`` then
            the view finished normally.
        """
        return await self._stopped

class ViewStore:
    def __init__(self, state: ConnectionState):
        # (component_type, custom_id): (View, Item, Expiry)
        self._views: Dict[Tuple[int, str], Tuple[View, Item, Optional[float]]] = {}
        # message_id: View
        self._synced_message_views: Dict[int, View] = {}
        self._state: ConnectionState = state

    @property
    def persistent_views(self) -> Sequence[View]:
        views = {
            view.id: view
            for (_, (view, _, _)) in self._views.items()
            if view.is_persistent()
        }
        return list(views.values())

    def __verify_integrity(self):
        to_remove: List[Tuple[int, str]] = []
        now = time.monotonic()
        for (k, (_, _, expiry)) in self._views.items():
            if expiry is not None and now >= expiry:
                to_remove.append(k)

        for k in to_remove:
            del self._views[k]

    def add_view(self, view: View, message_id: Optional[int] = None):
        self.__verify_integrity()

        expiry = view._expires_at
        view._start_listening(self)
        for item in view.children:
            if item.is_dispatchable():
                self._views[(item.type.value, item.custom_id)] = (view, item, expiry)  # type: ignore

        if message_id is not None:
            self._synced_message_views[message_id] = view

    def remove_view(self, view: View):
        for item in view.children:
            if item.is_dispatchable():
                self._views.pop((item.type.value, item.custom_id), None)  # type: ignore

        for key, value in self._synced_message_views.items():
            if value.id == view.id:
                del self._synced_message_views[key]
                break

    def dispatch(self, component_type: int, custom_id: str, interaction: Interaction):
        self.__verify_integrity()
        key = (component_type, custom_id)
        value = self._views.get(key)
        if value is None:
            return

        view, item, _ = value
        self._views[key] = (view, item, view._expires_at)
        item.refresh_state(interaction)
        view.dispatch(self._state, item, interaction)

    def is_message_tracked(self, message_id: int):
        return message_id in self._synced_message_views

    def remove_message_tracking(self, message_id: int) -> Optional[View]:
        return self._synced_message_views.pop(message_id, None)

    def update_from_message(self, message_id: int, components: List[ComponentPayload]):
        # pre-req: is_message_tracked == true
        view = self._synced_message_views[message_id]
        view.refresh([_component_factory(d) for d in components])
<|endoftext|>


<commit_before>import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.tayside import helpers
import ckanext.tayside.logic.action.update as update_actions

class TaysidePlugin(plugins.SingletonPlugin, toolkit.DefaultDatasetForm):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IDatasetForm, inherit=True)
    plugins.implements(plugins.ITemplateHelpers)
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IActions)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'tayside')
        toolkit.add_ckan_admin_tab(config_, 'ckanext_tayside_footer_logos',
                                   'Organization Links')

    # IRoutes

    def before_map(self, map):
        package_controller =\
            'ckanext.tayside.controllers.package:PackageController'
        admin_controller =\
            'ckanext.tayside.controllers.admin:AdminController'

        map.connect('/dataset/new', controller=package_controller,
                    action='create_metadata_package')
        map.connect('ckanext_tayside_footer_logos',
                    '/ckan-admin/manage_footer_logos',
                    controller=admin_controller, action='manage_footer_logos',
                    ckan_icon='building-o')

        return map

    # IDatasetForm

    def package_types(self):
        return ['metadata-only']

    # ITemplateHelpers

    def get_helpers(self):
        return {
            'tayside_get_groups': helpers.get_groups,
            'tayside_get_footer_logos': helpers.get_footer_logos,
        }

    # IConfigurer

    def update_config_schema(self, schema):
        ignore_missing = toolkit.get_validator('ignore_missing')
        validators = [ignore_missing, unicode]

        schema.update({
            'twitter_username': validators,
            'clear_hero_image_upload': validators,
            'hero_image_url': validators,
            'hero_image_upload': validators,
            'hero_image_license_text': validators,
            'site_symbol_url': validators,
            'site_symbol_upload': validators,
            'clear_site_symbol_upload': validators
        })

        for i in range(1, 6):
            schema.update({'footer_logo_{0}_image_url'.format(i): validators})
            schema.update({'footer_logo_{0}_link_url'.format(i): validators})
            schema.update({'footer_logo_{0}_text'.format(i): validators})
            schema.update({'footer_logo_{0}_upload'.format(i): validators})
            schema.update({
                'clear_footer_logo_{0}_upload'.format(i): validators
            })

        return schema

    # IActions

    def get_actions(self):
        return {
            'config_option_update': update_actions.config_option_update
        }
<commit_msg>Make metadata-only datasets searchable<commit_after>import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit

from ckanext.tayside import helpers
import ckanext.tayside.logic.action.update as update_actions

class TaysidePlugin(plugins.SingletonPlugin, toolkit.DefaultDatasetForm):
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IRoutes, inherit=True)
    plugins.implements(plugins.IDatasetForm, inherit=True)
    plugins.implements(plugins.ITemplateHelpers)
    plugins.implements(plugins.IConfigurer)
    plugins.implements(plugins.IActions)
    plugins.implements(plugins.IPackageController, inherit=True)

    # IConfigurer

    def update_config(self, config_):
        toolkit.add_template_directory(config_, 'templates')
        toolkit.add_public_directory(config_, 'public')
        toolkit.add_resource('fanstatic', 'tayside')
        toolkit.add_ckan_admin_tab(config_, 'ckanext_tayside_footer_logos',
                                   'Organization Links')

    # IRoutes

    def before_map(self, map):
        package_controller =\
            'ckanext.tayside.controllers.package:PackageController'
        admin_controller =\
            'ckanext.tayside.controllers.admin:AdminController'

        map.connect('/dataset/new', controller=package_controller,
                    action='create_metadata_package')
        map.connect('ckanext_tayside_footer_logos',
                    '/ckan-admin/manage_footer_logos',
                    controller=admin_controller, action='manage_footer_logos',
                    ckan_icon='building-o')

        return map

    # IDatasetForm

    def package_types(self):
        return ['metadata-only']

    # ITemplateHelpers

    def get_helpers(self):
        return {
            'tayside_get_groups': helpers.get_groups,
            'tayside_get_footer_logos': helpers.get_footer_logos,
        }

    # IConfigurer

    def update_config_schema(self, schema):
        ignore_missing = toolkit.get_validator('ignore_missing')
        validators = [ignore_missing, unicode]

        schema.update({
            'twitter_username': validators,
            'clear_hero_image_upload': validators,
            'hero_image_url': validators,
            'hero_image_upload': validators,
            'hero_image_license_text': validators,
            'site_symbol_url': validators,
            'site_symbol_upload': validators,
            'clear_site_symbol_upload': validators
        })

        for i in range(1, 6):
            schema.update({'footer_logo_{0}_image_url'.format(i): validators})
            schema.update({'footer_logo_{0}_link_url'.format(i): validators})
            schema.update({'footer_logo_{0}_text'.format(i): validators})
            schema.update({'footer_logo_{0}_upload'.format(i): validators})
            schema.update({
                'clear_footer_logo_{0}_upload'.format(i): validators
            })

        return schema

    # IActions

    def get_actions(self):
        return {
            'config_option_update': update_actions.config_option_update
        }

    # IPackageController

    def before_search(self, search_params):
        fq = search_params.get('fq', '')

        if 'dataset_type:dataset' in fq:
            fq = fq.replace('dataset_type:dataset',
                            'dataset_type: (dataset OR '
                            'metadata-only)')
            search_params.update({'fq': fq})

        return search_params
<|endoftext|>


<commit_before>from django.conf.urls import url
from .views import (
    experiment_rep_views,
    nitrogen_applied_views,
    experiment_details_views,
    experiment_duration_views,
    control_research_views,
    treatment_research_views,
)

# Experiment replication URLs
urlpatterns = [
    url(
        r'^experimentreplication/$',
        experiment_rep_views['ExperimentRepListAPIView'].as_view(),
        name='experiment_rep_list'
    ),
    url(
        r'^experimentreplication/create/$',
        experiment_rep_views['ExperimentRepCreateAPIView'].as_view(),
        name='experiment_rep_create'
    ),
    url(
        r'^experimentreplication/(?P<pk>[\w-]+)/$',
        experiment_rep_views['ExperimentRepDetailAPIView'].as_view(),
        name='experiment_rep_detail'
    ),
]

# Nitrogen Applied URLs
urlpatterns += [
    url(
        r'^nitrogenapplied/$',
        nitrogen_applied_views['NitrogenAppliedListAPIView'].as_view(),
        name='nitrogen_applied_list'
    ),
    url(
        r'^nitrogenapplied/create/$',
        nitrogen_applied_views['NitrogenAppliedCreateAPIView'].as_view(),
        name='nitrogen_applied_create'
    ),
    url(
        r'^nitrogenapplied/(?P<pk>[\w-]+)/$',
        nitrogen_applied_views['NitrogenAppliedDetailAPIView'].as_view(),
        name='nitrogen_applied_detail'
    ),
]

# Experiment details URLs
urlpatterns += [
    url(
        r'^experimentdetails/$',
        experiment_details_views['ExperimentDetailsListAPIView'].as_view(),
        name='experiment_details_list'
    ),
    url(
        r'^experimentdetails/create/$',
        experiment_details_views['ExperimentDetailsCreateAPIView'].as_view(),
        name='experiment_details_create'
    ),
    url(
        r'^experimentdetails/(?P<slug>[\w-]+)/$',
        experiment_details_views['ExperimentDetailsDetailAPIView'].as_view(),
        name='experiment_details_detail'
    ),
]

# Experiment duration URLs
urlpatterns += [
    url(
        r'^experimentduration/$',
        experiment_duration_views['ExperimentDurationListAPIView'].as_view(),
        name='experiment_duration_list'
    ),
    url(
        r'^experimentduration/create/$',
        experiment_duration_views['ExperimentDurationCreateAPIView'].as_view(),
        name='experiment_duration_create'
    ),
    url(
        r'^experimentduration/(?P<pk>[\w-]+)/$',
        experiment_duration_views['ExperimentDurationDetailAPIView'].as_view(),
        name='experiment_duration_detail'
    ),
]

# Control research URLs
urlpatterns += [
    url(
        r'^controlresearch/$',
        control_research_views['ControlResearchListAPIView'].as_view(),
        name='control_research_list'
    ),
    url(
        r'^controlresearch/create/$',
        control_research_views['ControlResearchCreateAPIView'].as_view(),
        name='control_research_create'
    ),
    url(
        r'controlresearch/(?P<pk>[\w-]+)/$',
        control_research_views['ControlResearchDetailAPIView'].as_view(),
        name='control_research_detail'
    ),
]

# Treatment research URLs
urlpatterns += [
    url(
        r'^treatmentresearch/$',
        treatment_research_views['TreatmentResearchListAPIView'].as_view(),
        name='treatment_research_list'
    ),
    url(
        r'^treatmentresearch/create/$',
        treatment_research_views['TreatmentResearchCreateAPIView'].as_view(),
        name='treatment_research_create'
    ),
    url(
        r'treatmentresearch/(?P<pk>[\w-]+)/$',
        treatment_research_views['TreatmentResearchDetailAPIView'].as_view(),
        name='treatment_research_detail'
    ),
]<commit_msg>Added "Measurement Season" urls<commit_after>from django.conf.urls import url
from .views import (
    experiment_rep_views,
    nitrogen_applied_views,
    experiment_details_views,
    experiment_duration_views,
    measurement_season_views,
    # measurement_year_views,
    control_research_views,
    treatment_research_views,
)

# Experiment replication URLs
urlpatterns = [
    url(
        r'^experimentreplication/$',
        experiment_rep_views['ExperimentRepListAPIView'].as_view(),
        name='experiment_rep_list'
    ),
    url(
        r'^experimentreplication/create/$',
        experiment_rep_views['ExperimentRepCreateAPIView'].as_view(),
        name='experiment_rep_create'
    ),
    url(
        r'^experimentreplication/(?P<pk>[\w-]+)/$',
        experiment_rep_views['ExperimentRepDetailAPIView'].as_view(),
        name='experiment_rep_detail'
    ),
]

# Nitrogen Applied URLs
urlpatterns += [
    url(
        r'^nitrogenapplied/$',
        nitrogen_applied_views['NitrogenAppliedListAPIView'].as_view(),
        name='nitrogen_applied_list'
    ),
    url(
        r'^nitrogenapplied/create/$',
        nitrogen_applied_views['NitrogenAppliedCreateAPIView'].as_view(),
        name='nitrogen_applied_create'
    ),
    url(
        r'^nitrogenapplied/(?P<pk>[\w-]+)/$',
        nitrogen_applied_views['NitrogenAppliedDetailAPIView'].as_view(),
        name='nitrogen_applied_detail'
    ),
]

# Experiment details URLs
urlpatterns += [
    url(
        r'^experimentdetails/$',
        experiment_details_views['ExperimentDetailsListAPIView'].as_view(),
        name='experiment_details_list'
    ),
    url(
        r'^experimentdetails/create/$',
        experiment_details_views['ExperimentDetailsCreateAPIView'].as_view(),
        name='experiment_details_create'
    ),
    url(
        r'^experimentdetails/(?P<slug>[\w-]+)/$',
        experiment_details_views['ExperimentDetailsDetailAPIView'].as_view(),
        name='experiment_details_detail'
    ),
]

# Experiment duration URLs
urlpatterns += [
    url(
        r'^experimentduration/$',
        experiment_duration_views['ExperimentDurationListAPIView'].as_view(),
        name='experiment_duration_list'
    ),
    url(
        r'^experimentduration/create/$',
        experiment_duration_views['ExperimentDurationCreateAPIView'].as_view(),
        name='experiment_duration_create'
    ),
    url(
        r'^experimentduration/(?P<pk>[\w-]+)/$',
        experiment_duration_views['ExperimentDurationDetailAPIView'].as_view(),
        name='experiment_duration_detail'
    ),
]

# Measurement Season URLs
urlpatterns += [
    url(
        r'^measurementseason/$',
        measurement_season_views['MeasurementSeasonListAPIView'].as_view(),
        name='measurement_season_list'
    ),
    url(
        r'^measurementseason/create/$',
        measurement_season_views['MeasurementSeasonCreateAPIView'].as_view(),
        name='measurement_season_create'
    ),
    url(
        r'^measurementseason/(?P<slug>[\w-]+)/$',
        measurement_season_views['MeasurementSeasonDetailAPIView'].as_view(),
        name='measurement_season_detail'
    ),
]

# # Measurement Year URLs
# urlpatterns += [
#     url(
#         r'^measurementyear/$',
#         measurement_year_views['MeasurementYearListAPIView'].as_view(),
#         name='measurement_year_list'
#     ),
#     url(
#         r'^measurementyear/create/$',
#         measurement_year_views['MeasurementYearCreateAPIView'].as_view(),
#         name='measurement_year_create'
#     ),
#     url(
#         r'^measurementyear/(?P<pk>[\w-]+)/$',
#         measurement_year_views['MeasurementYearDetailAPIView'].as_view(),
#         name='measurement_year_detail'
#     ),
# ]

# Control research URLs
urlpatterns += [
    url(
        r'^controlresearch/$',
        control_research_views['ControlResearchListAPIView'].as_view(),
        name='control_research_list'
    ),
    url(
        r'^controlresearch/create/$',
        control_research_views['ControlResearchCreateAPIView'].as_view(),
        name='control_research_create'
    ),
    url(
        r'controlresearch/(?P<pk>[\w-]+)/$',
        control_research_views['ControlResearchDetailAPIView'].as_view(),
        name='control_research_detail'
    ),
]

# Treatment research URLs
urlpatterns += [
    url(
        r'^treatmentresearch/$',
        treatment_research_views['TreatmentResearchListAPIView'].as_view(),
        name='treatment_research_list'
    ),
    url(
        r'^treatmentresearch/create/$',
        treatment_research_views['TreatmentResearchCreateAPIView'].as_view(),
        name='treatment_research_create'
    ),
    url(
        r'treatmentresearch/(?P<pk>[\w-]+)/$',
        treatment_research_views['TreatmentResearchDetailAPIView'].as_view(),
        name='treatment_research_detail'
    ),
]<|endoftext|>


<commit_before>"""
This module is for scriptCtx based tools
"""
import maya.cmds as cmds
import maya.mel

import mGui.runtimeCommands as rtc
from mGui.scriptJobs import SelectionChanged

from mGui.events import  Event

class ToolEvent(Event):
    REGISTRY = {}

    @classmethod
    def create(cls, name, *args, **kwargs):
        cls.REGISTRY[name] = cls(*args, **kwargs)
        return cls.REGISTRY[name]

# ----------------------------------------------
# helper classes for use in assembling contexts

class StructuredOptionProperty(object):
    """
    propety accessor
    """

    def __init__(self, key, flag, default):
        self.key = "_prop_" + key
        self.flag = flag
        self.default = default

    def __get__(self, instance, owner):
        if not hasattr(instance, self.key):
            self.__set__(instance, self.default)
        return getattr(instance, self.key)

    def __set__(self, instance, value):
        setattr(instance, self.key, value)

class StructuredOptionsMeta(type):
    """
    metaclass for cleaner creation of option flags
    """

    def __new__(cls, name, bases, kwargs):
        class_props = {'_PROPERTIES': []}

        for k, v in kwargs.items():
            if isinstance(v, tuple):
                new_prop = StructuredOptionProperty(k, v[0], v[1])
                class_props[k] = new_prop
                class_props['_PROPERTIES'].append(new_prop)
            else:
                class_props[k] = v
        return type.__new__(cls, name, bases, class_props)

class StructuredOptionSet(object):
    """
    base class for structured options
    """
    __metaclass__ = StructuredOptionsMeta

    def value(self):
        results = {}
        for v in self._PROPERTIES:
            results[v.flag] = v.__get__(self, None)
        return results

class Cursors(object):
    """
    The available cursors for scriptCtx commands
    """
    create = "create"
    dolly = "dolly"
    edit = "edit"
    pencil = "pencil"
    track = "track"
    trackHorizontal = "trackHorizontal"
    trackVertical = "trackVertical"
    transformation = "transformation"
    tumble = "tumble"
    zoom = "zoom"
    zoomIn = "zoomIn"
    zoomOut = "zoomOut"
    flyThrough = "flyThrough"
    dot = "dot"
    fleur = "fleur"
    leftArrow = "leftArrow"
    question = "question"
    doubleHorizArrow = "doubleHorizArrow"
    doubleVertArrow = "doubleVertArrow"
    sizing = "sizing"
    dollyIn = "dollyIn"
    dollyOut = "dollyOut"
    brush = "brush"
    camera = "camera"
    noAccess = "noAccess"
    input = "input"
    output = "output"
    leftCycle = "leftCycle"
    rightCycle = "rightCycle"
    rightExpand = "rightExpand"
    knife = "knife"

# ------------------------------------------------
# build contexts out of these classes.
# Note that the properties below become instance properties when an instance is created!

class PromptOptions(StructuredOptionSet):
    prompt = 'ssp', ''
    unselected = 'snp', 'select something'
    completed = 'dsp', 'selection completed'
    hud_prompt = 'ssh', ''
    hud_unselected = 'snh', 'select something'

class SelectionSetOptions(StructuredOptionSet):
    autocomplete = 'sac', False
    toggle = 'sat', False
    allow_excess = 'sae', False
    count = 'ssc', 0

    def __init__(self, prompt):
        self.prompt = prompt

    def value(self):
        result = super(SelectionSetOptions, self).value()
        result.update(self.prompt.value())
        return result

class ScriptContextFactory(StructuredOptionSet):
    cursor = 'tct', Cursors.edit
    exit_on_completion = 'euc', False
    ignore_invalid = 'iii', True
    root_select = 'ers', False
    show_manips = 'sm', False
    cumulative = 'cls', True

    def __init__(self, *selectionSets):
        self.sets = selectionSets

    def create_tool_sheet_callbacks(self, props):

        if hasattr(self, 'property_script'):
            props['bcn'] = self.__class__.__name__
            prop_info = rtc.ImportInfo(self.property_script)
            val_info = rtc.ImportInfo(self.value_script)
            prop_script = prop_info.import_statement() + ";" + prop_info.callable_name() + "()"
            val_script = val_info.import_statement() + ";" + val_info.callable_name() + "('\" + $toolName + \"')"
            # Properties generates the UI; it's a Mel call.
            # make sure to setParent to toolPropertyWindow -q -location
            maya.mel.eval("""global proc {}Properties(){}
            python("{}");
            {}
            """.format(self.__class__.__name__, "{", prop_script, "}"))
            # values sets context prop values. We can't do that
            maya.mel.eval("""global proc {}Values(string $toolName){}
            python("{}");
            {}
            """.format(self.__class__.__name__, "{", val_script, "}"))

    def value(self):

        required_class_methods = 'start', 'finish', 'exit', 'create_ctx'

        for method in required_class_methods:
            assert hasattr(self.__class__, method)

        result = super(ScriptContextFactory, self).value()
        result['tss'] = len(self.sets)
        opt_flags = ['snp', 'ssp', 'dsp', 'snh', 'ssh', 'ssc', 'sac', 'sat']
        for flag in opt_flags:
            result[flag] = []
        for each_set in self.sets:
            tmp = each_set.value()
            for opt in opt_flags:
                result[opt].append(tmp[opt])

        result['ts'] = rtc.create_runtime_command(self.__class__.__name__ + "_tool_start", self.__class__.start)
        result['tf'] = rtc.create_runtime_command(self.__class__.__name__ + "_tool_finish", self.__class__.finish)
        result['fcs'] = rtc.create_runtime_command(self.__class__.__name__ + "_tool_exit", self.__class__.exit)

        self.create_tool_sheet_callbacks(result)
        return result

    def create(self, title):
        opts = self.value()
        opts['title'] = title
        return cmds.scriptCtx(**opts)

class ComponentSelectionContextFactory(ScriptContextFactory):
    """
    A variant of ScriptContextOptions which tracks component selections in user selected order -- the stupid mel
    callback system makes this extremely awkward to do in the tool scripts themselves, so it's easier to just use this.
    """

    SELECTION_WATCHER = None
    SELECTED = []
    VISITED = set()

    @classmethod
    def start(cls):
        cls.SELECTED = []
        cls.VISITED = set()

        cls.SELECTION_WATCHER = SelectionChanged()
        cls.SELECTION_WATCHER += cls.track_selection
        cls.SELECTION_WATCHER.start()

    @classmethod
    def track_selection(cls, *ags, **kwargs):
        for comp in cmds.ls(sl=True):
            if not comp in cls.VISITED:
                cls.SELECTED.append(comp)
                cls.VISITED.add(comp)

    @classmethod
    def finish(cls):
        cls.track_selection()

    @classmethod
    def exit(cls, *args, **kwargs):
        cls.SELECTION_WATCHER.kill()
        cls.SELECTION_WATCHER = None

    @classmethod
    def component_selection(cls):
        return [i for i in cls.SELECTED]<commit_msg>converted to event model. Soooo much nicer<commit_after>"""
This module is for scriptCtx based tools
"""
import maya.cmds as cmds
import maya.mel

from mGui.scriptJobs import SelectionChanged
from mGui.events import Event

class ToolEvent(Event):
    REGISTRY = {}

    @classmethod
    def create(cls, name, *args, **kwargs):
        cls.REGISTRY[name] = cls(*args, **kwargs)
        return cls.REGISTRY[name]

    @classmethod
    def fire(cls, name):
        res = cls.REGISTRY.get(name)
        if res:
            res()
        else:
            cmds.warning("no event for %s" % name)

    @classmethod
    def delete_tool(cls, tool):
        for v in cls.REGISTRY.values():
            v -= tool.start
            v -= tool.finish
            v -= tool.exit
            if hasattr(tool, 'values'):
                v -= tool.values
            if hasattr(tool, 'properties'):
                v -= tool.properties

class ComponentSelectionTracker(object):
    """
    A variant of ScriptContextOptions which tracks component selections in user selected order -- the stupid mel
    callback system makes this extremely awkward to do in the tool scripts themselves, so it's easier to just use this.
    """

    def __init__(self):
        self.selected = []
        self.visited = set()
        self.watcher = SelectionChanged()
        self.watcher += self.track_selection

    def track_selection(self, *ags, **kwargs):
        sel = set(cmds.ls(sl=True, fl=True))
        for comp in sel:
            if not comp in self.visited:
                self.selected.append(comp)
                self.visited.add(comp)

        deletions = sel.difference(self.visited)
        for d in deletions:
            self.selected.remove(d)
            self.visited.remove(d)

    def start(self, *args, **kwargs):
        self.watcher.start()

    def finish(self):
        self.track_selection()

    def exit(self, *args, **kwargs):
        self.watcher.kill()
        self.selected = []
        self.visited = set()

    def component_selection(self):
        return [i for i in self.selected]

class Tool(object):
    """
    Represents a scriptContext tool
    """
    REGISTRY = {}  # don't override this in derived -- always use the Tool version
    START = 'start'
    FINISH = 'finish'
    EXIT = 'exit'
    PROPERTIES = 'properties'
    VALUES = 'values'

    EVENT_PREFIX = 'tool'  # give each derived tool a unique name

    def __init__(self, name):
        self.name = name

        def hook_event(name, function):
            event_name = lambda name: self.EVENT_PREFIX + "_" + name
            ev = ToolEvent.create(event_name(name))
            ev += function

        hook_event(self.START, self.start)
        hook_event(self.FINISH, self.finish)
        hook_event(self.EXIT, self.exit)

        # if the derived class implements 'properties' and 'values' methods
        if hasattr(self, 'properties'):
            hook_event(self.PROPERTIES, self.properties)
            hook_event(self.VALUES, self.values)

        Tool.REGISTRY[self.name] = self

    def create_context(self, contextOptions):
        """
        Create a context hooked to the events for this instance
        """
        props = hasattr(self, 'properties') or None
        vals = hasattr(self, 'values') or None
        if not props == vals:
            raise RuntimeError('Tool classes with custom properties must implement both properties() and values()')

        if props and vals:
            props = self.PROPERTIES
            vals = self.VALUES

        opts = contextOptions.value(self.EVENT_PREFIX, self.START, self.FINISH, self.EXIT, props, vals)
        opts['title'] = self.name
        context_name = cmds.scriptCtx(**opts)
        Tool.REGISTRY[context_name] = self
        return context_name

    def start(self, *args, **kwargs):
        pass

    def finish(self, *args, **kwargs):
        pass

    def exit(self, *args, **kwargs):
        pass

    @classmethod
    def retrieve(cls, name_or_context):
        return Tool.REGISTRY.get(name_or_context, None)

    @classmethod
    def delete(cls, name_or_context):
        target = cls.retrieve(name_or_context)
        if target is not None:
            ToolEvent.delete_tool(target)
            for k, v in Tool.REGISTRY.items():
                if v == target:
                    del (Tool.REGISTRY[k])

class SelectionTrackingTool(Tool):
    """
    This is a variant of the base tool which includes a ComponentSelectionTracker so that
     it can track serial selections. It preserves selection order to support component selection tools
     (it's hard to do this in Python otherwise)
    """

    def __init__(self, name):
        super(SelectionTrackingTool, self).__init__(name)
        self.tracker = ComponentSelectionTracker()

    def start(self, *args, **kwargs):
        self.tracker.start()

    def finish(self, *args, **kwargs):
        self.tracker.finish()

    def exit(self, *args, **kwargs):
        self.tracker.exit()

    def component_selection(self):
        return self.tracker.component_selection()

# ---------------------------------------------
# convenience constants

class Cursors(object):
    """
    The available cursors for scriptCtx commands
    """
    create = "create"
    dolly = "dolly"
    edit = "edit"
    pencil = "pencil"
    track = "track"
    trackHorizontal = "trackHorizontal"
    trackVertical = "trackVertical"
    transformation = "transformation"
    tumble = "tumble"
    zoom = "zoom"
    zoomIn = "zoomIn"
    zoomOut = "zoomOut"
    flyThrough = "flyThrough"
    dot = "dot"
    fleur = "fleur"
    leftArrow = "leftArrow"
    question = "question"
    doubleHorizArrow = "doubleHorizArrow"
    doubleVertArrow = "doubleVertArrow"
    sizing = "sizing"
    dollyIn = "dollyIn"
    dollyOut = "dollyOut"
    brush = "brush"
    camera = "camera"
    noAccess = "noAccess"
    input = "input"
    output = "output"
    leftCycle = "leftCycle"
    rightCycle = "rightCycle"
    rightExpand = "rightExpand"
    knife = "knife"

# ----------------------------------------------
# helper classes for use in assembling contexts

class StructuredOptionProperty(object):
    """
    propety accessor for StructuredOptions.  This is used
    to keep all the boilerplated for defaults, etc in one place
    """

    def __init__(self, key, flag, default):
        self.key = "_prop_" + key
        self.flag = flag
        self.default = default

    def __get__(self, instance, owner):
        if not hasattr(instance, self.key):
            self.__set__(instance, self.default)
        return getattr(instance, self.key)

    def __set__(self, instance, value):
        setattr(instance, self.key, value)

class StructuredOptionsMeta(type):
    """
    Make all StructuredOptions use StructuredOptionsProperties
    """

    def __new__(cls, name, bases, kwargs):
        class_props = {'_PROPERTIES': []}
        for k, v in kwargs.items():
            if isinstance(v, tuple):
                new_prop = StructuredOptionProperty(k, v[0], v[1])
                class_props[k] = new_prop
                class_props['_PROPERTIES'].append(new_prop)
            else:
                class_props[k] = v
        return type.__new__(cls, name, bases, class_props)

class StructuredOptionSet(object):
    """
    Base class for structured options. They are just a clean way
    to assemble the dictionary of options needed by the scriptCtx
    command
    """
    __metaclass__ = StructuredOptionsMeta

    def value(self):
        results = {}
        for v in self._PROPERTIES:
            results[v.flag] = v.__get__(self, None)
        return results

class PromptOptions(StructuredOptionSet):
    """
    The prompts for a selection set
    """
    prompt = 'ssp', ''
    unselected = 'snp', 'select something'
    completed = 'dsp', 'selection completed'
    hud_prompt = 'ssh', ''
    hud_unselected = 'snh', 'select something'

class SelectionSetOptions(StructuredOptionSet):
    """
    A selection set. A finished context includes at least one
    and possibly more of these
    """
    autocomplete = 'sac', False
    toggle = 'sat', False
    allow_excess = 'sae', False
    count = 'ssc', 0

    def __init__(self, prompt):
        self.prompt = prompt

    def value(self):
        result = super(SelectionSetOptions, self).value()
        result.update(self.prompt.value())
        return result

class ScriptContextFactory(StructuredOptionSet):
    """
    Collect selection sets into a single dictionary to be fed to the ScriptCtx command.
    """
    cursor = 'tct', Cursors.edit
    exit_on_completion = 'euc', False
    ignore_invalid = 'iii', True
    root_select = 'ers', False
    show_manips = 'sm', False
    cumulative = 'cls', True

    def __init__(self, *selectionSets):
        self.sets = selectionSets

    def value(self, tool_class, start_name, finish_name, exit_name, props_name, vals_name):
        result = super(ScriptContextFactory, self).value()
        result['tss'] = len(self.sets)
        opt_flags = ['snp', 'ssp', 'dsp', 'snh', 'ssh', 'ssc', 'sac', 'sat']
        for flag in opt_flags:
            result[flag] = []
        for each_set in self.sets:
            tmp = each_set.value()
            for opt in opt_flags:
                result[opt].append(tmp[opt])

        def generate_event_callback(classname, tool_name):
            long_name = classname + "_" + tool_name
            return '''python("from mGui.ctx import ToolEvent; ToolEvent.fire('%s')")''' % long_name

        result['ts'] = generate_event_callback(tool_class, start_name)
        result['tf'] = generate_event_callback(tool_class, finish_name)
        result['fcs'] = generate_event_callback(tool_class, exit_name)

        if props_name:
            # if custom properties are provided, define mel proxies
            result['bcn'] = tool_class
            prop_event = generate_event_callback(tool_class, props_name)
            maya.mel.eval("""global proc %sProperties(){%s}""" % (tool_class, prop_event))
            maya.mel.eval("""global proc %sValues(string $toolName){%s}""" % (tool_class, vals_name))

        return result

    def create(self, title):
        opts = self.value()
        opts['title'] = title
        return cmds.scriptCtx(**opts)

<|endoftext|>


<commit_before>from __future__ import print_function
import asyncore, collections, json, smtpd, sys, threading, time
from wsgiref.simple_server import make_server, WSGIRequestHandler, WSGIServer
import bottle

__version__ = '1.1.0'

try:
  import sendgrid
except ImportError:
  sendgrid = None

class _SMTPServer(smtpd.SMTPServer):

  def process_message(self, peer, mailfrom, rcpttos, data):
    email = Email(frm=mailfrom, to=rcpttos, msg=data)
    for callback in self.callbacks.values():
      callback(email)

_smtp_servers = {}

class Server(object):

  def __init__(self, smtp_port=1025, sendgrid_port=None):
    self._smtp_port = smtp_port
    self._sendgrid_port = sendgrid_port
    self._sendgrid_server = None
    self.emails = []
    if sendgrid_port:
      self._sendgrid_app = app = bottle.Bottle()

      @app.get('/v3/templates')
      def templates():
        return {'templates': []}

      @app.post('/v3/mail/send')
      def send():
        d = bottle.request.json
        for p in d['personalizations']:
          email = Email(frm=d['from']['email'], to=[addr['email'] for addr in p['to']], msg=json.dumps(p, indent=2))
          self.emails.append(email)
        return {}

  def _callback(self, email):
    self.emails.append(email)

  def _start_smtp_server(self):
    _smtp_server = _smtp_servers.get(self._smtp_port)
    if not _smtp_server:
      if sys.version_info[0] < 3:
        _smtp_server = _SMTPServer(('localhost', self._smtp_port), None)
      else:
        _smtp_server = _SMTPServer(('localhost', self._smtp_port), None, decode_data=True)
      _smtp_servers[self._smtp_port] = _smtp_server
      _smtp_server.callbacks = {}
      t = threading.Thread(target=asyncore.loop)
      t.daemon = True
      t.start()
    _smtp_server.callbacks[id(self)] = self._callback

  def _start_sendgrid_server(self):
    def f():
      self._sendgrid_server = make_server('localhost', self._sendgrid_port, self._sendgrid_app, WSGIServer, WSGIRequestHandler)
      self._sendgrid_server.serve_forever(poll_interval=.1)
    t = threading.Thread(target=f)
    t.start()
    time.sleep(.1)

  def __enter__(self):
    if self._smtp_port: self._start_smtp_server()
    if self._sendgrid_port: self._start_sendgrid_server()
    return self

  def __exit__(self, type, value, tb):
    if self._smtp_port:
      del _smtp_servers[self._smtp_port].callbacks[id(self)]
    if self._sendgrid_server:
      #print('closing', self._sendgrid_server)
      self._sendgrid_server.shutdown()
      self._sendgrid_server.server_close()

Email = collections.namedtuple('Email', ['frm','to','msg'])

<commit_msg>move sendgrid to a reused server like smtp<commit_after>from __future__ import print_function
import asyncore, collections, json, smtpd, sys, threading, time
from wsgiref.simple_server import make_server, WSGIRequestHandler, WSGIServer
import bottle

__version__ = '1.1.1'

try:
  import sendgrid
except ImportError:
  sendgrid = None

class _SMTPServer(smtpd.SMTPServer):

  def process_message(self, peer, mailfrom, rcpttos, data):
    email = Email(frm=mailfrom, to=rcpttos, msg=data)
    for callback in self.callbacks.values():
      callback(email)

_smtp_servers = {}

class _SendgridServer(object):
  def __init__(self, port):
    self.port = port
    self.app = app = bottle.Bottle()

    @app.get('/v3/templates')
    def templates():
      return {'templates': []}

    @app.post('/v3/mail/send')
    def send():
      d = bottle.request.json
      for p in d['personalizations']:
        email = Email(frm=d['from']['email'], to=[addr['email'] for addr in p['to']], msg=json.dumps(p, indent=2))
        for callback in self.callbacks.values():
          callback(email)
      return {}

  def start(self):
    def f():
      self._sendgrid_server = make_server('localhost', self.port, self.app, WSGIServer, WSGIRequestHandler)
      self._sendgrid_server.serve_forever()
    t = threading.Thread(target=f)
    t.daemon = True
    t.start()
    time.sleep(.1)

_sendgrid_servers = {}

class Server(object):

  def __init__(self, smtp_port=1025, sendgrid_port=None):
    self._smtp_port = smtp_port
    self._sendgrid_port = sendgrid_port
    self._sendgrid_server = None
    self.emails = []

  def _callback(self, email):
    self.emails.append(email)

  def _start_smtp_server(self):
    _smtp_server = _smtp_servers.get(self._smtp_port)
    if not _smtp_server:
      if sys.version_info[0] < 3:
        _smtp_server = _SMTPServer(('localhost', self._smtp_port), None)
      else:
        _smtp_server = _SMTPServer(('localhost', self._smtp_port), None, decode_data=True)
      _smtp_servers[self._smtp_port] = _smtp_server
      _smtp_server.callbacks = {}
      t = threading.Thread(target=asyncore.loop)
      t.daemon = True
      t.start()
    _smtp_server.callbacks[id(self)] = self._callback

  def _start_sendgrid_server(self):
    server = _sendgrid_servers.get(self._sendgrid_port)
    if not server:
      _sendgrid_servers[self._sendgrid_port] = server = _SendgridServer(self._sendgrid_port)
      server.callbacks = {}
      server.start()
    server.callbacks[id(self)] = self._callback

  def __enter__(self):
    if self._smtp_port: self._start_smtp_server()
    if self._sendgrid_port: self._start_sendgrid_server()
    return self

  def __exit__(self, type, value, tb):
    if self._smtp_port:
      del _smtp_servers[self._smtp_port].callbacks[id(self)]
    if self._sendgrid_port:
      del _sendgrid_servers[self._sendgrid_port].callbacks[id(self)]

Email = collections.namedtuple('Email', ['frm','to','msg'])

<|endoftext|>


<commit_before>def load_file(net, filename):
  import StringIO
  f = open(filename, 'r')
  buff = StringIO.StringIO(f.read())
  f.close()
  net.load_tsv_to_net(buff)

def load_tsv_to_net(net, file_buffer):
  import pandas as pd
  import categories
  from ast import literal_eval as make_tuple

  lines = file_buffer.getvalue().split('\n')
  num_labels = categories.check_categories(lines)

  row_arr = range(num_labels['row'])
  col_arr = range(num_labels['col'])
  tmp_df = {}

  # use header if there are col categories
  if len(col_arr) > 1:
    tmp_df['mat'] = pd.read_table(file_buffer, index_col=row_arr,
                                  header=col_arr)
  else:
    tmp_df['mat'] = pd.read_table(file_buffer, index_col=row_arr)

  # 1) check that rows are strings (in case of numerical names)
  # 2) check for tuples, and in that case load tuples to categories
  test = {}
  test['row'] = tmp_df['mat'].index.tolist()
  test['col'] = tmp_df['mat'].columns.tolist()

  # if type( test_row ) is not str and type( test_row ) is not tuple:

  found_tuple = {}
  found_number = {}
  for inst_rc in ['row','col']:

    inst_name = test[inst_rc][0]

    found_tuple[inst_rc] = False
    found_number[inst_rc] = False

    if type(inst_name) != tuple:

      if type(inst_name) is int or type(inst_name) is float:
        found_number[inst_rc] = True

      check_open = inst_name[0]
      check_comma = inst_name.find(',')
      check_close = inst_name[-1]

      if check_open == '(' and check_close == ')' and check_comma > 0 \
        and check_comma < len(inst_name):
        found_tuple[inst_rc] = True

  # convert to tuple if necessary
  #################################################
  if found_tuple['row']:
    row_names = tmp_df['mat'].index.tolist()
    row_names = [make_tuple(x) for x in row_names]
    tmp_df['mat'].index = row_names

  if found_tuple['col']:
    col_names = tmp_df['mat'].columns.tolist()
    col_names = [make_tuple(x) for x in col_names]
    tmp_df['mat'].columns = col_names

  # convert numbers to string if necessary
  #################################################
  if found_number['row']:
    row_names = tmp_df['mat'].index.tolist()
    row_names = [str(x) for x in row_names]
    tmp_df['mat'].index = row_names

  if found_number['col']:
    col_names = tmp_df['mat'].columns.tolist()
    col_names = [str(x) for x in col_names]
    tmp_df['mat'].columns = col_names

  # # remove columns with all nans, occurs when there are trailing
  # # tabs on rows
  # tmp_df['mat'] = tmp_df['mat'].dropna(axis=1, how='all')

  net.df_to_dat(tmp_df)

def load_json_to_dict(filename):
  import json
  f = open(filename, 'r')
  inst_dict = json.load(f)
  f.close()
  return inst_dict

def load_gmt(filename):
  f = open(filename, 'r')
  lines = f.readlines()
  f.close()
  gmt = {}
  for i in range(len(lines)):
    inst_line = lines[i].rstrip()
    inst_term = inst_line.split('\t')[0]
    inst_elems = inst_line.split('\t')[2:]
    gmt[inst_term] = inst_elems

  return gmt

def load_data_to_net(net, inst_net):
  ''' load data into nodes and mat, also convert mat to numpy array'''
  import data_formats
  net.dat['nodes'] = inst_net['nodes']
  net.dat['mat'] = inst_net['mat']
  data_formats.mat_to_numpy_arr(net)<commit_msg>bug fix in load_tsv, number col/row names can now be loaded<commit_after>def load_file(net, filename):
  import StringIO
  f = open(filename, 'r')
  buff = StringIO.StringIO(f.read())
  f.close()
  net.load_tsv_to_net(buff)

def load_tsv_to_net(net, file_buffer):
  import numpy as np
  import pandas as pd
  import categories
  from ast import literal_eval as make_tuple

  lines = file_buffer.getvalue().split('\n')
  num_labels = categories.check_categories(lines)

  row_arr = range(num_labels['row'])
  col_arr = range(num_labels['col'])
  tmp_df = {}

  # use header if there are col categories
  if len(col_arr) > 1:
    tmp_df['mat'] = pd.read_table(file_buffer, index_col=row_arr,
                                  header=col_arr)
  else:
    tmp_df['mat'] = pd.read_table(file_buffer, index_col=row_arr)

  # 1) check that rows are strings (in case of numerical names)
  # 2) check for tuples, and in that case load tuples to categories
  test = {}
  test['row'] = tmp_df['mat'].index.tolist()
  test['col'] = tmp_df['mat'].columns.tolist()

  # if type( test_row ) is not str and type( test_row ) is not tuple:

  found_tuple = {}
  found_number = {}
  for inst_rc in ['row','col']:

    inst_name = test[inst_rc][0]

    found_tuple[inst_rc] = False
    found_number[inst_rc] = False

    if type(inst_name) != tuple:

      if type(inst_name) is int or type(inst_name) is float or type(inst_name) is np.int64:
        found_number[inst_rc] = True

      else:
        check_open = inst_name[0]
        check_comma = inst_name.find(',')
        check_close = inst_name[-1]

        if check_open == '(' and check_close == ')' and check_comma > 0 \
          and check_comma < len(inst_name):
          found_tuple[inst_rc] = True

  # convert to tuple if necessary
  #################################################
  if found_tuple['row']:
    row_names = tmp_df['mat'].index.tolist()
    row_names = [make_tuple(x) for x in row_names]
    tmp_df['mat'].index = row_names

  if found_tuple['col']:
    col_names = tmp_df['mat'].columns.tolist()
    col_names = [make_tuple(x) for x in col_names]
    tmp_df['mat'].columns = col_names

  # convert numbers to string if necessary
  #################################################
  if found_number['row']:
    row_names = tmp_df['mat'].index.tolist()
    row_names = [str(x) for x in row_names]
    tmp_df['mat'].index = row_names

  if found_number['col']:
    col_names = tmp_df['mat'].columns.tolist()
    col_names = [str(x) for x in col_names]
    tmp_df['mat'].columns = col_names

  # # remove columns with all nans, occurs when there are trailing
  # # tabs on rows
  # tmp_df['mat'] = tmp_df['mat'].dropna(axis=1, how='all')

  net.df_to_dat(tmp_df)

def load_json_to_dict(filename):
  import json
  f = open(filename, 'r')
  inst_dict = json.load(f)
  f.close()
  return inst_dict

def load_gmt(filename):
  f = open(filename, 'r')
  lines = f.readlines()
  f.close()
  gmt = {}
  for i in range(len(lines)):
    inst_line = lines[i].rstrip()
    inst_term = inst_line.split('\t')[0]
    inst_elems = inst_line.split('\t')[2:]
    gmt[inst_term] = inst_elems

  return gmt

def load_data_to_net(net, inst_net):
  ''' load data into nodes and mat, also convert mat to numpy array'''
  import data_formats
  net.dat['nodes'] = inst_net['nodes']
  net.dat['mat'] = inst_net['mat']
  data_formats.mat_to_numpy_arr(net)<|endoftext|>


<commit_before>""" a task for waiting on a specific custom settings value """

from cumulusci.tasks.salesforce import BaseSalesforceApiTask
from cumulusci.core.utils import process_bool_arg

class CustomSettingValueWait(BaseSalesforceApiTask):
    """ CustomSettingValueWait polls an org until the specific value exists in a custom settings field """

    name = "CustomSettingValueWait"

    task_options = {
        "object": {
            "description": "Name of the SObject to query. Can include the %%%NAMESPACE%%% token. ",
            "required": True,
        },
        "field": {
            "description": "Name of the field on the Sobject to query. Can include the %%%NAMESPACE%%% token. ",
            "required": True,
        },
        "value": {
            "description": "Value of the field to wait for (String or Boolean). ",
            "required": True,
        },
        "managed": {
            "description": (
                "If True, will inject the project's namespace prefix to replace %%%NAMESPACE%%% tokens in the object or field "
                "Defaults to False or no namespace."
            ),
            "required": False,
        },
        "poll_interval": {
            "description": (
                "Seconds to wait before polling for batch job completion. "
                "Defaults to 10 seconds."
            ),
        },
    }

    def _run_task(self):
        self.poll_interval_s = int(self.options.get("poll_interval", 10))

        self.object_name = self.options["object"]
        self.field_name = self.options["field"]
        self.check_value = self.options["value"]

        # Process namespace tokens
        managed = self.options.get("managed") or False
        namespace = self.project_config.project__package__namespace
        namespace_prefix = ""
        if managed:
            namespace_prefix = namespace + "__"

        self.object_name = self.object_name.replace("%%%NAMESPACE%%%", namespace_prefix)
        self.field_name = self.field_name.replace("%%%NAMESPACE%%%", namespace_prefix)

        self._poll()  # will block until poll_complete

        self.logger.info("Value Matched.")

        return True

    def _poll_action(self):
        query_results = self.sf.query(self._object_query)

        self.record = query_results["records"][0]

        self.poll_complete = not self._poll_again()

    def _poll_again(self):
        return not self.success

    @property
    def success(self):
        self.field_value = self.record[self.field_name]

        if isinstance(self.field_value, (bool)):
            self.check_value = process_bool_arg(self.check_value)
            self.field_value = process_bool_arg(self.field_value)
        elif isinstance(self.field_value, (int, float)):
            self.check_value = float(self.check_value)
            self.field_value = float(self.field_value)
        elif isinstance(field_value, (str)):
            self.check_value = str(self.check_value).lower()
            self.field_value = str(self.field_value).lower()

        self.logger.info(
            "{0}: Looking for {1} and found {2}".format(
                self.field_name, self.check_value, self.field_value
            )
        )
        return self.field_value == self.check_value

    @property
    def _object_query(self):
        return "SELECT {0} FROM {1} LIMIT 1".format(self.field_name, self.object_name)
<commit_msg>Update cumulusci/tasks/apex/custom_settings.py<commit_after>""" a task for waiting on a specific custom settings value """

from cumulusci.tasks.salesforce import BaseSalesforceApiTask
from cumulusci.core.utils import process_bool_arg

class CustomSettingValueWait(BaseSalesforceApiTask):
    """ CustomSettingValueWait polls an org until the specific value exists in a custom settings field """

    name = "CustomSettingValueWait"

    task_options = {
        "object": {
            "description": "Name of the SObject to query. Can include the %%%NAMESPACE%%% token. ",
            "required": True,
        },
        "field": {
            "description": "Name of the field on the Sobject to query. Can include the %%%NAMESPACE%%% token. ",
            "required": True,
        },
        "value": {
            "description": "Value of the field to wait for (String or Boolean). ",
            "required": True,
        },
        "managed": {
            "description": (
                "If True, will inject the project's namespace prefix to replace %%%NAMESPACE%%% tokens in the object or field "
                "Defaults to False or no namespace."
            ),
            "required": False,
        },
        "poll_interval": {
            "description": (
                "Seconds to wait before polling for batch job completion. "
                "Defaults to 10 seconds."
            ),
        },
    }

    def _run_task(self):
        self.poll_interval_s = int(self.options.get("poll_interval", 10))

        self.object_name = self.options["object"]
        self.field_name = self.options["field"]
        self.check_value = self.options["value"]

        # Process namespace tokens
        managed = self.options.get("managed") or False
        namespace = self.project_config.project__package__namespace
        namespace_prefix = ""
        if managed:
            namespace_prefix = namespace + "__"

        self.object_name = self.object_name.replace("%%%NAMESPACE%%%", namespace_prefix)
        self.field_name = self.field_name.replace("%%%NAMESPACE%%%", namespace_prefix)

        self._poll()  # will block until poll_complete

        self.logger.info("Value Matched.")

        return True

    def _poll_action(self):
        query_results = self.sf.query(self._object_query)

        self.record = query_results["records"][0]

        self.poll_complete = not self._poll_again()

    def _poll_again(self):
        return not self.success

    @property
    def success(self):
        self.field_value = self.record[self.field_name]

        if isinstance(self.field_value, (bool)):
            self.check_value = process_bool_arg(self.check_value)
            self.field_value = process_bool_arg(self.field_value)
        elif isinstance(self.field_value, (int, float)):
            self.check_value = float(self.check_value)
            self.field_value = float(self.field_value)
        elif isinstance(field_value, (str)):
            self.check_value = str(self.check_value).lower()
            self.field_value = str(self.field_value).lower()

        self.logger.info(
            "{0}: Looking for {1} and found {2}".format(
                self.field_name, self.check_value, self.field_value
            )
        )
        return self.field_value == self.check_value

    @property
    def _object_query(self):
        return f"SELECT {self.field_name} FROM {self.object_name} LIMIT 1"
<|endoftext|>