def _set_window_icon(self):
        if self.icon is None:
            icon = ImageResource('application.png')
        else:
            icon = self.icon

        self.control.setWindowIcon(icon.create_icon())
Example #2
0
    def set_icon(self, icon=None):
        """Sets the dialog's icon."""

        from enthought.pyface.image_resource import ImageResource

        if not isinstance(icon, ImageResource):
            icon = ImageResource('frame.png')

        self.control.setWindowIcon(icon.create_icon())
Example #3
0
class AboutDialog(MAboutDialog, Dialog):
    """ The toolkit specific implementation of an AboutDialog.  See the
    IAboutDialog interface for the API documentation.
    """

    implements(IAboutDialog)

    #### 'IAboutDialog' interface #############################################

    additions = List(Unicode)

    image = Instance(ImageResource, ImageResource('about'))

    ###########################################################################
    # Protected 'IDialog' interface.
    ###########################################################################

    def _create_contents(self, parent):
        label = QtGui.QLabel()

        if parent.parent() is not None:
            title = parent.parent().windowTitle()
        else:
            title = ""

        # Set the title.
        self.title = "About %s" % title

        # Load the image to be displayed in the about box.
        image = self.image.create_image()
        #path = self.image.absolute_path
        path = './radpy/images/about.png'
        # The additional strings.
        additions = '<br />'.join(self.additions)

        # Get the version numbers.
        py_version = sys.version[0:sys.version.find("(")]
        pyqt_version = QtCore.PYQT_VERSION_STR
        qt_version = QtCore.QT_VERSION_STR

        # Set the page contents.
        label.setText(_DIALOG_TEXT % (path, additions, py_version, pyqt_version, qt_version))

        # Create the button.
        buttons = QtGui.QDialogButtonBox()

        if self.ok_label:
            buttons.addButton(self.ok_label, QtGui.QDialogButtonBox.AcceptRole)
        else:
            buttons.addButton(QtGui.QDialogButtonBox.Ok)

        buttons.connect(buttons, QtCore.SIGNAL('accepted()'), parent, QtCore.SLOT('accept()'))

        lay = QtGui.QVBoxLayout()
        lay.addWidget(label)
        lay.addWidget(buttons)

        parent.setLayout(lay)
Example #4
0
    def _get_image_not_found(cls):
        """ Returns the 'image not found' image resource. """

        if cls._image_not_found is None:
            from enthought.pyface.image_resource import ImageResource

            cls._image_not_found = ImageResource('image_not_found')

        return cls._image_not_found
Example #5
0
 def dialog_view(self):
     """ Returns a view with an icon and a title.
     """
     view = self.trait_view()
     icon = self._icon_path + os.sep + 'images' + os.sep \
                         + self.icon
     view.icon = ImageResource(icon)
     view.title = "Edit%s: %s" % (self.type, self.name)
     view.buttons = ['OK', 'Cancel']
     return view
 def traits_view(self):
     file_menu = Menu( 
         ActionGroup(
             Action(id="open", name=u"打开", action="open_file"),
             Action(id="save", name=u"保存", action="save_file"),
         ),
         ActionGroup(
             Action(id="exit_app", name=u"退出", action="exit_app"),
         ),
         name = u"文件"
     )
     
     about_menu = Menu(
         Action(id="about", name=u"关于", action="about_dialog"),
         name = u"帮助"
     )
     
     tool_bar = ToolBar( 
         Action(
             image = ImageResource("folder_page.png", search_path = ["img"]),
             tooltip = u"打开文档",
             action = "open_file"
         ), 
         Action(
             image = ImageResource("disk.png", search_path = ["img"]),
             tooltip = u"保存文档",
             action = "save_file"
         ),                 
     )
     
     return View(
         Item("text", style="custom", show_label=False, 
             editor=CodeEditor(line="current_line")),
         menubar = MenuBar(file_menu, about_menu), 
         toolbar = tool_bar,
         statusbar = ["status_info"], 
         resizable = True,
         width = 500, height = 300,
         title = u"程序编辑器",
         handler = MenuDemoHandler()
     )
Example #7
0
class Employee(HasTraits):

    # Define the traits:
    name = Str
    dept = Str
    email = Str

    # Define the view:
    view = View(
        VGroup(
            VGroup(
                Item('name',
                     show_label=False,
                     editor=ImageEditor(image=ImageResource(
                         'info', search_path=search_path)))),
            VGroup(Item('name'), Item('dept'), Item('email'))))
Example #8
0
class Bugfix(Action):
    """ An action that pop up the bugfix GitHub page in a browser. """

    name = "Bugfixes"
    tooltip = "Bug Fixes ..."
    description = "Bug Fixes ..."
    image = ImageResource("bug.png", search_path=[IMAGE_PATH])

    ###########################################################################
    # 'Action' interface.
    ###########################################################################

    def perform(self, event):
        """ Performs the action. """
        browser_open(url='http://github.com/LTS5/connectomeviewer/issues',
                     decorated=True)
