Esempio n. 1
0
 class UserInterface(object):
     def __init__(self):
         self.o = o
     show = make_invoke_method("show")
     isVisible = J.make_method("isVisible", "()Z")
     getApplicationFrame = J.make_method(
         "getApplicationFrame", "()Lorg/scijava/ui/ApplicationFrame;")
Esempio n. 2
0
class GenericJavaObj:
    __str__ = javabridge.make_method("toString", "()Ljava/lang/String;")
    get_class = javabridge.make_method("getClass", "()Ljava/lang/Class;")
    __repl__ = javabridge.make_method("toString", "()Ljava/lang/String;")

    def __init__(self, jobj):
        self.o = jobj
Esempio n. 3
0
    class UIService(object):
        def __init__(self):
            self.o = ui_service

        createUI = make_invoke_method("showUI", doc='''Create the ImageJ UI''')
        isVisible = J.make_method("isVisible", "()Z")
        getDefaultUI = J.make_method("getDefaultUI",
                                     "()Lorg/scijava/ui/UserInterface;",
                                     fn_post_process=wrap_user_interface)
        getUI = J.make_method(
            "getUI",
            "(Ljava/lang/String;)Lorg/scijava/ui/UserInterface;",
            fn_post_process=wrap_user_interface)
Esempio n. 4
0
            class OMETiffWriter(IFormatWriter):

                new_fn = javabridge.make_new("loci/formats/out/OMETiffWriter",
                                             "()V")

                def __init__(self):

                    self.new_fn()

                setId = javabridge.make_method("setId",
                                               "(Ljava/lang/String;)V",
                                               "Sets the current file name.")
                saveBytesXYWH = javabridge.make_method(
                    "saveBytes", "(I[BIIII)V",
                    "Saves the given byte array to the current file")
                close = javabridge.make_method(
                    "close", "()V",
                    "Closes currently open file(s) and frees allocated memory."
                )
                setTileSizeX = javabridge.make_method(
                    "setTileSizeX", "(I)I", "Set tile size width in pixels.")
                setTileSizeY = javabridge.make_method(
                    "setTileSizeY", "(I)I", "Set tile size height in pixels.")
                getTileSizeX = javabridge.make_method(
                    "getTileSizeX", "()I", "Set tile size width in pixels.")
                getTileSizeY = javabridge.make_method(
                    "getTileSizeY", "()I", "Set tile size height in pixels.")
                setBigTiff = javabridge.make_method("setBigTiff", "(Z)V",
                                                    "Set the BigTiff flag.")
Esempio n. 5
0
    class Dataset(object):
        def __init__(self, o=dataset):
            self.o = o

        getImgPlus = J.make_method("getImgPlus",
                                   "()Lnet/imglib2/meta/ImgPlus;")
        setImgPlus = J.make_method("setImgPlus",
                                   "(Lnet/imglib2/meta/ImgPlus;)V")
        getAxes = J.make_method("getAxes", "()[Lnet/imglib2/img/AxisType;")
        getType = J.make_method("getType",
                                "()Lnet/imglib2/type/numeric/RealType;")
        isSigned = J.make_method("isSigned", "()Z")
        isInteger = J.make_method("isInteger", "()Z")
        getName = J.make_method("getName", "()Ljava/lang/String;")
        setName = J.make_method("setName", "(Ljava/lang/String;)V")

        def get_pixel_data(self, axes=None):
            imgplus = self.getImgPlus()
            pixel_data = get_pixel_data(imgplus)
            script = """
            var result = java.util.ArrayList();
            for (i=0;i<imgplus.numDimensions();i++) 
                result.add(imgplus.axis(i).type());
            result"""
            inv_axes = J.run_script(script, dict(imgplus=imgplus))
            inv_axes = list(J.iterate_collection(inv_axes))
            transpose = calculate_transpose(inv_axes, axes)
            return pixel_data.transpose(transpose)
Esempio n. 6
0
    class DisplayService(object):
        def __init__(self):
            self.o = o

        def createDisplay(self, name, dataset):
            """Create a display that contains the given dataset
            :param dataset:
            :param name:
            """
            return wrap_display(
                J.call(
                    o, "createDisplay",
                    "(Ljava/lang/String;Ljava/lang/Object;)Lorg/scijava/display/Display;",
                    name, dataset))

        def getActiveDisplay(self, klass=None):
            """Get the first display, optionally of the given type from the list

            klass - if not None, return the first display of this type,
                    otherwise return the first display
                    :param klass:
            """
            if klass is None:
                return wrap_display(
                    J.call(self.o, "getActiveDisplay",
                           "()Lorg/scijava/display/Display;"))
            else:
                return wrap_display(
                    J.call(self.o, "getActiveDisplay",
                           "(Ljava/lang/Class;)Lorg/scijava/display/Display;",
                           klass))

        def getActiveImageDisplay(self):
            """Get the active imagej.data.display.ImageDisplay"""
            return wrap_display(
                J.call(self.o, "getActiveDisplay",
                       "()Lorg/scijava/display/Display;",
                       J.class_for_name("net.imagej.display.ImageDisplay")))

        setActiveDisplay = J.make_method("setActiveDisplay",
                                         "(Lorg/scijava/display/Display;)V")
        getDisplays = J.make_method("getDisplays",
                                    "()Ljava/util/List;",
                                    fn_post_process=lambda x: map(
                                        wrap_display, J.iterate_collection(x)))
        getDisplay = J.make_method(
            "getDisplay",
            "(Ljava/lang/String;)Lorg/scijava/display/Display;",
            fn_post_process=wrap_display)
        isUniqueName = J.make_method("isUniqueName", "(Ljava/lang/String;)Z")
