http://trac.edgewall.org/wiki/TracDev/PluginDevelopment



trac.env.IEnvironmentSetupParticipant
    Allows plugins to participate in the creation and upgrade of the environment. Can be used to setup additional database tables or directories needed for the plugin to operate 

trac.web.api.IRequestHandler
    Allows plugins to add handlers for HTTP requests. 

trac.web.api.IRequestFilter
    Allows plugins to add filters to the HTTP requests. 

trac.web.chrome.INavigationContributor
    Allows plugins to extend the navigation menus of the web interface. 

trac.web.chrome.ITemplateProvider
    Extension point interface for components that provide their own ClearSilver templates and accompanying static resources. 

trac.perm.IPermissionRequestor
    Plugins can use this extension point to define additional "actions" for the permission system. 

trac.timeline.ITimelineEventProvider
    Allows plugins to contribute events to the timeline. 

trac.mimeview.api.IHTMLPreviewRenderer
    Allows plugins to provide support for rendering specific content of a specific type as HTML (used for TracSyntaxColoring and image preview) 

trac.wiki.api.IWikiChangeListener
    Allows plugins to observe creation, modification and deletion of wiki pages. 

trac.wiki.api.IWikiMacroProvider
    Allows plugins to contribute WikiMacros to Trac. 

trac.wiki.api.IWikiSyntaxProvider
    Plugins can extend this extension point to add custom syntax rules to the wiki formatting system. In particular, this allows registration of additional TracLinks types. 

trac.ticket.api.ITicketChangeListener
    Extension point interface for components that require notification when tickets are created, modified, or deleted. 


# 環境（プロジェクトの作成、更新の可否、更新）を拡張する
# trac.env.IEnvironmentSetupParticipant
# ○：入れた
class IEnvironmentSetupParticipant(Interface):
    """Extension point interface for components that need to participate in the
    creation and upgrading of Trac environments, for example to create
    additional database tables."""

    def environment_created():
        """Called when a new Trac environment is created."""

	# プラグインが有効にされたときに、upgradeが必要がきかれる
    def environment_needs_upgrade(db):
        """Called when Trac checks whether the environment needs to be upgraded.
        
        Should return `True` if this participant needs an upgrade to be
        performed, `False` otherwise.
        """

    def upgrade_environment(db):
        """Actually perform an environment upgrade.
        
        Implementations of this method should not commit any database
        transactions. This is done implicitly after all participants have
        performed the upgrades they need without an error being raised.
        """


# リクエストの処理（メニューとか）を拡張する
# ○：入れた
# trac.web.api.IRequestHandler
class IRequestHandler(Interface):
    """Extension point interface for request handlers."""

	# リクエストが自分のものか問い合わせ
    def match_request(req):
        """Return whether the handler wants to process the given request."""

    def process_request(req):
        """Process the request. For ClearSilver, return a (template_name,
        content_type) tuple, where `template` is the ClearSilver template to use
        (either a `neo_cs.CS` object, or the file name of the template), and
        `content_type` is the MIME type of the content. For Genshi, return a
        (template_name, data, content_type) tuple, where `data` is a dictionary
        of substitutions for the template.

        For both templating systems, "text/html" is assumed if `content_type` is
        `None`.

        Note that if template processing should not occur, this method can
        simply send the response itself and not return anything.
        """