Example #9
0
class HelpIndex(Action):
    """ An action that pop up the help in a browser. """

    name = "Help"
    tooltip = "The Connectome Viewer User Guide"
    description = "The Connectome Viewer User Guide"
    image = ImageResource("help-browser.png", search_path=[IMAGE_PATH])

    ###########################################################################
    # 'Action' interface.
    ###########################################################################

    def perform(self, event):
        """ Performs the action. """
        auto_close_message("Opening help in web browser...")
        browser_open(url='http://www.connectomeviewer.org/documentation',
                     decorated=True)
Example #10
0
class FeatureTool(DockWindowFeature):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    image = ImageResource('feature_tool')

    #---------------------------------------------------------------------------
    #  Returns whether a specified object can be dropped on the feature image:
    #---------------------------------------------------------------------------

    def can_drop(self, object):
        """ Returns whether a specified object can be dropped on the feature 
            image.
        """
        return True
Example #11
0
    def _actions_default(self):
        """ Append a preferences action to the toolbar: this view of the
            engine is meant to be a powerful view giving access to
            all of Mayavi's functionality.
        """
        preferences_action = \
            Action(
                image=ImageResource('preferences.png',
                                     search_path=self._image_path),
                tooltip="Modify Mayavi's preferences",
                checked=False,
                defined_when='True',
                perform=preference_manager_view.dialog_view,
            )

        actions = super(EngineRichView, self)._actions_default()
        actions.extend((Separator(), preferences_action))
        return actions
Example #12
0
class Keybindings(Action):
    """ An action that creates a temporary html file to show the key bindings.. """

    name = "Key Bindings"
    tooltip = "Show Key Bindings in Browser"
    description = "Key Bindings"
    image = ImageResource("keyboard.png", search_path=[IMAGE_PATH])

    ###########################################################################
    # 'Action' interface.
    ###########################################################################

    def perform(self, event):
        """ Performs the action. """
        import os.path
        browser_open(url=os.path.join(IMAGE_PATH, '..', 'keybindings',
                                      'index.html'),
                     decorated=True)
Example #13
0
class SaveCFile(Action):
    """ An action that save aconnectome file """

    name = "Save CFF File"
    description = "Save the connectome file"
    tooltip = "Save a CFF file"
    path = Str("MenuBar/File/LoadDataMenu")
    image = ImageResource("cff-open.png", search_path=[IMAGE_PATH])

    # Is the action enabled?
    enabled = Bool(True)

    # Is the action visible?
    visible = Bool(True)

    ###########################################################################
    # 'Action' interface.
    ###########################################################################

    def perform(self, event, cfile=None):
        """ Performs the action. """

        logger.info('Performing save connectome file action')

        # helper variable to use this function not only in the menubar
        exec_as_funct = True

        cfile = self.window.application.get_service(
            'cviewer.plugins.cff2.cfile.CFile')

        wildcard = "Connectome File Format v2.0 (*.cff)|*.cff|" \
                    "All files (*.*)|*.*"

        dlg = FileDialog(wildcard=wildcard,title="Save as Connectome File",\
                         resizeable=False, action = 'save as',\
                         default_directory=preference_manager.cviewerui.cffpath,)

        if dlg.open() == OK:

            if (dlg.paths[0]).endswith('.cff'):

                cfflib.save_to_cff(cfile.obj, dlg.paths[0])
                logger.info("Saved connectome file to %s" % dlg.paths[0])
Example #14
0
class GraphEditorExtension(Editor):
    """ Associates a graph editor with '.dot' file extensions.
    """

    # The object contribution's globally unique identifier.
    id = "godot.plugin.graph_editor"

    # A name that will be used in the UI for this editor
    name = "Graph Editor"

    # An icon that will be used for all resources that match the
    # specified extensions
    image = ImageResource("graph", search_path=[IMAGE_LOCATION])

    # The contributed editor class
    editor_class = "godot.plugin.graph_editor:GraphEditor"

    # The list of file types understood by the editor
    extensions = [".dot", ".xdot"]

    # If true, this editor will be used as the default editor for the type
    default = True
Example #15
0
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
Example #16
0
#------------------------------------------------------------------------------
#  Local imports:
#------------------------------------------------------------------------------

from godot.base_graph import BaseGraph
from godot.api import Graph, Cluster, Node, Edge, GodotDataParser, Subgraph

from godot.ui.graph_menu import menubar, toolbar
from godot.ui.graph_view import nodes_view, edges_view, attr_view, about_view
from godot.ui.graph_tree import graph_tree_editor

#------------------------------------------------------------------------------
#  Constants:
#------------------------------------------------------------------------------

frame_icon = ImageResource("dot.ico")

#------------------------------------------------------------------------------
#  "GraphViewModel" class:
#------------------------------------------------------------------------------

class GraphViewModel(ModelView):
    """ Defines a view model for Graphs.  """

    #--------------------------------------------------------------------------
    #  Trait definitions:
    #--------------------------------------------------------------------------

    # File path to to use for saving.
    save_file = File
Example #17
0
    def _get_index_text(self):
        return str(self.row)

    def _get_index_image(self):
        x, y, z = self.item
        if sqrt((x - 0.5)**2 + (y - 0.5)**2 + (z - 0.5)**2) <= 0.25:
            return 'red_flag'
        return None


#--[Tabular Editor Definition]--------------------------------------------------