Esempio n. 7
0
    class Interval(object):
        def __init__(self, o=interval):
            self.o = o

        numDimensions = J.make_method("numDimensions", "()I")
        min1D = J.make_method(
            "min", "(I)J",
            "Retrieve the minimum coordinate for a single dimension")
        max1D = J.make_method(
            "max", "(I)J",
            "Retrieve the maximum coordinate for a single dimension")
        dimension = J.make_method(
            "dimension", "(I)J",
            "Retrieve the number of pixels in the given dimension")

        def minND(self):
            return [self.min1D(i) for i in range(self.numDimensions())]

        def maxND(self):
            return [self.max1D(i) for i in range(self.numDimensions())]

        def dimensions(self):
            return [self.dimension(i) for i in range(self.numDimensions())]

        #
        # # # # # # # # # # # # # # #
        #
        # Calibrated interval methods
        #
        getAxes = J.make_method("getAxes", "()L[net.imglib2.meta.AxisType;")

        #
        # minimum and maximum by axis
        #
        def minAx(self, axis):
            """Get the minimum of the interval along the given axis
            :param axis:
            """
            axes = self.getAxes()
            idx = axes.index(axis)
            return self.min1D(idx)

        def maxAx(self, axis):
            """Get the maximum of the interval along the given axis
            :param axis:
            """
            axes = self.getAxes()
            idx = axes.index(axis)
            return self.max1D(idx)
Esempio n. 8
0
 class OverlayService(object):
     def __init__(self, o=o):
         self.o = o
         
     getOverlays = J.make_method("getOverlays", "()Ljava/util/List;",
                                 fn_post_process=J.get_collection_wrapper)
     getDisplayOverlays = J.make_method(
         "getOverlays",
         "(Lnet/imagej/display/ImageDisplay;)Ljava/util/List;",
         fn_post_process=J.get_collection_wrapper)
     addOverlays = make_invoke_method("addOverlays")
     removeOverlay = make_invoke_method("removeOverlay")
     getSelectionBounds = J.make_method(
         "getSelectionBounds",
         "(Lnet/imagej/display/ImageDisplay;)Lorg/scijava/util/RealRect;")
Esempio n. 9
0
    class CommandService(object):
        def __init__(self):
            self.o = command_service

        run = make_invoke_method(
            "run",
            returns_value=True,
            doc="""Run the command associated with a ModuleInfo
            
            Runs the command with pre and post processing plugins.
            
            module_info - the ModuleInfo that defines a command
            
            process - True to run pre and post processing on command, False
                      to execute as-is.
            
            inputs - a java.util.map of parameter name to value
            
            returns a java.util.concurrent.Future that can be redeemed
            for the module after the module has been run.
            """,
            fn_post_process=J.get_future_wrapper)
        getCommandS = J.make_method(
            "getCommand",
            "(Ljava/lang/String;)Lorg/scijava/command/CommandInfo;",
            doc="""Get command by class name
            
            className - dotted class name, e.g. imagej.core.commands.app.AboutImageJ
            """,
            fn_post_process=wrap_module_info)
Esempio n. 10
0
        class MyInteger:
            new_fn = javabridge.make_new("java/lang/Integer", '(I)V')

            def __init__(self, value):
                self.new_fn(value)

            intValue = javabridge.make_method("intValue", '()I')
Esempio n. 11
0
 class Module(object):
     def __init__(self, o = module):
         self.o = o
         
     getInfo = J.make_method("getInfo", "()Limagej/module/ModuleInfo;")
     getInput = J.make_method("getInput", "(Ljava/lang/String;)Ljava/lang/Object;")
     getOutput = J.make_method("getOutput", "(Ljava/lang/String;)Ljava/lang/Object;")
     setInput = J.make_method("setInput", "(Ljava/lang/String;Ljava/lang/Object;)V")
     setOutput = J.make_method("setOutput", "(Ljava/lang/String;Ljava/lang/Object;)V")
     isResolved = J.make_method("isResolved", "(Ljava/lang/String;)Z")
     setResolved = J.make_method("setResolved", "(Ljava/lang/String;Z)V")
     setContext = J.make_method("setContext", "(Lorg/scijava/Context;)V")
     initialize = J.make_method("initialize", "()V")