# HTTP リクエストの前後処理を拡張する
# trac.web.api.IRequestFilter
# ○：入れた
class IRequestFilter(Interface):
    """Extension point interface for components that want to filter HTTP
    requests, before and/or after they are processed by the main handler."""

    def pre_process_request(req, handler):
        """Called after initial handler selection, and can be used to change
        the selected handler or redirect request.
        
        Always returns the request handler, even if unchanged.
        """

    # for ClearSilver templates
    def post_process_request(req, template, content_type):
        """Do any post-processing the request might need; typically adding
        values to req.hdf, or changing template or mime type.
        
        Always returns a tuple of (template, content_type), even if
        unchanged.

        Note that `template`, `content_type` will be `None` if:
         - called when processing an error page
         - the default request handler did not return any result

        (for 0.10 compatibility; only used together with ClearSilver templates)
        """

    # for Genshi templates
    def post_process_request(req, template, data, content_type):
        """Do any post-processing the request might need; typically adding
        values to the template `data` dictionary, or changing template or
        mime type.
        
        `data` may be update in place.

        Always returns a tuple of (template, data, content_type), even if
        unchanged.

        Note that `template`, `data`, `content_type` will be `None` if:
         - called when processing an error page
         - the default request handler did not return any result

        (Since 0.11)
        """


# ナビゲーション（メニュー）を拡張する
# ○：入れた
# trac.web.chrome.INavigationContributor
class INavigationContributor(Interface):
    """Extension point interface for components that contribute items to the
    navigation.
    """

    def get_active_navigation_item(req):
        """This method is only called for the `IRequestHandler` processing the
        request.
        
        It should return the name of the navigation item that should be
        highlighted as active/current.
        """

	# メニューアイテムの表示方法の問い合わせ
    def get_navigation_items(req):
        """Should return an iterable object over the list of navigation items to
        add, each being a tuple in the form (category, name, text).
        """



# ClearSilver テンプレートを使用する
# ○：入れた
# trac.web.chrome.ITemplateProvider
class ITemplateProvider(Interface):
    """Extension point interface for components that provide their own
    ClearSilver templates and accompanying static resources.
    """

    def get_htdocs_dirs():
        """Return a list of directories with static resources (such as style
        sheets, images, etc.)

        Each item in the list must be a `(prefix, abspath)` tuple. The
        `prefix` part defines the path in the URL that requests to these
        resources are prefixed with.
        
        The `abspath` is the absolute path to the directory containing the
        resources on the local file system.
        """

    def get_templates_dirs():
        """Return a list of directories containing the provided template
        files.
        """


# パーミッションの扱いを拡張する
# trac.perm.IPermissionRequestor
# ○：入れた
class IPermissionRequestor(Interface):
    """Extension point interface for components that define actions."""

	# パーミッション現在の動作を問い合わせ
    def get_permission_actions():
        """Return a list of actions defined by this component.
        
        The items in the list may either be simple strings, or
        `(string, sequence)` tuples. The latter are considered to be "meta
        permissions" that group several simple actions under one name for
        convenience.
        """


# タイムラインを拡張する
# trac.timeline.ITimelineEventProvider
# ○：入れた
class ITimelineEventProvider(Interface):
    """Extension point interface for adding sources for timed events to the
    timeline.
    """

    def get_timeline_filters(req):
        """Return a list of filters that this event provider supports.
        
        Each filter must be a (name, label) tuple, where `name` is the internal
        name, and `label` is a human-readable name for display.

        Optionally, the tuple can contain a third element, `checked`.
        If `checked` is omitted or True, the filter is active by default,
        otherwise it will be inactive.
        """

    def get_timeline_events(req, start, stop, filters):
        """Return a list of events in the time range given by the `start` and
        `stop` parameters.

        The `filters` parameters is a list of the enabled filters, each item
        being the name of the tuples returned by `get_timeline_filters`.

        Since 0.11, the events are `(kind, date, author, data)` tuples,
        where `kind` is a string used for categorizing the event, `date`
        is a `datetime` object, `author` is a string and `data` is some
        private data that the component will reuse when rendering the event.

        When the event has been created indirectly by another module,
        like this happens when calling `AttachmentModule.get_timeline_events()`
        the tuple can also specify explicitly the provider by returning tuples
        of the following form: `(kind, date, author, data, provider)`.

        Before version 0.11,  the events returned by this function used to
        be tuples of the form `(kind, href, title, date, author, markup)`.
        This is still supported but less flexible, as `href`, `title` and
        `markup` are not context dependent.
        """

    def render_timeline_event(context, field, event):
        """Display the title of the event in the given context.

        :param context: the rendering `Context` object that can be used for
                        rendering
        :param field: what specific part information from the event should
                      be rendered: can be the 'title', the 'description' or
                      the 'url'
        :param event: the event tuple, as returned by `get_timeline_events`
        """