tabular_editor = TabularEditor(
    adapter=ArrayAdapter(),
    images=[ImageResource('red_flag', search_path=search_path)])

#--[ShowArray Class]------------------------------------------------------------


class ShowArray(HasTraits):

    data = Array

    view = View(Item('data', editor=tabular_editor, show_label=False),
                title='Array Viewer',
                width=0.3,
                height=0.8,
                resizable=True,
                buttons=NoButtons)
Example #18
0
class EngineView(HasTraits):
    """ A view displaying the engine's object tree. """

    # The MayaVi engine we are a view of.
    engine = Instance(Engine, allow_none=True)

    # Path used to search for images
    _image_path = [
        join(resource_path(), 'images'),
    ]

    # The icon of the dialog
    icon = ImageResource('mv2.ico', search_path=_image_path)

    # Nodes on the tree.
    nodes = Any

    # TreeEditor
    tree_editor = Instance(TreeEditor)

    # Toolbar
    toolbar = Instance(ToolBar)

    # Toolbar actions.
    actions = List(Either(Action, Separator))

    # Some delegates, for the toolbar to update
    scenes = Delegate('engine')
    current_selection = Delegate('engine')

    ###########################################################################
    # `object` interface.
    ###########################################################################
    def __init__(self, **traits):
        super(EngineView, self).__init__(**traits)

    ###########################################################################
    # `HasTraits` interface.
    ###########################################################################
    def default_traits_view(self):
        """The default traits view of the Engine View.
        """

        view = View(Item(name='engine',
                         id='engine',
                         editor=self.tree_editor,
                         resizable=True,
                         show_label=False),
                    id='enthought.mayavi.engine',
                    help=False,
                    resizable=True,
                    scrollable=True,
                    undo=False,
                    revert=False,
                    ok=False,
                    cancel=False,
                    icon=self.icon,
                    title='Mayavi pipeline',
                    toolbar=self.toolbar,
                    handler=EngineViewHandler)
        return view

    def _nodes_default(self):
        """ The default value of the cached nodes list.
        """
        # Now setup the view.
        nodes = [
            TreeNode(
                node_for=[Engine],
                children='children_ui_list',
                label='=Mayavi',
                auto_open=False,
                copy=False,
                delete=False,
                rename=True,
            ),
            ObjectTreeNode(
                node_for=[Base],
                children='children_ui_list',
                label='name',
                auto_open=True,
                copy=True,
                delete=True,
                rename=True,
                tooltip='=Right click for more options',
            ),
            AdderTreeNode(
                node_for=[SceneAdderNode],
                icon_item='add_scene.png',
            ),
            AdderTreeNode(
                node_for=[SourceAdderNode],
                icon_item='add_source.png',
            ),
            AdderTreeNode(
                node_for=[ModuleFilterAdderNode],
                icon_item='add_module.png',
            ),
        ]
        return nodes

    def _tree_editor_default(self):
        return TreeEditor(editable=False,
                          hide_root=True,
                          on_dclick='handler._on_dclick',
                          on_select='handler._on_select',
                          orientation='vertical',
                          selected='object.engine.current_selection',
                          nodes=self.nodes)

    def _toolbar_default(self):
        toolbar = ToolBar(*self.actions)
        toolbar.image_size = (16, 16)
        toolbar.show_tool_names = False
        toolbar.show_divider = False
        return toolbar

    def _actions_default(self):
        add_scene = \
            Action(
                image=ImageResource('add_scene.png',
                                            search_path=self._image_path),
                tooltip="Create a new scene",
                defined_when='True',
                enabled_when='True',
                perform=self._perform_new_scene,
            )

        add_source = \
            Action(
                image=ImageResource('add_source.png',
                                            search_path=self._image_path),
                tooltip="Add a data source",
                defined_when='True',
                enabled_when='len(scenes) > 0',
                perform=self._perform_add_source,
            )

        add_module = \
            Action(
                image=ImageResource('add_module.png',
                                            search_path=self._image_path),
                tooltip="Add a visualization module",
                defined_when='True',
                # isinstance doesn't work in enabled_when
                enabled_when=\
                    'current_selection is not None and'
                    '( hasattr(current_selection, "output_info")'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_module,
            )

        add_filter = \
            Action(
                image=ImageResource('add_filter.png',
                                            search_path=self._image_path),
                tooltip="Add a processing filter",
                defined_when='True',
                enabled_when=\
                    'current_selection is not None and'
                    '( ( hasattr(current_selection, "output_info")'
                    ' and not current_selection.type in (" module", '
                    ' " module manager"))'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_filter,
             )

        help = \
            Action(
                image=ImageResource('help-action.png',
                                            search_path=self._image_path),
                tooltip="Help on the Mayavi pipeline",
                defined_when='True',
                enabled_when='True',
                perform=open_help_index,
            )

        tvtk_docs = \
            Action(
                image=ImageResource('reader.png',
                                            search_path=self._image_path),
                tooltip="Search the VTK class browser",
                defined_when='True',
                enabled_when='True',
                perform=open_tvtk_docs,
            )

        record = \
            Action(
                image=ImageResource('record.png',
                                     search_path=self._image_path),
                tooltip="Start/Stop script recording",
                style='toggle',
                checked=False,
                defined_when='True',
                enabled_when='engine is not None',
                perform=self._perform_record,
            )

        # Check the record icon if the engine already has a recorder
        # set.
        if self.engine is not None and self.engine.recorder is not None:
            record.checked = True

        return [
            tvtk_docs,
            Separator(), add_scene, add_source, add_module, add_filter,
            Separator(), help, record
        ]

    ###########################################################################
    # Private interface.
    ###########################################################################
    def _perform_new_scene(self):
        self.engine.new_scene()
        self.engine.current_selection = self.engine.current_scene

    def _perform_add_source(self):
        adder = SourceAdderNode(object=self.engine.current_scene)
        adder.edit_traits(view=adder.dialog_view())

    def _perform_add_module(self):
        object = self.engine.current_selection
        if isinstance(object, AdderNode):
            object = object.object
        adder = ModuleAdderNode(object=object)
        adder.edit_traits(view=adder.dialog_view())

    def _perform_add_filter(self):
        object = self.engine.current_selection
        if isinstance(object, AdderNode):
            object = object.object
        adder = FilterAdderNode(object=object)
        adder.edit_traits(view=adder.dialog_view())

    def _perform_record(self):
        e = self.engine
        if e.recorder is None:
            start_recording(e, known=True, script_id='engine')
        else:
            stop_recording(e, save=False)

    def _recorder_changed_for_engine(self, recorder):
        """Called when the recorder trait on the engine trait of this
        object changes.

        This basically toggles the recording action when someone
        attaches a recorder to the engine.
        """
        record_action = None
        for action in self.actions:
            if hasattr(action, 'tooltip') and \
               action.tooltip.endswith('recording'):
                record_action = action
                break

        if record_action is not None:
            if recorder is not None:
                record_action.checked = True
            else:
                record_action.checked = False
