Beispiel #1
0
def CopyIcons(dstpath, srcpath):
    import os.path, string
    index = None
    try:
        srcpath, index = map(string.strip, string.split(srcpath, ','))
        index = int(index)
    except:
        pass
    print "I: PATH, INDEX", srcpath, index
    srcext = os.path.splitext(srcpath)[1]
    if string.lower(srcext) == '.ico':
        return CopyIcons_FromIco(dstpath, srcpath)
    if index is not None:
        print "I: Updating icons from", srcpath, ", %d to" % index, dstpath
    else:
        print "I: Updating icons from", srcpath, "to", dstpath
    import win32api  #, win32con
    hdst = win32api.BeginUpdateResource(dstpath, 0)
    hsrc = win32api.LoadLibraryEx(srcpath, 0, LOAD_LIBRARY_AS_DATAFILE)
    if index is None:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[0]
    elif index >= 0:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[index]
    else:
        grpname = -index
    data = win32api.LoadResource(hsrc, RT_GROUP_ICON, grpname)
    win32api.UpdateResource(hdst, RT_GROUP_ICON, grpname, data)
    for iconname in win32api.EnumResourceNames(hsrc, RT_ICON):
        data = win32api.LoadResource(hsrc, RT_ICON, iconname)
        win32api.UpdateResource(hdst, RT_ICON, iconname, data)
    win32api.FreeLibrary(hsrc)
    win32api.EndUpdateResource(hdst, 0)
def CopyIcons(dstpath, srcpath):
    import os.path

    if type(srcpath) in StringTypes:
        srcpath = [srcpath]

    def splitter(s):
        try:
            srcpath, index = s.split(',')
            return srcpath.strip(), int(index)
        except ValueError:
            return s, None

    srcpath = list(map(splitter, srcpath))
    logger.info("SRCPATH %s", srcpath)

    if len(srcpath) > 1:
        # At the moment, we support multiple icons only from .ico files
        srcs = []
        for s in srcpath:
            e = os.path.splitext(s[0])[1]
            if e.lower() != '.ico':
                raise ValueError(
                    'Multiple icons supported only from .ico files')
            if s[1] is not None:
                raise ValueError('index not allowed for .ico files')
            srcs.append(s[0])
        return CopyIcons_FromIco(dstpath, srcs)

    srcpath, index = srcpath[0]
    srcext = os.path.splitext(srcpath)[1]
    if srcext.lower() == '.ico':
        return CopyIcons_FromIco(dstpath, [srcpath])
    if index is not None:
        logger.info("Updating icons from %s, %d to %s", srcpath, index,
                    dstpath)
    else:
        logger.info("Updating icons from %s to %s", srcpath, dstpath)
    import win32api  #, win32con
    hdst = win32api.BeginUpdateResource(dstpath, 0)
    hsrc = win32api.LoadLibraryEx(srcpath, 0, LOAD_LIBRARY_AS_DATAFILE)
    if index is None:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[0]
    elif index >= 0:
        grpname = win32api.EnumResourceNames(hsrc, RT_GROUP_ICON)[index]
    else:
        grpname = -index
    data = win32api.LoadResource(hsrc, RT_GROUP_ICON, grpname)
    win32api.UpdateResource(hdst, RT_GROUP_ICON, grpname, data)
    for iconname in win32api.EnumResourceNames(hsrc, RT_ICON):
        data = win32api.LoadResource(hsrc, RT_ICON, iconname)
        win32api.UpdateResource(hdst, RT_ICON, iconname, data)
    win32api.FreeLibrary(hsrc)
    win32api.EndUpdateResource(hdst, 0)
Beispiel #3
0
def decode(pathnm):
    h = win32api.LoadLibraryEx(pathnm, 0, LOAD_LIBRARY_AS_DATAFILE)
    nm = win32api.EnumResourceNames(h, RT_VERSION)[0]
    data = win32api.LoadResource(h, RT_VERSION, nm)
    vs = VSVersionInfo()
    j = vs.fromRaw(data)
    if TEST:
        print vs
        if data[:j] != vs.toRaw():
            print "AAAAAGGHHHH"
        txt = repr(vs)
        glbls = {}
        glbls['VSVersionInfo'] = VSVersionInfo
        glbls['FixedFileInfo'] = FixedFileInfo
        glbls['StringFileInfo'] = StringFileInfo
        glbls['StringTable'] = StringTable
        glbls['StringStruct'] = StringStruct
        glbls['VarFileInfo'] = VarFileInfo
        glbls['VarStruct'] = VarStruct
        vs2 = eval(txt + '\n', glbls)
        if vs.toRaw() != vs2.toRaw():
            print
            print 'reconstruction not the same!'
            print vs2
    win32api.FreeLibrary(h)
    return vs