# Mimeview コンポーネントの HTML 描画を拡張する
# trac.mimeview.api.IHTMLPreviewRenderer
# ○：入れた
class IHTMLPreviewRenderer(Interface):
    """Extension point interface for components that add HTML renderers of
    specific content types to the `Mimeview` component.

    ----
    This interface will be merged with IContentConverter, as conversion
    to text/html will be simply a particular type of content conversion.

    However, note that the IHTMLPreviewRenderer will still be supported
    for a while through an adapter, whereas the IContentConverter interface
    itself will be changed.

    So if all you want to do is convert to HTML and don't feel like
    following the API changes, rather you should rather implement this
    interface for the time being.
    ---
    """

    # implementing classes should set this property to True if they
    # support text content where Trac should expand tabs into spaces
    expand_tabs = False

    # indicate whether the output of this renderer is source code that can
    # be decorated with annotations
    returns_source = False

    def get_quality_ratio(mimetype):
        """Return the level of support this renderer provides for the `content`
        of the specified MIME type. The return value must be a number between
        0 and 9, where 0 means no support and 9 means "perfect" support.
        """

    def render(context, mimetype, content, filename=None, url=None):
        """Render an XHTML preview of the raw `content` within a Context.

        The `content` might be:
         * a `str` object
         * an `unicode` string
         * any object with a `read` method, returning one of the above

        It is assumed that the content will correspond to the given `mimetype`.

        Besides the `content` value, the same content may eventually
        be available through the `filename` or `url` parameters.
        This is useful for renderers that embed objects, using <object> or
        <img> instead of including the content inline.
        
        Can return the generated XHTML text as a single string or as an
        iterable that yields strings. In the latter case, the list will
        be considered to correspond to lines of text in the original content.
        """


# チケットの作成、変更、削除時の動作を拡張する
# ○：入れた
# trac.ticket.api.ITicketChangeListener
class ITicketChangeListener(Interface):
    """Extension point interface for components that require notification
    when tickets are created, modified, or deleted."""

    def ticket_created(ticket):
        """Called when a ticket is created."""

    def ticket_changed(ticket, comment, author, old_values):
        """Called when a ticket is modified.
        
        `old_values` is a dictionary containing the previous values of the
        fields that have changed.
        """

    def ticket_deleted(ticket):
        """Called when a ticket is deleted."""





その他
# 
# trac.web.api.ITemplateStreamFilter
# ○：入れた
class ITemplateStreamFilter(Interface):
    """Filter a Genshi event stream prior to rendering."""

    def filter_stream(req, method, filename, stream, data):
        """Return a filtered Genshi event stream, or the original unfiltered
        stream if no match.

        `req` is the current request object, `method` is the Genshi render
        method (xml, xhtml or text), `filename` is the filename of the template
        to be rendered, `stream` is the event stream and `data` is the data for
        the current template.

        See the Genshi documentation for more information.
        """


# 
# trac.web.api.IAuthenticator
# ○：入れた
class IAuthenticator(Interface):
    """Extension point interface for components that can provide the name
    of the remote user."""

    def authenticate(req):
        """Return the name of the remote user, or `None` if the identity of the
        user is unknown."""