Example #19
0
    def _actions_default(self):
        add_scene = \
            Action(
                image=ImageResource('add_scene.png',
                                            search_path=self._image_path),
                tooltip="Create a new scene",
                defined_when='True',
                enabled_when='True',
                perform=self._perform_new_scene,
            )

        add_source = \
            Action(
                image=ImageResource('add_source.png',
                                            search_path=self._image_path),
                tooltip="Add a data source",
                defined_when='True',
                enabled_when='len(scenes) > 0',
                perform=self._perform_add_source,
            )

        add_module = \
            Action(
                image=ImageResource('add_module.png',
                                            search_path=self._image_path),
                tooltip="Add a visualization module",
                defined_when='True',
                # isinstance doesn't work in enabled_when
                enabled_when=\
                    'current_selection is not None and'
                    '( hasattr(current_selection, "output_info")'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_module,
            )

        add_filter = \
            Action(
                image=ImageResource('add_filter.png',
                                            search_path=self._image_path),
                tooltip="Add a processing filter",
                defined_when='True',
                enabled_when=\
                    'current_selection is not None and'
                    '( ( hasattr(current_selection, "output_info")'
                    ' and not current_selection.type in (" module", '
                    ' " module manager"))'
                    'or current_selection.__class__.__name__ =='
                    '"ModuleFilterAdderNode")',
                perform=self._perform_add_filter,
             )

        help = \
            Action(
                image=ImageResource('help-action.png',
                                            search_path=self._image_path),
                tooltip="Help on the Mayavi pipeline",
                defined_when='True',
                enabled_when='True',
                perform=open_help_index,
            )

        tvtk_docs = \
            Action(
                image=ImageResource('reader.png',
                                            search_path=self._image_path),
                tooltip="Search the VTK class browser",
                defined_when='True',
                enabled_when='True',
                perform=open_tvtk_docs,
            )

        record = \
            Action(
                image=ImageResource('record.png',
                                     search_path=self._image_path),
                tooltip="Start/Stop script recording",
                style='toggle',
                checked=False,
                defined_when='True',
                enabled_when='engine is not None',
                perform=self._perform_record,
            )

        # Check the record icon if the engine already has a recorder
        # set.
        if self.engine is not None and self.engine.recorder is not None:
            record.checked = True

        return [
            tvtk_docs,
            Separator(), add_scene, add_source, add_module, add_filter,
            Separator(), help, record
        ]
Example #20
0
def mk_scene_icon():
    icon_path = os.path.join(resource_path(), 'images', 'scene.ico')
    return ImageResource(icon_path)
Example #21
0
from enthought.pyface.image_resource \
    import ImageResource

from dock_window \
    import DockWindow

from dock_sizer \
    import DockSizer, DockSection, DockRegion, DockControl, DOCK_RIGHT

#-------------------------------------------------------------------------------
#  Constants:
#-------------------------------------------------------------------------------

# DockWindowShell frame icon:
FrameIcon = ImageResource('shell.ico')

#-------------------------------------------------------------------------------
#  'DockWindowShell' class:
#-------------------------------------------------------------------------------


class DockWindowShell(HasPrivateTraits):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    # The wx.Frame window which is the actual shell:
    control = Instance(wx.Frame)