Esempio n. 12
0
    class ImageReader(IFormatReader):
        new_fn = jutil.make_new(class_name, '(Lloci/formats/ClassList;)V')

        def __init__(self):
            self.new_fn(class_list.o)

        getFormat = jutil.make_method(
            'getFormat', '()Ljava/lang/String;',
            'Get a string describing the format of this file')
        getReader = jutil.make_method('getReader',
                                      '()Lloci/formats/IFormatReader;')

        def allowOpenToCheckType(self, allow):
            '''Allow the "isThisType" function to open files

            For the cluster, you want to tell potential file formats
            not to open the image file to test if it's their format.
            '''
            if not hasattr(self, "allowOpenToCheckType_method"):
                self.allowOpenToCheckType_method = None
                class_wrapper = jutil.get_class_wrapper(self.o)
                methods = class_wrapper.getMethods()
                for method in jutil.get_env().get_object_array_elements(
                        methods):
                    m = jutil.get_method_wrapper(method)
                    if m.getName() in ('allowOpenToCheckType',
                                       'setAllowOpenFiles'):
                        self.allowOpenToCheckType_method = m
            if self.allowOpenToCheckType_method is not None:
                object_class = env.find_class('java/lang/Object')
                jexception = jutil.get_env().exception_occurred()
                if jexception is not None:
                    raise jutil.JavaException(jexception)

                boolean_value = jutil.make_instance('java/lang/Boolean',
                                                    '(Z)V', allow)
                args = jutil.get_env().make_object_array(1, object_class)
                jexception = jutil.get_env().exception_occurred()
                if jexception is not None:
                    raise jutil.JavaException(jexception)
                jutil.get_env().set_object_array_element(
                    args, 0, boolean_value)
                jexception = jutil.get_env().exception_occurred()
                if jexception is not None:
                    raise jutil.JavaException(jexception)
                self.allowOpenToCheckType_method.invoke(self.o, args)
Esempio n. 13
0
        def __init__(self):
            self.new_fn = jutil.make_new(self.class_name, '()V')
            self.setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
                                           'Sets the current file name.')
            self.close = jutil.make_method(
                'close','()V',
                'Closes currently open file(s) and frees allocated memory.')
            self.saveBytesIFD = jutil.make_method(
                'saveBytes', '(I[BLloci/formats/tiff/IFD;)V',
                '''save a byte array to an image channel

                index - image index
                bytes - byte array to save
                ifd - a loci.formats.tiff.IFD instance that gives all of the
                IFD values associated with the channel''')

            self.new_fn()
Esempio n. 14
0
 class ObjectService(object):
     def __init__(self):
         self.o = o
     
     getObjects = J.make_method(
         "getObjects", "(Ljava/lang/Class;)Ljava/util/List;",
         doc= """Get all objects of the given class""",
         fn_post_process=J.get_collection_wrapper)
Esempio n. 15
0
        def __init__(self):
            self.new_fn = jutil.make_new(self.class_name, '()V')
            self.setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
                                           'Sets the current file name.')
            self.close = jutil.make_method(
                'close', '()V',
                'Closes currently open file(s) and frees allocated memory.')
            self.saveBytesIFD = jutil.make_method(
                'saveBytes', '(I[BLloci/formats/tiff/IFD;)V',
                '''save a byte array to an image channel

                index - image index
                bytes - byte array to save
                ifd - a loci.formats.tiff.IFD instance that gives all of the
                IFD values associated with the channel''')

            self.new_fn()
Esempio n. 16
0
                class JavaEncoder():
                    new_fn = javabridge.make_new("java/lang/String",
                                                 "([BLjava/lang/String;)V")

                    def __init__(self, i, s):
                        self.new_fn(i, s)

                    toString = javabridge.make_method(
                        "toString", "()Ljava/lang/String;",
                        "Retrieve the integer value")
    class ReaderWrapper(IFormatReader):
        __doc__ = '''A wrapper for %s

        See http://hudson.openmicroscopy.org.uk/job/LOCI/javadoc/loci/formats/ImageReader.html
        '''%class_name
        new_fn = jutil.make_new(class_name, '(Lloci/formats/IFormatReader;)V')
        def __init__(self, rdr):
            self.new_fn(rdr)

        setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
                                  'Set the name of the data file')
Esempio n. 18
0
    class ModuleInfo(object):
        def __init__(self):
            self.o = instance

        getInput = J.make_method(
            "getInput", 
            "(Ljava/lang/String;)Lorg/scijava/module/ModuleItem;", 
            doc = "Gets the input item with the given name.",
            fn_post_process=wrap_module_item)

        getOutput = J.make_method(
            "getOutput", 
            "(Ljava/lang/String;)Lorg/scijava/module/ModuleItem;",
            doc = "Gets the output item with the given name.",
            fn_post_process=wrap_module_item)

        getInputs = J.make_method(
            "inputs", "()Ljava/lang/Iterable;",
            """Get the module info's input module items""",
            fn_post_process=lambda iterator:
            map(wrap_module_item, J.iterate_collection(iterator)))
            
        getOutputs = J.make_method(
            "outputs", "()Ljava/lang/Iterable;",
            """Get the module info's output module items""",
            fn_post_process=lambda iterator:
            map(wrap_module_item, J.iterate_collection(iterator)))
        
        getTitle = J.make_method(
            "getTitle",
            "()Ljava/lang/String;")
        createModule = J.make_method(
            "createModule",
            "()Lorg/scijava/module/Module;",
            fn_post_process=wrap_module)
        getMenuPath = J.make_method(
            "getMenuPath", "()Lorg/scijava/MenuPath;")
        getMenuRoot = J.make_method(
            "getMenuRoot", "()Ljava/lang/String;")
        getName = J.make_method("getName", "()Ljava/lang/String;")
        getClassName = J.make_method("getClassName", "()Ljava/lang/String;")        
Esempio n. 19
0
 def _init_writer(self):
     # If file already exists, delete it before initializing again.
     # If this is not done, then the file will be appended.
     if os.path.exists(self._file_path):
         os.remove(self._file_path)
     
     w_klass = make_ome_tiff_writer_class()
     w_klass.setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
                                     'Sets the current file name.')
     w_klass.saveBytesXYWH = jutil.make_method('saveBytes', '(I[BIIII)V',
                                             'Saves the given byte array to the current file')
     w_klass.close = jutil.make_method('close','()V',
                                     'Closes currently open file(s) and frees allocated memory.')
     w_klass.setTileSizeX = jutil.make_method('setTileSizeX','(I)I',
                                             'Set tile size width in pixels.')
     w_klass.setTileSizeY = jutil.make_method('setTileSizeY','(I)I',
                                             'Set tile size height in pixels.')
     w_klass.getTileSizeX = jutil.make_method('getTileSizeX','()I',
                                             'Set tile size width in pixels.')
     w_klass.getTileSizeY = jutil.make_method('getTileSizeY','()I',
                                             'Set tile size height in pixels.')
     w_klass.setBigTiff = jutil.make_method('setBigTiff','(Z)V',
                                            'Set the BigTiff flag.')
     writer = w_klass()
     
     # Always set bigtiff flag. There have been some instances where bioformats does not
     # properly write images that are less than 2^32 if bigtiff is not set. So, just always
     # set it since it doesn't drastically alter file size.
     writer.setBigTiff(True)
     
     script = """
     importClass(Packages.loci.formats.services.OMEXMLService,
                 Packages.loci.common.services.ServiceFactory);
     var service = new ServiceFactory().getInstance(OMEXMLService);
     var metadata = service.createOMEXMLMetadata(xml);
     var writer = writer
     writer.setMetadataRetrieve(metadata);
     """
     jutil.run_script(script,
                      dict(path=self._file_path,
                           xml=self._metadata.to_xml().replace('<ome:','<').replace('</ome:','</'),
                           writer=writer))
     writer.setId(self._file_path)
     writer.setInterleaved(False)
     writer.setCompression("LZW")
     x = writer.setTileSizeX(self._TILE_SIZE)
     y = writer.setTileSizeY(self._TILE_SIZE)
     
     self._pix['chunk'] = self._MAX_BYTES/(self._pix['spp']*self._pix['bpp'])      # number of pixels to load at a time
         
     self.__writer = writer
Esempio n. 20
0
    class WriterWrapper(IFormatWriter):
        __doc__ = '''A wrapper for %s

        See http://hudson.openmicroscopy.org.uk/job/LOCI/javadoc/loci/formats/ImageWriter.html
        ''' % class_name
        new_fn = jutil.make_new(class_name, '(Lloci/formats/IFormatWriter;)V')

        def __init__(self, writer):
            self.new_fn(writer)

        setId = jutil.make_method('setId', '(Ljava/lang/String;)V',
                                  'Sets the current file name.')
Esempio n. 21
0
    class ClassList(object):
        remove_class = jutil.make_method(
            'removeClass', '(Ljava/lang/Class;)V',
            'Remove the given class from the class list')
        add_class = jutil.make_method(
            'addClass', '(Ljava/lang/Class;)V',
            'Add the given class to the back of the class list')
        get_classes = jutil.make_method(
            'getClasses', '()[Ljava/lang/Class;',
            'Get the classes in the list as an array')

        def __init__(self):
            env = jutil.get_env()
            class_name = 'loci/formats/ImageReader'
            klass = env.find_class(class_name)
            base_klass = env.find_class('loci/formats/IFormatReader')
            self.o = jutil.make_instance(
                "loci/formats/ClassList",
                "(Ljava/lang/String;"
                "Ljava/lang/Class;"  # base
                "Ljava/lang/Class;)V",  # location in jar
                "readers.txt",
                base_klass,
                klass)
            problem_classes = [
                # BDReader will read all .tif files in an experiment if it's
                # called to load a .tif.
                #
                'loci.formats.in.BDReader',
                #
                # MRCReader will read .stk files which should be read
                # by MetamorphReader
                #
                'loci.formats.in.MRCReader'
            ]
            for problem_class in problem_classes:
                # Move to back
                klass = jutil.class_for_name(problem_class)
                self.remove_class(klass)
                self.add_class(klass)