# パーミッション管理を拡張する
# trac.perm.IPermissionStore
# ○：入れた
class IPermissionStore(Interface):
    """Extension point interface for components that provide storage and
    management of permissions."""

    def get_user_permissions(username):
        """Return all permissions for the user with the specified name.
        
        The permissions are returned as a dictionary where the key is the name
        of the permission, and the value is either `True` for granted
        permissions or `False` for explicitly denied permissions."""

    def get_users_with_permissions(permissions):
        """Retrieve a list of users that have any of the specified permissions.

        Users are returned as a list of usernames.
        """

    def get_all_permissions():
        """Return all permissions for all users.

        The permissions are returned as a list of (subject, action)
        formatted tuples."""

    def grant_permission(username, action):
        """Grant a user permission to perform an action."""

    def revoke_permission(username, action):
        """Revokes the permission of the given user to perform an action."""


# パーミッショングループを拡張する
# trac.perm.IPermissionGroupProvider
# ○：入れた
class IPermissionGroupProvider(Interface):
    """Extension point interface for components that provide information about
    user groups.
    """

    def get_permission_groups(username):
        """Return a list of names of the groups that the user with the specified
        name is a member of."""



# パーミッションポリシーを拡張する
# trac.perm.IPermissionPolicy
# ○：入れた
class IPermissionPolicy(Interface):
    """A security policy provider used for fine grained permission checks."""

    def check_permission(action, username, resource, perm):
        """Check that the action can be performed by username on the resource

        :param action: the name of the permission
        :param username: the username string or 'anonymous' if there's no
                         authenticated user
        :param resource: the resource on which the check applies.
                         Will be `None`, if the check is a global one and
                         not made on a resource in particular
        :param perm: the permission cache for that username and resource, 
                     which can be used for doing secondary checks on other
                     permissions. Care must be taken to avoid recursion.  

        :return: `True` if action is allowed, `False` if action is denied,
                 or `None` if indifferent. If `None` is returned, the next
                 policy in the chain will be used, and so on.

        Note that when checking a permission on a realm resource (i.e. when
        `.id` is `None`), this usually corresponds to some preliminary check
        done before making a fine-grained check on some resource.
        Therefore the `IPermissionPolicy` should be conservative and return:

         * `True` if the action *can* be allowed for some resources in
           that realm. Later, for specific resource, the policy will be able
           to return `True` (allow), `False` (deny) or `None` (don't decide).
         * `None` if the action *can not* be performed for *some* resources.
           This corresponds to situation where the policy is only interested
           in returning `False` or `None` on specific resources.
         * `False` if the action *can not* be performed for *any* resource in
           that realm (that's a very strong decision as that will usually
           prevent any fine-grained check to even happen).

        Note that performing permission checks on realm resources may seem
        redundant for now as the action name itself contains the realm, but
        this will probably change in the future (e.g. `'VIEW' in ...`).
        """


# チケットワークフローを拡張する
# trac.ticket.api.ITicketActionController
# ○：入れた
class ITicketActionController(Interface):
    """Extension point interface for components willing to participate
    in the ticket workflow.

    This is mainly about controlling the changes to the ticket ''status'',
    though not restricted to it.
    """

    def get_ticket_actions(req, ticket):
        """Return an iterable of `(weight, action)` tuples corresponding to
        the actions that are contributed by this component.
        That list may vary given the current state of the ticket and the
        actual request parameter.

        `action` is a key used to identify that particular action.
        (note that 'history' and 'diff' are reserved and should not be used
        by plugins)
        
        The actions will be presented on the page in descending order of the
        integer weight. The first action in the list is used as the default
        action.

        When in doubt, use a weight of 0."""

    def get_all_status():
        """Returns an iterable of all the possible values for the ''status''
        field this action controller knows about.

        This will be used to populate the query options and the like.
        It is assumed that the initial status of a ticket is 'new' and
        the terminal status of a ticket is 'closed'.
        """

    def render_ticket_action_control(req, ticket, action):
        """Return a tuple in the form of `(label, control, hint)`

        `label` is a short text that will be used when listing the action,
        `control` is the markup for the action control and `hint` should
        explain what will happen if this action is taken.
        
        This method will only be called if the controller claimed to handle
        the given `action` in the call to `get_ticket_actions`.

        Note that the radio button for the action has an `id` of
        `"action_%s" % action`.  Any `id`s used in `control` need to be made
        unique.  The method used in the default ITicketActionController is to
        use `"action_%s_something" % action`.
        """

    def get_ticket_changes(req, ticket, action):
        """Return a dictionary of ticket field changes.

        This method must not have any side-effects because it will also
        be called in preview mode (`req.args['preview']` will be set, then).
        See `apply_action_side_effects` for that. If the latter indeed triggers
        some side-effects, it is advised to emit a warning
        (`trac.web.chrome.add_warning(req, reason)`) when this method is called
        in preview mode.

        This method will only be called if the controller claimed to handle
        the given `action` in the call to `get_ticket_actions`.
        """

    def apply_action_side_effects(req, ticket, action):
        """Perform side effects once all changes have been made to the ticket.

        Multiple controllers might be involved, so the apply side-effects
        offers a chance to trigger a side-effect based on the given `action`
        after the new state of the ticket has been saved.

        This method will only be called if the controller claimed to handle
        the given `action` in the call to `get_ticket_actions`.
        """