Example #22
0
class CFFView(HasTraits):
    """ A view displaying the cfile's object tree. """

    # The connectome file we are viewing
    cfile = Instance(CFile, allow_none=True)

    # Path used to search for images
    _image_path = [
        IMAGE_PATH,
    ]

    # The icon of the dialog
    icon = ImageResource('favicon.ico', search_path=_image_path)

    # Nodes on the tree
    nodes = Any

    # TreeEditor
    tree_editor = Instance(TreeEditor)

    # render actions
    #renderactions = List(Action)

    #    childrenlist = Property(List, depends_on = ['cfile'] )
    #
    #    def _get_childrenlist(self):
    #        print "get childrenlist"
    #        return self.cfile.connectome_network

    ###########################################################################
    # `object` interface.
    ###########################################################################
    def __init__(self, **traits):
        super(CFFView, self).__init__(**traits)

    ###########################################################################
    # `HasTraits` interface.
    ###########################################################################
    def default_traits_view(self):
        """ The Connectome File Tree View
        """

        view = View(Item(name='cfile',
                         id='cfile',
                         editor=self.tree_editor,
                         resizable=True,
                         show_label=False),
                    id='cviewer.plugins.cff2.cfile',
                    help=False,
                    resizable=True,
                    scrollable=True,
                    undo=False,
                    revert=False,
                    ok=False,
                    cancel=False,
                    icon=self.icon,
                    title='Connectome File View',
                    handler=CFFViewHandler)

        return view

    def _nodes_default(self):
        """ The default value of the cached nodes list.
        """

        # Now setup the view.
        nodes = [
            CFileTreeNode(
                node_for=[CFile],
                children='children',
                icon_path=IMAGE_PATH,
            ),
            CNetworkTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
            CSurfaceTreeNode(
                children='children',
                icon_path=IMAGE_PATH,
                auto_open=True,
            ),
            CSurfaceDarrayTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
            CDataTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
            CScriptTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
            CVolumeTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
            CTimeseriesTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
            CImagestackTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
            CTrackTreeNode(
                children='',
                icon_path=IMAGE_PATH,
                auto_open=False,
            ),
        ]

        return nodes

    def _tree_editor_default(self):
        return TreeEditor(editable=False,
                          hide_root=False,
                          on_dclick='handler._on_dclick',
                          orientation='vertical',
                          nodes=self.nodes)
Example #23
0
    
    def _get_big_image ( self ):
        size = self.item.size
        if size > 65536:
            return 'red_ball'
            
        return ( None, 'blue_ball' )[ size > 16384 ]
   
#--[Tabular Editor Definition]--------------------------------------------------

tabular_editor = TabularEditor(
    editable   = False,
    selected   = 'file_info',
    adapter    = FileInfoAdapter(),
    operations = [],
    images     = [ ImageResource( 'blue_ball', search_path = search_path ),
                   ImageResource( 'red_ball',  search_path = search_path ) ]
)

#--[PythonBrowser Class]--------------------------------------------------------