Beispiel #4
0
def load_icon(module, index, as_data=False, size=ICON_SIZE):
    handle = win32api.LoadLibraryEx(module, 0, 0x20 | 0x2)
    try:
        ids = win32api.EnumResourceNames(handle, win32con.RT_GROUP_ICON)
        grp_id = -index if index < 0 else ids[index]
        data = win32api.LoadResource(handle, win32con.RT_GROUP_ICON, grp_id)
        pos = 0
        reserved, idtype, count = struct.unpack_from(b'<HHH', data, pos)
        pos += 6
        fmt = b'<BBBBHHIH'
        ssz = struct.calcsize(fmt)
        icons = []
        Icon = namedtuple('Icon', 'size width height id')
        while count > 0:
            count -= 1
            width, height, color_count, reserved, planes, bitcount, isize, icon_id = struct.unpack_from(
                fmt, data, pos)
            icons.append(Icon(isize, width, height, icon_id))
            pos += ssz
        # Unfortunately we cannot simply choose the icon with the largest
        # width/height as the width and height are not recorded for PNG images
        pixmaps = []
        for icon in icons:
            ans = read_icon(handle, icon)
            if ans is not None and not ans.isNull():
                pixmaps.append(ans)
        pixmaps.sort(key=lambda p: p.size().width(), reverse=True)
        pixmap = copy_to_size(pixmaps[0], size=size)
        if as_data:
            pixmap = pixmap_to_data(pixmap)
        return pixmap
    finally:
        win32api.FreeLibrary(handle)
Beispiel #5
0
    def test_load_resource(self):
        with self.load_library(win32api, u'explorer.exe') as handle:
            resource_types = win32api.EnumResourceTypes(handle)
            for resource_type in resource_types:
                resource_names = win32api.EnumResourceNames(
                    handle, resource_type)
                for resource_name in resource_names:
                    resource_languages = win32api.EnumResourceLanguages(
                        handle, resource_type, resource_name)
                    for resource_language in resource_languages:
                        expected = win32api.LoadResource(
                            handle, resource_type, resource_name,
                            resource_language)
                        resource = self.module.LoadResource(
                            handle, resource_type, resource_name,
                            resource_language)
                        # check that the #<index> format works
                        resource = self.module.LoadResource(
                            handle, self._id2str(resource_type),
                            self._id2str(resource_name),
                            resource_language)
                        self.assertEqual(resource, expected)

        with self.assertRaises(error):
            self.module.LoadResource(
                handle, resource_type, resource_name, 12435)
Beispiel #6
0
def decode(pathnm):
    h = win32api.LoadLibraryEx(pathnm, 0, LOAD_LIBRARY_AS_DATAFILE)
    nm = win32api.EnumResourceNames(h, pefile.RESOURCE_TYPE['RT_VERSION'])[0]
    data = win32api.LoadResource(h, pefile.RESOURCE_TYPE['RT_VERSION'], nm)
    vs = VSVersionInfo()
    j = vs.fromRaw(data)
    win32api.FreeLibrary(h)
    return vs
Beispiel #7
0
def _GetResources(hsrc, types=None, names=None, languages=None):
    """
    Get resources from hsrc.

    types = a list of resource types to search for (None = all)
    names = a list of resource names to search for (None = all)
    languages = a list of resource languages to search for (None = all)
    Return a dict of the form {type_: {name: {language: data}}} which
    might also be empty if no matching resources were found.
    """
    if types:
        types = set(types)
    if names:
        names = set(names)
    if languages:
        languages = set(languages)
    res = {}
    try:
        # logger.debug("Enumerating resource types")
        enum_types = win32api.EnumResourceTypes(hsrc)
        if types and not "*" in types:
            enum_types = filter(lambda type_:
                                type_ in types,
                                enum_types)
        for type_ in enum_types:
            # logger.debug("Enumerating resources of type %s", type_)
            enum_names = win32api.EnumResourceNames(hsrc, type_)
            if names and not "*" in names:
                enum_names = filter(lambda name:
                                    name in names,
                                    enum_names)
            for name in enum_names:
                # logger.debug("Enumerating resources of type %s name %s", type_, name)
                enum_languages = win32api.EnumResourceLanguages(hsrc,
                                                                type_,
                                                                name)
                if languages and not "*" in languages:
                    enum_languages = filter(lambda language:
                                            language in languages,
                                            enum_languages)
                for language in enum_languages:
                    data = win32api.LoadResource(hsrc, type_, name, language)
                    if not type_ in res:
                        res[type_] = {}
                    if not name in res[type_]:
                        res[type_][name] = {}
                    res[type_][name][language] = data
    except pywintypes.error as exception:
        if exception.args[0] in (ERROR_RESOURCE_DATA_NOT_FOUND,
                                 ERROR_RESOURCE_TYPE_NOT_FOUND,
                                 ERROR_RESOURCE_NAME_NOT_FOUND,
                                 ERROR_RESOURCE_LANG_NOT_FOUND):
            # logger.info('%s: %s', exception.args[1:3])
            pass
        else:
            raise exception
    return res
