from enthought.traits.ui.menu import Action, Menu, Separator
from enthought.traits.ui.api import Handler
from enthought.pyface.image_resource  import ImageResource


actions_doc = None
def _buildAction(desc):
    global actions_doc
    from window import tcActionHandler
    if len(desc) == 0:
        return Separator()
    exec("tcActionHandler.%s = lambda self,i:self.chooseAction(i,'_on_%s')"%(desc["name"],desc["name"]))
    style = desc["name"].startswith("toggle") and "toggle" or "push"
    default = False
    if "default" in desc:
        default = desc["default"]
    desc["tooltip"] = desc["tooltip"].strip()
    action = Action(name=desc["name"].replace("_"," "), action=desc["name"],
                  tooltip=desc["tooltip"],
                  image=ImageResource(desc["name"]),
                  style=style,
                  checked=default)
    tcActionHandler.actions[desc["name"]] = action
    if not actions_doc is None:
        actions_doc += "\n**%s**:\n"%(desc["name"].replace("_"," ").strip())
        actions_doc += "\n.. image:: images/%s.png\n\n"%(desc["name"])
        actions_doc += desc["tooltip"] +"\n"
    return action

# this is a bit ugly, but still better than duplicating the documentation in .rst and tooltips
def _create_toolbar_actions():
    actions = (
        {},
        {"name": "invert","tooltip":"""Invert processes show/hide value.

This is useful, when you are fully zoomed, and you want to see 
if you are not missing some valuable info in the hidden processes"""},
        {"name": "select_all","tooltip":"""Select/Unselect all process visible in the process list

Thus processes that are filtered are always unselected by this command"""},
        {},
        {"name": "show","tooltip":"""Show selected processes in the timechart"""},
        {"name": "hide","tooltip":"""Hide selected processes in the timechart"""},
        {},
        {"name": "hide_others","tooltip":
"""Hide process that are not shown at current zoom window

All processes that *are not* currently visible in the timechart will be hidden
This is useful when you zoom at a particular activity, and you want to unzoom 
without being noised by other activities."""
         },
        {"name": "hide_onscreen","tooltip":
"""Hide process that are shown at current zoom window

All processes that *are* currently visible in the timechart will be hidden
This is useful when you zoom at a particular noise activity, and you want to unzoom 
without being annoyed by this activity."""
         },
        {},
        {"name": "toggle_autohide","tooltip":"""*autoHide* processes that do not have any events in the current zooming window

If this option is disabled, and a process does not have any activity in the
current view, this will show an empty line, and eat vertical space for not
much meaning. This is why it is recommanded to leave this setting on.
""",
         "default":True},
        {"name": "toggle_auto_zoom_y","tooltip":"""Automatically set the y scale to fit the number of process shown

This make sure all the process that are not hidden fit the window vertically.
 
Disable this feature if you want to manually zoom though the y-axis with the *CTRL+mouse wheel* command.
""",
         "default":True},
        {},
        {"name": "toggle_wakes","tooltip":"""Show/Hide the wake_events.

Wake events are generated by the "sched_wakeup" trace_event. wake events are
represented by a row connecting a process to another.

Reason of wakes can be for example: 
* kernel driver waking up process because IO is available.
* user thread releasing mutex on which another thread was waiting for.

Disabled by default because this slows down a lot graphics, and adds a lot 
of noise when fully unzoomed"""
         },
        {"name": "toggle_cpufreq","tooltip":'Show/Hide the cpufreq representation.', "default":True},
        {"name": "toggle_cpuidle","tooltip":'Show/Hide the cpuidle representation.', "default":True},
# only for debugging overview
#        {"name": "toggle_overview","tooltip":'This will accelerate plotting by merging contiguous events when zoomed out.', "default":True},
        {},
        {"name": "trace_text","tooltip":"""Shows the text trace of the selection

Sometimes, looking at the textual trace is more precise than just looking at the timechart.
Moreover, all the informations of the trace is not represented by the timechart.

You can also save some part of a trace to another file with this option
"""
         },
        {"name": "zoom","tooltip":"""Zoom so that the selection fits the window"""},
        {"name": "unzoom","tooltip":'Unzoom to show the whole trace'},
        )
    ret = []
    for i in actions:
        ret.append(_buildAction(i))
    return tuple(ret)
def _create_menubar_actions():
    desc = (('&File', ( {"name": "open_trace_file","tooltip":'open new file into pytimechart'},
                        {"name": "exit","tooltip":'exit pytimechart'})),
            ('&Help', ( {"name": "about","tooltip":'about'},{"name": "doc","tooltip":'doc'})))
    ret = []
    for menu in desc:
        actions = []
        for action in menu[1]:
            actions.append(_buildAction(action))
        ret.append(Menu(*tuple(actions), name = menu[0]))
    return tuple(ret)

if __name__ == '__main__':
    actions_doc = ""
    _create_toolbar_actions()
    wholedoc = open("docs/sources/userguide.rst").read()
    start = ".. start_automatically_generated_from_tooltips\n"
    end = ".. end_automatically_generated_from_tooltips\n"
    wholedoc = wholedoc[0:wholedoc.find(start)+len(start)] + actions_doc + wholedoc[wholedoc.find(end)-1:]
    f = open("docs/sources/userguide.rst","w")
    f.write(wholedoc)
    f.close()