# XHTML の Annotation 拡張？？
# trac.mimeview.api.IHTMLPreviewAnnotator
# ○：入れた
class IHTMLPreviewAnnotator(Interface):
    """Extension point interface for components that can annotate an XHTML
    representation of file contents with additional information."""

    def get_annotation_type():
        """Return a (type, label, description) tuple
        that defines the type of annotation and provides human readable names.
        The `type` element should be unique to the annotator.
        The `label` element is used as column heading for the table,
        while `description` is used as a display name to let the user
        toggle the appearance of the annotation type.
        """
        
    def get_annotation_data(context):
        """Return some metadata to be used by the `annotate_row` method below.

        This will be called only once, before lines are processed.
        If this raises an error, that annotator won't be used.
        """

    def annotate_row(context, row, number, line, data):
        """Return the XHTML markup for the table cell that contains the
        annotation data.

        `context` is the context corresponding to the content being annotated,
        `row` is the tr Element being built, `number` is the line number being
        processed and `line` is the line's actual content.
        `annotations` is whatever additional data the `get_annotation_data`
        method decided to provide.
        """


# MIME コンテンツの変換？？
# trac.mimeview.api.IContentConverter
# ○：入れた
class IContentConverter(Interface):
    """An extension point interface for generic MIME based content
    conversion.

    ----
    NOTE: This api will likely change in the future, e.g.:

    def get_supported_conversions(input): 
        '''Tells whether this converter can handle this `input` type.

        Return an iterable of `Conversion` objects, each describing
        how the conversion should be done and what will be the output type.
        '''

    def convert_content(context, conversion, content): 
        '''Convert the given `AbstractContent` as specified by `Conversion`.

        The conversion takes place in the given rendering context.
        
        Return the converted content, which ''must'' be a `MimeContent` object.
        '''
    ----
    """

    def get_supported_conversions():
        """Return an iterable of tuples in the form (key, name, extension,
        in_mimetype, out_mimetype, quality) representing the MIME conversions
        supported and
        the quality ratio of the conversion in the range 0 to 9, where 0 means
        no support and 9 means "perfect" support. eg. ('latex', 'LaTeX', 'tex',
        'text/x-trac-wiki', 'text/plain', 8)"""

    def convert_content(req, mimetype, content, key):
        """Convert the given content from mimetype to the output MIME type
        represented by key. Returns a tuple in the form (content,
        output_mime_type) or None if conversion is not possible."""


# Wikiの変更処理を拡張する
#trac.wiki.api.IWikiChangeListener
# ○：入れた
class IWikiChangeListener(Interface):
    """Extension point interface for components that should get notified about
    the creation, deletion and modification of wiki pages.
    """

    def wiki_page_added(page):
        """Called whenever a new Wiki page is added."""

    def wiki_page_changed(page, version, t, comment, author, ipnr):
        """Called when a page has been modified."""

    def wiki_page_deleted(page):
        """Called when a page has been deleted."""

    def wiki_page_version_deleted(page):
        """Called when a version of a page has been deleted."""