Esempio n. 22
0
 class ScriptService(object):
     def __init__(self, o=o):
         self.o = o
     
     getPluginService = J.make_method(
         "getPluginService", "()Lorg/scijava/plugin/PluginService;")
     getIndex = J.make_method(
         "getIndex", "()Lorg/scijava/script/ScriptLanguageIndex;")
     getLanguages = J.make_method(
         "getLanguages", "()Ljava/util/List;",
         doc = "Return the script engine factories supported by this service",
         fn_post_process = lambda jlangs: [
             wrap_script_engine_factory(o) 
             for o in J.iterate_collection(jlangs)])
     getByFileExtension = J.make_method(
         "getLanguageByExtension", 
         "(Ljava/lang/String;)Lorg/scijava/script/ScriptLanguage;",
         fn_post_process=wrap_script_engine_factory)
     getByName = J.make_method(
         "getLanguageByName", 
         "(Ljava/lang/String;)Lorg/scijava/script/ScriptLanguage;",
         fn_post_process=wrap_script_engine_factory)
Esempio n. 23
0
    class DatasetService(object):
        def __init__(self, o=o):
            self.o = o
            
        getAllDatasets = J.make_method(
            "getDatasets", "()Ljava/util/List;",
            doc = "Get all dataset objects in the context")
        getDatasets = J.make_method(
            "getDatasets", 
            "(Lnet/imagej/display/ImageDisplay)Ljava/util/List;",
            doc = """Get the datasets linked to a particular image display""")
        create1 = J.make_method(
            "create",
            "([JLjava/lang/String;[Lnet/imglib2/meta/AxisType;IZZ)"
            "Lnet/imagej/Dataset;",
            doc = """Create a dataset with a given bitdepth
            
            dims - # of dimensions
            
            name - name of dataset
            
            axes - the dataset's axis labels
            
            bitsPerPixel - dataset's bit depth / precision
            
            signed - whether the native type is signed or unsigned
            
            floating - whether the native type is floating or integer""",
            fn_post_process=wrap_dataset)
        create2 = J.make_method(
            "create",
            "(Lnet/imglib2/type/numeric/RealType;[JLjava/lang/String;[Lnet/imglib2/meta/AxisType;)"
            "Lnet/imagej/Dataset;",
            doc = """Create a dataset based on an IMGLIB type
            
            type - The type of the dataset.
	    dims - The dataset's dimensional extents.
            name - The dataset's name.
            axes - The dataset's dimensional axis labels.""",
            fn_post_process=wrap_dataset)
        create3 = J.make_method(
            "create",
            "(Lnet/imglib2/img/ImgFactory;"
            "Lnet/imglib2/type/numeric/RealType;"
            "[JLjava/lang/String;[Lnet/imglib2/meta/AxisType)"
            "Lnet/imagej/Dataset;",
            doc = """Create a dataset from an IMGLIB image factory
            
            factory - The ImgFactory to use to create the data.
            type - The type of the dataset.
            dims - The dataset's dimensional extents.
            name - The dataset's name.
            axes - The dataset's dimensional axis labels.""",
            fn_post_process=wrap_dataset)
        create4 = J.make_method(
            "create",
            "Lnet/imglib2/img/ImgPlus;",
            doc = """Create a dataset wrapped around an ImgPlus""",
            fn_post_process=wrap_dataset)
Esempio n. 24
0
    class Context(object):
        def __init__(self):
            if service_classes is None:
                classes = None
                ctxt_fn = J.run_script("""new java.util.concurrent.Callable() {
                        call: function() {
                            return new Packages.net.imagej.ImageJ(false);
                        }
                    }""")
            else:
                classes = [
                    J.class_for_name(x)
                    for x in service_classes or REQUIRED_SERVICES
                ]
                classes = J.make_list(classes)
                ctxt_fn = J.run_script(
                    """new java.util.concurrent.Callable() {
                        call: function() {
                            return new Packages.net.imagej.ImageJ(classes);
                        }
                    }""", dict(classes=classes.o))

            self.o = J.execute_future_in_main_thread(
                J.make_future_task(ctxt_fn))

        def getService(self, class_name):
            '''Get a service with the given class name
            
            class_name - class name in dotted form
            
            returns the class or None if no implementor loaded.
            '''
            klass = J.class_for_name(class_name)
            return J.call(self.o, 'get',
                          '(Ljava/lang/Class;)Lorg/scijava/service/Service;',
                          klass)

        getContext = J.make_method("getContext", "()Lorg/scijava/Context;")
        getVersion = J.make_method("getVersion", "()Ljava/lang/String;")
Esempio n. 25
0
 class DataView(object):
     def __init__(self, o=view):
         self.o = o
     isCompatible = J.make_method("isCompatible", "(Lnet/imagej/Data;)Z")
     initialize = J.make_method("initialize", "(Lnet/imagej/Data;)V")
     getData = J.make_method("getData", "()Lnet/imagej/Data;")
     getPlanePosition = J.make_method(
         "getPlanePosition", "()Lnet/imagej/Position;")
     setSelected = J.make_method("setSelected", "(Z)V")
     isSelected = J.make_method("isSelected", "()Z")
     getPreferredWidth = J.make_method("getPreferredWidth", "()I")
     getPreferredHeight = J.make_method("getPreferredHeight", "()I")
     update = make_invoke_method("update")
     rebuild = make_invoke_method("rebuild")
     dispose = make_invoke_method("dispose")
Esempio n. 26
0
class CLJFn(Callable):
    """Construct a python callable from a clojure object.  This callable will forward
function calls to it's Clojure object expecting a clojure.lang.IFn interface."""
    applyTo = javabridge.make_method("applyTo", "(clojure/lang/ISeq;)Ljava/lang/Object;")
    def __init__(self, ifn_obj):
        self.o = ifn_obj

    def __call__(self, *args, **kw_args):
        if not kw_args:
            invoker = getattr(self, "invoke"+str(len(args)))
            return invoker(*args)
        else:
            raise Exception("Unable to handle kw_args for now")
        print(len(args), len(kw_args))
Esempio n. 27
0
    def __init__(self, func_name, *args):
        """
        Creates a function decorator for a javabridge function that
        is the member of a class

        Arguments:

        func_name -- The name of the java function
        args -- tuples of form (java_signature, (python arg types),post_process_func)
                e.g. ("(I)I",(int,),None)
                or ("(I)[L",(int,),lambda x: javabridge.get_env().get_long_array_elements(x))
        """
        self.func_name = func_name
        ## Create signature dictionary of {(python args) -> function}
        self.func_dict = signature_dict()
        self.return_func_dict = signature_dict()
        for sig, pyargs, py_return in args:
            self.func_dict[pyargs] = javabridge.make_method(func_name,
                                                    sig)
            if py_return is None:
                self.return_func_dict[pyargs] = lambda x: x
            else:
                self.return_func_dict[pyargs] = py_return
Esempio n. 28
0
        class String(object):
            def __init__(self):
                self.o = env.new_string_utf("Hello, world")

            charAt = javabridge.make_method("charAt", "(I)C",
                                            "My documentation")
Esempio n. 29
0
 def wrapped_f(*args):
     ## If the signature is not set, do it
     if args[0] not in self.sig_set:
         self.func_dict = signature_dict()
         self.return_func_dict = signature_dict()
         ## Set up signature dictionary ##
         for sig, pyargs, py_return in self.func_params:
             ## Replace any instances of strings in the pyargs with the python type
             pyargs = tuple(map(lambda x: (args[0].generic_dict[x] if \
                                 x in args[0].generic_dict else TASSELpy.javaObj.javaObj) if \
                                type(x) == str else x,pyargs))
             # Set func_dict entries
             self.func_dict[pyargs] = javabridge.make_method(self.func_name,sig)
             if type(py_return) == str:
                 ## If return function is replaced with string, meaning
                 # to instantiate generic type
                 if hasattr(args[0].generic_dict[py_return],'generic_dict'):
                     generic_tuple = tuple(map(lambda x: x[1],
                             sorted(args[0].generic_dict[py_return].generic_dict.items())))
                     self.return_func_dict[pyargs] = lambda x: \
                       args[0].generic_dict[py_return](obj=x, generic=generic_tuple) if \
                       isinstance(x,javabridge.JB_Object) else \
                       (args[0].generic_dict[py_return](x) if x is not None else None)
                 else:
                     def da_return_func(x):
                         if isinstance(x, javabridge.JB_Object):
                             return args[0].generic_dict[py_return](obj=x)
                         elif x is None:
                             return None
                         else:
                             try:
                                 return args[0].generic_dict[py_return](x)
                             except KeyError:
                                 obj = None
                                 if isinstance(x, str) or isinstance(x,unicode):
                                     obj = javabridge.make_instance('java/lang/String',
                                                     '(Ljava/lang/String;)V',x)
                                 elif isinstance(x, int):
                                     obj = javabridge.make_instance('java/lang/Integer',
                                                     '(Ljava/lang/Integer;)V',x)
                                 elif isinstance(x, float):
                                     obj = javabridge.make_instance('java/lang/Double',
                                                     '(Ljava/lang/Double;)V',x)
                                 if obj is None: return obj
                                 else:
                                     return args[0].generic_dict[py_return](obj=obj)
                     self.return_func_dict[pyargs] = da_return_func
             elif isinstance(py_return, dict):
                 ## If this is a dictionary, specify the generic type
                 # and make constructor call method
                 if 'type' not in py_return:
                     raise ValueError("Return type of object not given")
                 elif 'generic' not in py_return:
                     raise ValueError("Generic type(s) for return object not given")
                 self.return_func_dict[pyargs] = \
                       lambda x: py_return['type'](obj=x,
                         generic=tuple(map(lambda y: args[0].generic_dict[y] if \
                                           isinstance(y,str) else y,
                                           py_return['generic']))) if \
                                 isinstance(x,javabridge.JB_Object) else x
             elif py_return is None:
                 ## If no return function specified, return raw output
                 self.return_func_dict[pyargs] = lambda x: x
             else:
                 ## If function specified, use that
                 self.return_func_dict[pyargs] = py_return
         # Set sig_set variable to true
         self.sig_set.add(args[0])
     ## Run the function ##
     if len(args) > 1:
         # Get the right function based on argument types
         key = tuple(map(type, args[1:]))
         # Convert any wrapped java items to their java objects
         args = list(args)
         #args[1:] = map(lambda x: (x.o if not hasattr(x,'toPrimative') else x.toPrimative()) \
         #                    if isinstance(x,TASSELpy.javaObj.javaObj) else x,
         #                   args[1:])
         args[1:] = map(lambda x: (x.o if isinstance(x,TASSELpy.javaObj.javaObj) else x),
                            args[1:])
         return_val = self.func_dict[key](*args)
         return self.return_func_dict[key](return_val)
     else:
         return_val = self.func_dict[()](*args)
         return self.return_func_dict[()](return_val)