Beispiel #8
0
def GetIconNamesList(pathName):
    # Using LoadLibrary (rather than CreateFile) is required otherwise
    # LoadResource, FindResource and others will fail
    hlib = win32api.LoadLibraryEx(pathName, 0, 2)

    # get icon groups, default is the first group
    icon_groups = win32api.EnumResourceNames(hlib, win32con.RT_GROUP_ICON)

    return icon_groups
Beispiel #9
0
def ExtractIconFromExe(pathName, tmpDirName):
    # Using LoadLibrary (rather than CreateFile) is required otherwise
    # LoadResource, FindResource and others will fail
    hlib = win32api.LoadLibraryEx(pathName, 0, 2)

    # get icon groups, default is the first group
    icon_groups = win32api.EnumResourceNames(hlib, win32con.RT_GROUP_ICON)

    for group_name in icon_groups:
        IconToFile(hlib, tmpDirName, group_name)
Beispiel #10
0
def get_manifest_from_dll(dll):
    import win32api, pywintypes
    LOAD_LIBRARY_AS_DATAFILE = 2
    d = win32api.LoadLibraryEx(os.path.abspath(dll), 0, LOAD_LIBRARY_AS_DATAFILE)
    try:
        resources = win32api.EnumResourceNames(d, 24)
    except pywintypes.error as err:
        if err.winerror == 1812:
            return None, None  # no resource section (probably a .pyd file)
        raise
    if resources:
        return resources[0], win32api.LoadResource(d, 24, resources[0])
    return None, None
Beispiel #11
0
def GetIconNamesList(pathName):
    # Using LoadLibrary (rather than CreateFile) is required otherwise
    # LoadResource, FindResource and others will fail
	try:
		hlib = win32api.LoadLibraryEx(pathName, 0, 2)

		# get icon groups, default is the first group
		iconGroups = win32api.EnumResourceNames(hlib, win32con.RT_GROUP_ICON)
	except Exception:
		exc = sys.exc_info()[1]
		lib_common.ErrorMessageHtml("GetIconNamesList pathName=%s caught:%s" % ( pathName, str(exc) ) )

    # Strings and integers.
	return iconGroups
Beispiel #12
0
def getico(loc):
	#Better way?
	try:
		b=win32api.LoadLibraryEx (loc, 0, LOAD_LIBRARY_AS_DATAFILE)
		for e in win32api.EnumResourceNames (b, RT_ICON):
			data = win32api.LoadResource(b, RT_ICON, e)
			stream = StringIO.StringIO(ICON_HEADER + data)
			ir=Image.open(stream)
			if(ir.getextrema()[1] > 200):
				if(ir.size[-1] > B_SZ-10): #32
					break
	except:
		ir =Image.open(ICON_DEFAULT)
	return ir