# Wikiページ変更前後の処理を拡張する
# trac.wiki.api.IWikiPageManipulator
# ○：入れた
class IWikiPageManipulator(Interface):
    """Extension point interface for components that need to do specific
    pre and post processing of wiki page changes.
    
    Unlike change listeners, a manipulator can reject changes being committed
    to the database.
    """

    def prepare_wiki_page(req, page, fields):
        """Not currently called, but should be provided for future
        compatibility."""

    def validate_wiki_page(req, page):
        """Validate a wiki page after it's been populated from user input.
        
        Must return a list of `(field, message)` tuples, one for each problem
        detected. `field` can be `None` to indicate an overall problem with the
        page. Therefore, a return value of `[]` means everything is OK."""


# Wiki マクロを拡張する
# trac.wiki.api.IWikiMacroProvider
# ○：入れた
class IWikiMacroProvider(Interface):
    """Extension point interface for components that provide Wiki macros."""

    def get_macros():
        """Return an iterable that provides the names of the provided macros."""

    def get_macro_description(name):
        """Return a plain text description of the macro with the specified name.
        """

    def render_macro(req, name, content):
        """Return the HTML output of the macro (deprecated)"""

    def expand_macro(formatter, name, content, args={}):
        """Called by the formatter when rendering the parsed wiki text.

        `content` is the content of the macro call. When called using macro
        syntax (`[[Macro(content)]]`), this is the string contained between
        parentheses, usually containing macro arguments. When called using wiki
        processor syntax (`{{{!#Macro ...}}}`), it is the content of the
        processor block, that is, the text starting on the line following the
        macro name. In this case, `args` contains the named arguments passed on
        the same line as the macro name.

        (since 0.11)
        """


# Wiki シンタックスを拡張する
# trac.wiki.api.IWikiSyntaxProvider
# ○：入れた
class IWikiSyntaxProvider(Interface):
 
    def get_wiki_syntax():
        """Return an iterable that provides additional wiki syntax.

        Additional wiki syntax correspond to a pair of (regexp, cb),
        the `regexp` for the additional syntax and the callback `cb`
        which will be called if there's a match.
        That function is of the form cb(formatter, ns, match).
        """
 
    def get_link_resolvers():
        """Return an iterable over (namespace, formatter) tuples.

        Each formatter should be a function of the form
        fmt(formatter, ns, target, label), and should
        return some HTML fragment.
        The `label` is already HTML escaped, whereas the `target` is not.
        """



# チケットのワークフローを拡張する？
# ○：入れた
# trac.ticket.api.ITicketManipulator
class ITicketManipulator(Interface):
    """Miscellaneous manipulation of ticket workflow features."""

    def prepare_ticket(req, ticket, fields, actions):
        """Not currently called, but should be provided for future
        compatibility."""

    def validate_ticket(req, ticket):
        """Validate a ticket after it's been populated from user input.
        
        Must return a list of `(field, message)` tuples, one for each problem
        detected. `field` can be `None` to indicate an overall problem with the
        ticket. Therefore, a return value of `[]` means everything is OK."""



# 管理画面の作成
# -*- coding: utf-8 -*-
# 
# Copyright (C)2006-2009 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.

# ○：入れた
from trac.core import *


class IAdminPanelProvider(Interface):
    """Extension point interface for adding panels to the web-based
    administration interface.
    """

    def get_admin_panels(req):
        """Return a list of available admin panels.
        
        The items returned by this function must be tuples of the form
        `(category, category_label, page, page_label)`.
        """

    def render_admin_panel(req, category, page, path_info):
        """Process a request for an admin panel.
        
        This function should return a tuple of the form `(template, data)`,
        where `template` is the name of the template to use and `data` is the
        data to be passed to the template.
        """