Esempio n. 30
0
    class ModuleItem(object):
        def __init__(self):
            self.o = instance

        IV_NORMAL = J.get_static_field("org/scijava/ItemVisibility", "NORMAL",
                                       "Lorg/scijava/ItemVisibility;")
        IV_TRANSIENT = J.get_static_field("org/scijava/ItemVisibility",
                                          "TRANSIENT",
                                          "Lorg/scijava/ItemVisibility;")
        IV_INVISIBLE = J.get_static_field("org/scijava/ItemVisibility",
                                          "INVISIBLE",
                                          "Lorg/scijava/ItemVisibility;")
        IV_MESSAGE = J.get_static_field("org/scijava/ItemVisibility",
                                        "MESSAGE",
                                        "Lorg/scijava/ItemVisibility;")

        def getType(self):
            jtype = J.call(self.o, "getType", "()Ljava/lang/Class;")
            type_name = J.call(jtype, "getCanonicalName",
                               "()Ljava/lang/String;")
            if field_mapping.has_key(type_name):
                return field_mapping[type_name]
            for class_instance, result in field_class_mapping():
                if J.call(class_instance, "isAssignableFrom",
                          "(Ljava/lang/Class;)Z", jtype):
                    return result
            return None

        getWidgetStyle = J.make_method("getWidgetStyle",
                                       "()Ljava/lang/String;")
        getMinimumValue = J.make_method("getMinimumValue",
                                        "()Ljava/lang/Object;")
        getMaximumValue = J.make_method("getMaximumValue",
                                        "()Ljava/lang/Object;")
        getStepSize = J.make_method("getStepSize", "()Ljava/lang/Number;")
        getColumnCount = J.make_method("getColumnCount", "()I")
        getChoices = J.make_method("getChoices", "()Ljava/util/List;")
        getValue = J.make_method(
            "getValue", "(Lorg/scijava/module/Module;)Ljava/lang/Object;")
        setValue = J.make_method(
            "setValue", "(Lorg/scijava/module/Module;Ljava/lang/Object;)V",
            "Set the value associated with this item on the module")
        getName = J.make_method("getName", "()Ljava/lang/String;")
        getLabel = J.make_method("getLabel", "()Ljava/lang/String;")
        getDescription = J.make_method("getDescription",
                                       "()Ljava/lang/String;")
        loadValue = J.make_method("loadValue", "()Ljava/lang/Object;")
        isInput = J.make_method("isInput", "()Z")
        isOutput = J.make_method("isOutput", "()Z")
        isRequired = J.make_method("isRequired", "()Z")
        initialize = J.make_method("initialize",
                                   "(Lorg/scijava/module/Module;)V")
Esempio n. 31
0
    class ImageDisplay(object):
        def __init__(self):
            self.o = display

        #
        # List<DataView> methods
        #
        size = J.make_method("size", "()I")
        isEmpty = J.make_method("isEmpty", "()Z")
        contains = J.make_method("contains", "(Ljava/lang/Object;)Z")

        def __iter__(self):
            return J.iterate_collection(self.o)

        toArray = J.make_method(
            "toArray",
            "()[Ljava/lang/Object;",
            fn_post_process=lambda o: [
                wrap_data_view(v)
                for v in J.get_env().get_object_array_elements(o)
            ])
        addO = make_invoke_method("add", returns_value=True)
        removeO = make_invoke_method("remove", returns_value=True)
        clear = make_invoke_method("clear", returns_value=True)
        get = J.make_method("get",
                            "(I)Ljava/lang/Object;",
                            fn_post_process=wrap_data_view)
        set = make_invoke_method("set")
        addI = make_invoke_method("add")
        removeI = make_invoke_method("remove")
        #
        # Display methods
        #
        canDisplay = J.make_method(
            "canDisplay", "(Ljava/lang/Object;)Z",
            "Return true if display can display dataset")
        display = make_invoke_method("display", doc="Display the given object")
        update = make_invoke_method("update", doc="Signal display change")
        getName = J.make_method("getName", "()Ljava/lang/String;")
        setName = J.make_method("setName", "(Ljava/lang/String;)V")

        def close(self):
            '''Close the display
            
            This is run in the UI thread with synchronization.
            '''
            r = J.run_script(
                """new java.lang.Runnable() {
                run: function() { display.close(); }
                };
                """, dict(display=self.o))
            J.execute_runnable_in_main_thread(r, True)

        #
        # ImageDisplay methods
        #
        getActiveView = J.make_method("getActiveView",
                                      "()Lnet/imagej/display/DataView;",
                                      fn_post_process=wrap_data_view)
        getActiveAxis = J.make_method("getActiveAxis",
                                      "()Lnet/imglib2/meta/AxisType;")
        setActiveAxis = J.make_method("setActiveAxis",
                                      "(Lnet/imglib2/meta/AxisType;)V")
        getCanvas = J.make_method("getCanvas",
                                  "()Lnet/imagej/display/ImageCanvas;")
Esempio n. 32
0
    class DisplayService(object):
        def __init__(self):
            self.o = o

        def createDisplay(self, name, dataset):
            '''Create a display that contains the given dataset'''
            #
            # Must be run on the gui thread
            #
            jcallable = J.run_script(
                """new java.util.concurrent.Callable() {
                    call:function() {
                        return displayService.createDisplay(name, dataset);
                    }
                };
                """, dict(displayService=self.o, name=name, dataset=dataset.o))
            future = J.make_future_task(jcallable,
                                        fn_post_process=wrap_display)
            return J.execute_future_in_main_thread(future)

        def getActiveDisplay(self, klass=None):
            '''Get the first display, optionally of the given type from the list
            
            klass - if not None, return the first display of this type, 
                    otherwise return the first display
            '''
            if klass is None:
                return wrap_display(
                    J.call(self.o, "getActiveDisplay",
                           "()Lorg/scijava/display/Display;"))
            else:
                return wrap_display(
                    J.call(self.o, "getActiveDisplay",
                           "(Ljava/lang/Class;)Lorg/scijava/display/Display;",
                           klass))

        def getActiveImageDisplay(self):
            '''Get the active imagej.data.display.ImageDisplay'''
            return wrap_display(
                J.call(self.o, "getActiveDisplay",
                       "()Lorg/scijava/display/Display;",
                       J.class_for_name("net.imagej.display.ImageDisplay")))

        def setActiveDisplay(self, display):
            '''Make this the active display'''
            # Note: has to be run in GUI thread on mac
            r = J.run_script(
                """new java.lang.Runnable() {
                    run:function() { displayService.setActiveDisplay(display); }
                }
                """, dict(displayService=self.o, display=display.o))
            J.execute_runnable_in_main_thread(r, True)

        getDisplays = J.make_method("getDisplays",
                                    "()Ljava/util/List;",
                                    fn_post_process=lambda x: map(
                                        wrap_display, J.iterate_collection(x)))
        getDisplay = J.make_method(
            "getDisplay",
            "(Ljava/lang/String;)Lorg/scijava/display/Display;",
            fn_post_process=wrap_display)
        isUniqueName = J.make_method("isUniqueName", "(Ljava/lang/String;)Z")
Esempio n. 33
0
    class MenuEntry(object):
        def __init__(self, o=menu_entry):
            self.o = o

        setName = J.make_method("setName", "(Ljava/lang/String;)V")
        getName = J.make_method("getName", "()Ljava/lang/String;")
        setWeight = J.make_method("setWeight", "(D)V")
        getWeight = J.make_method("getWeight", "()D")
        setMnemonic = J.make_method("setMnemonic", "(C)V")
        getMnemonic = J.make_method("getMnemonic", "()C")
        setAccelerator = J.make_method("setAccelerator",
                                       "(Lorg/scijava/input/Accelerator;)V")
        getAccelerator = J.make_method("getAccelerator",
                                       "()Lorg/scijava/input/Accelerator;")
        setIconPath = J.make_method("setIconPath", "(Ljava/lang/String;)V")
        getIconPath = J.make_method("getIconPath", "()Ljava/lang/String;")
        assignProperties = J.make_method("assignProperties",
                                         "(Lorg/scijava/MenuEntry;)V")