Beispiel #13
0
    def ExtractAllToDir(self, extract_to):
        """Extracts all resources from our input file to a directory hierarchy
    in the directory named extract_to.

    The generated directory hierarchy is three-level, and looks like:
      resource-type/
        resource-name/
          lang-id.

    Args:
      extract_to: path to the folder to output to. This folder will be erased
          and recreated if it already exists.
    """
        _LOGGER.info('Extracting all resources from "%s" to directory "%s".',
                     self.input_file, extract_to)

        if os.path.exists(extract_to):
            _LOGGER.info('Destination directory "%s" exists, deleting',
                         extract_to)
            shutil.rmtree(extract_to)

        # Make sure the destination dir exists.
        os.makedirs(extract_to)

        # Now enumerate the resource types.
        for res_type in win32api.EnumResourceTypes(self.module):
            res_type_str = _ResIdToString(res_type)

            # And the resource names.
            for res_name in win32api.EnumResourceNames(self.module, res_type):
                res_name_str = _ResIdToString(res_name)

                # Then the languages.
                for res_lang in win32api.EnumResourceLanguages(
                        self.module, res_type, res_name):
                    res_lang_str = _ResIdToString(res_lang)

                    dest_dir = os.path.join(extract_to, res_type_str,
                                            res_lang_str)
                    dest_file = os.path.join(dest_dir, res_name_str)
                    _LOGGER.info(
                        'Extracting resource "%s", lang "%d" name "%s" '
                        'to file "%s".', res_type_str, res_lang, res_name_str,
                        dest_file)

                    # Extract each resource to a file in the output dir.
                    if not os.path.exists(dest_dir):
                        os.makedirs(dest_dir)
                    self.ExtractResource(res_type, res_lang, res_name,
                                         dest_file)
Beispiel #14
0
    def test_enum_resource_names(self):
        with self.load_library(win32api, u'shell32.dll') as handle:
            resource_types = win32api.EnumResourceTypes(handle)
            for resource_type in resource_types:
                expected = win32api.EnumResourceNames(handle, resource_type)
                resource_names = self.module.EnumResourceNames(
                    handle, resource_type)
                self.assertEqual(resource_names, expected)
                # check that the #<index> format works
                resource_names = self.module.EnumResourceNames(
                    handle, self._id2str(resource_type))
                self.assertEqual(resource_names, expected)

        with self.assertRaises(error):
            self.module.EnumResourceNames(2, 3)
Beispiel #15
0
def GetIconNamesList(path_name):
    """For a Windows executable file, it returns the list of resource icons groups it contains."""

    # Using LoadLibrary (instead of CreateFile) is required otherwise LoadResource, FindResource and others will fail.
    try:
        hlib = win32api.LoadLibraryEx(path_name, 0, 2)

        # get icon groups, default is the first group
        icon_groups = win32api.EnumResourceNames(hlib, win32con.RT_GROUP_ICON)
    except Exception as exc:
        lib_common.ErrorMessageHtml("GetIconNamesList pathName=%s caught:%s" %
                                    (path_name, str(exc)))

    # Strings and integers.
    return icon_groups
Beispiel #16
0
def _GetResources(hsrc, types=None, names=None, languages=None):
    """
    Get resources from hsrc.
    
    types = a list of resource types to search for (None = all)
    names = a list of resource names to search for (None = all)
    languages = a list of resource languages to search for (None = all)
    Return a dict of the form {type_: {name: {language: data}}} which 
    might also be empty if no matching resources were found.
    
    """
    res = {}
    try:
        # print "I: Enumerating resource types"
        enum_types = win32api.EnumResourceTypes(hsrc)
        if types and not "*" in types:
            enum_types = filter(lambda type_: type_ in types, enum_types)
        for type_ in enum_types:
            # print "I: Enumerating resources of type", type_
            enum_names = win32api.EnumResourceNames(hsrc, type_)
            if names and not "*" in names:
                enum_names = filter(lambda name: name in names, enum_names)
            for name in enum_names:
                # print "I: Enumerating resources of type", type_, "name", name
                enum_languages = win32api.EnumResourceLanguages(
                    hsrc, type_, name)
                if languages and not "*" in languages:
                    enum_languages = filter(
                        lambda language: language in languages, enum_languages)
                for language in enum_languages:
                    data = win32api.LoadResource(hsrc, type_, name, language)
                    if not type_ in res:
                        res[type_] = {}
                    if not name in res[type_]:
                        res[type_][name] = {}
                    res[type_][name][language] = data
    except pywintypes.error, exception:
        if exception.args[0] in (ERROR_RESOURCE_DATA_NOT_FOUND,
                                 ERROR_RESOURCE_TYPE_NOT_FOUND,
                                 ERROR_RESOURCE_NAME_NOT_FOUND,
                                 ERROR_RESOURCE_LANG_NOT_FOUND):
            # print "I:", exception.args[1] + ":", \
            # exception.args[2]
            pass
        else:
            raise exception
Beispiel #17
0
def load_manifest(handle):
    """get the first manifest string from HMODULE"""
    for restype in (RT_MANIFEST, ):  # win32api.EnumResourceTypes(handle)
        for name in win32api.EnumResourceNames(handle, restype):
            return win32api.LoadResource(handle, restype, name).decode('utf_8')