class PythonBrowser ( HasPrivateTraits ):

    dir       = Directory
    files     = List( FileInfo )    
    file_info = Instance( FileInfo )
    code      = Code
    
    view = View(
        HSplit(
            Item( 'dir', style = 'custom' ),
Example #24
0
class tcProject(HasTraits):
    c_states = List(tcGeneric)
    p_states = List(tcGeneric)
    processes = List(tcProcess)
    selected = List(tcProcess)
    filtered_processes = List(tcProcess)
    remove_filter = Button(image=ImageResource("clear.png"),
                           width_padding=0,
                           height_padding=0,
                           style='toolbar')
    minimum_time_filter = Enum((0, 1000, 10000, 50000, 100000, 500000, 1000000,
                                5000000, 1000000, 5000000, 10000000, 50000000))
    minimum_events_filter = Enum(
        (0, 2, 4, 8, 10, 20, 40, 100, 1000, 10000, 100000, 1000000))
    plot_redraw = Long()
    filter = Str("")
    filter_invalid = Property(depends_on="filter")
    filename = Str("")
    power_event = CArray
    num_cpu = Property(Int, depends_on='c_states')
    num_process = Property(Int, depends_on='process')
    traits_view = View(
        VGroup(
            HGroup(
                Item(
                    'filter',
                    invalid="filter_invalid",
                    width=1,
                    tooltip=
                    'filter the process list using a regular expression,\nallowing you to quickly find a process'
                ),
                Item('remove_filter',
                     show_label=False,
                     style='custom',
                     tooltip='clear the filter')),
            HGroup(
                Item(
                    'minimum_time_filter',
                    width=1,
                    label='dur',
                    tooltip=
                    'filter the process list with minimum duration process is scheduled'
                ),
                Item(
                    'minimum_events_filter',
                    width=1,
                    label='num',
                    tooltip=
                    'filter the process list with minimum number of events process is generating'
                ),
            )),
        Item('filtered_processes',
             show_label=False,
             height=40,
             editor=process_table_editor))
    first_ts = 0

    def _get_filter_invalid(self):
        try:
            r = re.compile(self.filter)
        except:
            return True
        return False

    def _remove_filter_changed(self):
        self.filter = ""

    def _filter_changed(self):
        try:
            r = re.compile(self.filter)
        except:
            r = None
        filtered_processes = self.processes
        if self.minimum_events_filter:
            filtered_processes = filter(
                lambda p: self.minimum_events_filter < len(p.start_ts),
                filtered_processes)
        if self.minimum_time_filter:
            filtered_processes = filter(
                lambda p: self.minimum_time_filter < p.total_time,
                filtered_processes)
        if r:
            filtered_processes = filter(lambda p: r.search(p.comm),
                                        filtered_processes)
        self.filtered_processes = filtered_processes

    _minimum_time_filter_changed = _filter_changed
    _minimum_events_filter_changed = _filter_changed

    def _processes_changed(self):
        self._filter_changed()

    def _on_show(self):
        for i in self.selected:
            i.show = True
        self.plot_redraw += 1

    def _on_hide(self):
        for i in self.selected:
            i.show = False
        self.plot_redraw += 1

    def _on_select_all(self):
        if self.selected == self.filtered_processes:
            self.selected = []
        else:
            self.selected = self.filtered_processes
        self.plot_redraw += 1

    def _on_invert(self):
        for i in self.filtered_processes:
            i.show = not i.show
        self.plot_redraw += 1

    @cached_property
    def _get_num_cpu(self):
        return len(self.c_states)

    def _get_num_process(self):
        return len(self.processes)

    def process_list_selected(self, selection):
        print selection
######### stats part ##########

    def process_stats(self, start, end):
        fact = 100. / (end - start)
        for tc in self.processes:
            starts, ends, types = tc.get_partial_tables(start, end)
            inds = np.where(types == colors.get_color_id("running"))
            tot = sum(ends[inds] - starts[inds])
            tc.selection_time = int(tot)
            tc.selection_pc = tot * fact

    def get_selection_text(self, start, end):
        low_line = -1
        high_line = -1
        low_i = searchsorted(self.timestamps, start)
        high_i = searchsorted(self.timestamps, end)
        low_line = self.linenumbers[low_i]
        high_line = self.linenumbers[high_i]
        return self.get_partial_text(self.filename, low_line, high_line)
######### generic parsing part ##########

    def generic_find_process(self,
                             pid,
                             comm,
                             ptype,
                             same_pid_match_timestamp=0):
        if self.tmp_process.has_key((pid, comm)):
            return self.tmp_process[(pid, comm)]
        # else try to find if there has been a process with same pid recently, and different name. Only for user_process because other traces set pid to 0
        if same_pid_match_timestamp != 0 and ptype == "user_process":
            for k, p in self.tmp_process.items():
                if k[0] == pid and p['type'] == "user_process":
                    if len(
                            p['start_ts']
                    ) > 0 and p['start_ts'][-1] > same_pid_match_timestamp:
                        p['comm'] = comm
                        self.tmp_process[(pid, comm)] = p
                        del self.tmp_process[k]
                        return p
        tmp = {
            'type': ptype,
            'comm': comm,
            'pid': pid,
            'start_ts': [],
            'end_ts': [],
            'types': [],
            'cpus': [],
            'comments': []
        }
        if not (pid == 0 and ptype == "user_process"):
            self.tmp_process[(pid, comm)] = tmp
        return tmp

    def generic_process_start(self, process, event, build_p_stack=True):
        if process['type'] == "user_process" and process['pid'] == 0:
            return  # ignore swapper event
        if len(process['start_ts']) > len(process['end_ts']):
            process['end_ts'].append(event.timestamp)
        if self.first_ts == 0:
            self.first_ts = event.timestamp
        self.cur_process_by_pid[process['pid']] = process
        if build_p_stack:
            p_stack = self.cur_process[event.common_cpu]
            if p_stack:
                p = p_stack[-1]
                if len(p['start_ts']) > len(p['end_ts']):
                    p['end_ts'].append(event.timestamp)
                # mark old process to wait for cpu
                p['start_ts'].append(int(event.timestamp))
                p['types'].append(colors.get_color_id("waiting_for_cpu"))
                p['cpus'].append(event.common_cpu)
                p_stack.append(process)
            else:
                self.cur_process[event.common_cpu] = [process]
        # mark process to use cpu
        process['start_ts'].append(event.timestamp)
        process['types'].append(colors.get_color_id("running"))
        process['cpus'].append(event.common_cpu)

    def generic_process_end(self, process, event, build_p_stack=True):
        if process['type'] == "user_process" and process['pid'] == 0:
            return  # ignore swapper event
        if len(process['start_ts']) > len(process['end_ts']):
            process['end_ts'].append(event.timestamp)
        if build_p_stack:
            p_stack = self.cur_process[event.common_cpu]
            if p_stack:
                p = p_stack.pop()
                if p['pid'] != process['pid']:
                    print "warning: process premption stack following failure on CPU", event.common_cpu, p[
                        'comm'], p['pid'], process['comm'], process[
                            'pid'], map(
                                lambda a: "%s:%d" % (a['comm'], a['pid']),
                                p_stack), event.linenumber
                    p_stack = []

                if p_stack:
                    p = p_stack[-1]
                    if len(p['start_ts']) > len(p['end_ts']):
                        p['end_ts'].append(event.timestamp)
                    # mark old process to run on cpu
                    p['start_ts'].append(event.timestamp)
                    p['types'].append(colors.get_color_id("running"))
                    p['cpus'].append(event.common_cpu)

    def generic_process_single_event(self, process, event):
        if len(process['start_ts']) > len(process['end_ts']):
            process['end_ts'].append(event.timestamp)
        # mark process to use cpu
        process['start_ts'].append(event.timestamp)
        process['types'].append(colors.get_color_id("running"))
        process['cpus'].append(event.common_cpu)
        process['end_ts'].append(event.timestamp)

    def generic_add_wake(self, caller, callee, event):
        self.wake_events.append(
            ((caller['comm'], caller['pid']), (callee['comm'], callee['pid']),
             event.timestamp))

    def do_function_default(self, event):
        process = self.generic_find_process(
            0, "kernel function:%s" % (event.callee), "function")
        self.generic_process_single_event(process, event)

    def do_event_default(self, event):
        event.name = event.event.split(":")[0]
        process = self.generic_find_process(0, "event:%s" % (event.name),
                                            "event")
        self.generic_process_single_event(process, event)
        process['comments'].append(event.event)

    def start_parsing(self, get_partial_text):
        # we build our data into python data formats, who are resizeable
        # once everything is parsed, we will transform it into numpy array, for fast access
        self.tmp_c_states = []
        self.tmp_p_states = []
        self.tmp_process = {}
        self.timestamps = []
        self.linenumbers = []
        self.cur_process_by_pid = {}
        self.wake_events = []
        self.cur_process = [None] * 20
        self.last_irq = {}
        self.last_spi = []
        self.missed_power_end = 0
        self.get_partial_text = get_partial_text
        self.methods = {}
        import plugin
        colors.parse_colors(plugin.get_plugins_additional_colors())
        plugin.get_plugins_methods(self.methods)
        self.process_types = {
            "function": (tcProcess, plugin.MISC_TRACES_CLASS),
            "event": (tcProcess, plugin.MISC_TRACES_CLASS)
        }
        self.process_types.update(
            plugin.get_plugins_additional_process_types())

    def finish_parsing(self):
        #put generated data in unresizable numpy format
        c_states = []
        i = 0
        for tc in self.tmp_c_states:
            t = tcIdleState(name='cpu%d' % (i))
            while len(tc['start_ts']) > len(tc['end_ts']):
                tc['end_ts'].append(tc['start_ts'][-1])
            t.start_ts = numpy.array(tc['start_ts'])
            t.end_ts = numpy.array(tc['end_ts'])
            t.types = numpy.array(tc['types'])
            c_states.append(t)
            i += 1
        self.c_states = c_states
        i = 0
        p_states = []
        for tc in self.tmp_p_states:
            t = tcFrequencyState(name='cpu%d' % (i))
            t.start_ts = numpy.array(tc['start_ts'])
            t.end_ts = numpy.array(tc['end_ts'])
            t.types = numpy.array(tc['types'])
            i += 1
            p_states.append(t)
        self.wake_events = numpy.array(self.wake_events,
                                       dtype=[('waker', tuple),
                                              ('wakee', tuple),
                                              ('time', 'uint64')])
        self.p_states = p_states
        processes = []
        last_ts = 0
        for pid, comm in self.tmp_process:
            tc = self.tmp_process[pid, comm]
            if len(tc['end_ts']) > 0 and last_ts < tc['end_ts'][-1]:
                last_ts = tc['end_ts'][-1]
        if len(self.tmp_process) > 0:
            progress = ProgressDialog(title="precomputing data",
                                      message="precomputing overview data...",
                                      max=len(self.tmp_process),
                                      show_time=False,
                                      can_cancel=False)
            progress.open()
        i = 0
        for pid, comm in self.tmp_process:
            tc = self.tmp_process[pid, comm]
            if self.process_types.has_key(tc['type']):
                klass, order = self.process_types[tc['type']]
                t = klass(pid=pid, comm=tc['comm'], project=self)
            else:
                t = tcProcess(pid=pid, comm=comm, project=self)
            while len(tc['start_ts']) > len(tc['end_ts']):
                tc['end_ts'].append(last_ts)
            t.start_ts = numpy.array(tc['start_ts'])
            t.end_ts = numpy.array(tc['end_ts'])
            t.types = numpy.array(tc['types'])
            t.cpus = numpy.array(tc['cpus'])
            t.comments = tc['comments']  #numpy.array(tc['comments'])
            t.process_type = tc["type"]
            # precompute 16 levels of overview cache
            t.get_overview_ts(1 << 16)
            processes.append(t)
            progress.update(i)
            i += 1
        if len(self.tmp_process) > 0:
            progress.close()
            self.tmp_process = []

        def cmp_process(x, y):
            # sort process by type, pid, comm
            def type_index(t):
                try:
                    return self.process_types[t][1]
                except ValueError:
                    return len(order) + 1

            c = cmp(type_index(x.process_type), type_index(y.process_type))
            if c != 0:
                return c
            c = cmp(x.pid, y.pid)
            if c != 0:
                return c
            c = cmp(x.comm, y.comm)
            return c

        processes.sort(cmp_process)
        self.processes = processes
        self.p_states = p_states
        self.tmp_c_states = []
        self.tmp_p_states = []
        self.tmp_process = {}

    def ensure_cpu_allocated(self, cpu):
        # ensure we have enough per_cpu p/c_states timecharts
        while len(self.tmp_c_states) <= cpu:
            self.tmp_c_states.append({
                'start_ts': [],
                'end_ts': [],
                'types': []
            })
        while len(self.tmp_p_states) <= cpu:
            self.tmp_p_states.append({
                'start_ts': [],
                'end_ts': [],
                'types': []
            })

    def run_callbacks(self, callback, event):
        if callback in self.methods:
            for m in self.methods[callback]:
                try:
                    m(self, event)
                except AttributeError:
                    if not hasattr(m, "num_exc"):
                        m.num_exc = 0
                    m.num_exc += 1
                    if m.num_exc < 10:
                        print "bug in ", m, "still continue.."
                        traceback.print_exc()
                        print event
                    if m.num_exc == 10:
                        print m, "is too buggy, disabling, please report bug!"
                        self.methods[callback].remove(m)
                        if len(self.methods[callback]) == 0:
                            del self.methods[callback]
            return True
        return False

    def handle_trace_event(self, event):
        self.linenumbers.append(event.linenumber)
        self.timestamps.append(event.timestamp)
        if event.event == 'function':
            callback = "do_function_" + event.callee
            self.run_callbacks("do_all_functions", event)
        else:
            callback = "do_event_" + event.event
            self.run_callbacks("do_all_events", event)

        if not self.run_callbacks(callback, event):
            if event.event == 'function':
                self.do_function_default(event)
            else:
                self.do_event_default(event)
Example #25
0
from enthought.traits.ui.api \
    import *

from enthought.traits.ui.menu \
    import *

from enthought.pyface.image_resource \
    import ImageResource

from enthought.developer.tools.ui_debugger import UIDebugger

#-------------------------------------------------------------------------------
#  Constants:
#-------------------------------------------------------------------------------

image1 = ImageResource('folder')
image2 = ImageResource('gear')

#-------------------------------------------------------------------------------
#  'TestDock' class:
#-------------------------------------------------------------------------------


class TestDock(HasPrivateTraits):

    #---------------------------------------------------------------------------
    #  Trait definitions:
    #---------------------------------------------------------------------------

    button1 = Button
    button2 = Button
Example #26
0
class OpenCFile(Action):
    """ An action that opens a data file depending on the supported
    extensions.  """

    name = "Open CFF File"
    description = "Open the File Dialog where you can select a .cff or meta.cml file"
    tooltip = "Open a CFF file"
    path = Str("MenuBar/File/LoadDataMenu")
    image = ImageResource("cff-open.png", search_path=[IMAGE_PATH])

    # Is the action enabled?
    enabled = Bool(True)

    # Is the action visible?
    visible = Bool(True)

    ###########################################################################
    # 'Action' interface.
    ###########################################################################

    def perform(self, event, cfile=None):
        """ Performs the action. """

        logger.info('Performing open connectome file action')

        # helper variable to use this function not only in the menubar
        exec_as_funct = True

        if cfile is None:
            # get the instance of the current CFile
            # with the help of the Service Registry
            cfile = self.window.application.get_service(
                'cviewer.plugins.cff2.cfile.CFile')
            exec_as_funct = False

        wildcard = "Connectome Markup File v2.0 (meta.cml)|meta.cml|" \
                    "Connectome File Format v2.0 (*.cff)|*.cff|" \
                    "All files (*.*)|*.*"
        dlg = FileDialog(wildcard=wildcard,title="Choose a Connectome File",\
                         resizeable=False, \
                         default_directory=preference_manager.cviewerui.cffpath,)

        if dlg.open() == OK:

            if not os.path.isfile(dlg.path):
                logger.error("File '%s' does not exist!" % dlg.path)
                return

            # if file exists and has .cff ending
            if os.path.exists(
                    dlg.paths[0]) and (dlg.paths[0]).endswith('.cff'):

                # close the cfile if one is currently loaded
                cfile.close_cfile()

                # load cfile data
                cfile.load_cfile(dlg.paths[0])

                self.window.status_bar_manager.message = ''
            elif os.path.exists(
                    dlg.paths[0]) and (dlg.paths[0]).endswith('meta.cml'):
                cfile.close_cfile()
                cfile.load_cfile(dlg.paths[0], ismetacml=True)
            else:
                logger.info('Could not load file: ' + dlg.paths)
Example #27
0
from enthought.traits.ui.table_filter import \
    EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate, RuleTableFilter

from enthought.naming.unique_name import make_unique_name

from enthought.pyface.image_resource import ImageResource
from enthought.enable.component_editor import ComponentEditor

import godot

#------------------------------------------------------------------------------
#  Images:
#------------------------------------------------------------------------------

frame_icon = ImageResource("dot")

#------------------------------------------------------------------------------
#  Node factory function:
#------------------------------------------------------------------------------


def node_factory(**row_factory_kw):
    """ Give new nodes a unique ID. """

    if "__table_editor__" in row_factory_kw:
        graph = row_factory_kw["__table_editor__"].object
        ID = make_unique_name("n", [node.ID for node in graph.nodes])
        del row_factory_kw["__table_editor__"]
        return godot.node.Node(ID)
    else: