Esempio n. 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)
Esempio n. 2
0
def IconToFile(hlib, tmpDirName, group_name):
    libc = ctypes.CDLL(ctypes.util.find_library('c'))
    libc.memcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t]
    libc.memcpy.restype = ctypes.c_char_p

    # patch FindResourceW, ctypes.windll.kernel32.SizeofResource
    FindResourceW = ctypes.windll.kernel32.FindResourceW
    FindResourceW.argtypes = [
        ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p
    ]
    FindResourceW.restype = ctypes.c_void_p
    SizeofResource = ctypes.windll.kernel32.SizeofResource
    SizeofResource.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
    SizeofResource.restype = ctypes.c_size_t

    hRes = win32api.LoadResource(hlib, win32con.RT_GROUP_ICON, group_name)
    mem_icon_dir = ctypes.windll.kernel32.LockResource(hRes)

    # 32 bits color; 16 and 256 colors are too old

    icon_size = 256
    icon_name = ctypes.windll.user32.LookupIconIdFromDirectoryEx(
        mem_icon_dir, True, icon_size, icon_size, 0x00000000)
    sys.stderr.write("icon_name=%s\n" % str(icon_name))
    hResInfo = FindResourceW(hlib, icon_name, win32con.RT_ICON)
    size = ctypes.windll.kernel32.SizeofResource(hlib, hResInfo)
    rec = win32api.LoadResource(hlib, win32con.RT_ICON, icon_name)
    mem_icon = ctypes.windll.kernel32.LockResource(rec)

    # And this is some differ (copy data to Python buffer)
    binary_data = (ctypes.c_ubyte * size)()
    libc.memcpy(binary_data, mem_icon, size)
    hIconRet = ctypes.windll.user32.CreateIconFromResourceEx(
        binary_data, size, True, 0x00030000, 0, 0, 0x00000000)
    info = win32gui.GetIconInfo(hIconRet)
    bminfo = win32gui.GetObject(info[4])

    # generate bitmap by drawing the icon
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, bminfo.bmWidth, bminfo.bmHeight)
    hcdc = hdc.CreateCompatibleDC()
    hcdc.SelectObject(hbmp)
    win32gui.DrawIconEx(hcdc.GetHandleOutput(), 0, 0, hIconRet, bminfo.bmWidth,
                        bminfo.bmHeight, 0, 0, 0x0003)

    # Need temp directory or generate image on the fly, for inclusion into an HTML page.
    # Temp file visible from HTTP server.
    # An alternative is to send the file content to a socket stream.
    # MIME type is "image/bmp"
    imgFilNam = "icon-%03dx%03d-%05d-%03d.bmp" % (
        bminfo.bmWidth, bminfo.bmHeight, group_name, icon_name)
    if tmpDirName:
        imgFilNam = tmpDirName + imgFilNam
    sys.stderr.write("Generating %s\n" % imgFilNam)
    hbmp.SaveBitmapFile(hcdc, imgFilNam)
    win32gui.DestroyIcon(hIconRet)
    return imgFilNam
Esempio n. 3
0
def IconToFile(hlib, group_name):
    """The group might be a string or an integer and its type must be kept."""

    # patch FindResourceW, ctypes.windll.kernel32.SizeofResource
    FindResourceW = ctypes.windll.kernel32.FindResourceW
    FindResourceW.argtypes = [
        ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p
    ]
    FindResourceW.restype = ctypes.c_void_p
    SizeofResource = ctypes.windll.kernel32.SizeofResource
    SizeofResource.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
    SizeofResource.restype = ctypes.c_size_t

    hRes = win32api.LoadResource(hlib, win32con.RT_GROUP_ICON, group_name)
    mem_icon_dir = ctypes.windll.kernel32.LockResource(hRes)

    # 32 bits color; 16 and 256 colors are too old

    icon_size = 256
    icon_name = ctypes.windll.user32.LookupIconIdFromDirectoryEx(
        mem_icon_dir, True, icon_size, icon_size, 0x00000000)
    h_res_info = FindResourceW(hlib, icon_name, win32con.RT_ICON)
    size = ctypes.windll.kernel32.SizeofResource(hlib, h_res_info)
    rec = win32api.LoadResource(hlib, win32con.RT_ICON, icon_name)
    mem_icon = ctypes.windll.kernel32.LockResource(rec)

    # And this is some differ (copy data to Python buffer)
    binary_data = (ctypes.c_ubyte * size)()
    ctypes.memmove(binary_data, mem_icon, size)
    h_icon_ret = ctypes.windll.user32.CreateIconFromResourceEx(
        binary_data, size, True, 0x00030000, 0, 0, 0x00000000)
    info = win32gui.GetIconInfo(h_icon_ret)
    bminfo = win32gui.GetObject(info[4])

    # generate bitmap by drawing the icon
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    hbmp.CreateCompatibleBitmap(hdc, bminfo.bmWidth, bminfo.bmHeight)
    hcdc = hdc.CreateCompatibleDC()
    hcdc.SelectObject(hbmp)
    win32gui.DrawIconEx(hcdc.GetHandleOutput(), 0, 0, h_icon_ret,
                        bminfo.bmWidth, bminfo.bmHeight, 0, 0, 0x0003)

    # MIME type is "image/bmp"
    # The group name might be a number: 110 etc... or a string such as 'ICO_MYCOMPUTER'.

    # This is the prefix of the temporary BMP file name containing the extracted icon.
    img_fil_nam_prefix = "icon-%03dx%03d-%s-%03d" % (
        bminfo.bmWidth, bminfo.bmHeight, str(group_name), icon_name)

    # The destructor will remove the file.
    obj_temp_file = lib_util.TmpFile(img_fil_nam_prefix, "bmp")

    img_fil_nam = obj_temp_file.Name
    hbmp.SaveBitmapFile(hcdc, img_fil_nam)
    win32gui.DestroyIcon(h_icon_ret)
    return obj_temp_file
Esempio n. 4
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)
Esempio n. 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)
def read_default_windows7_tasklist_xml():
    handle = win32api.LoadLibraryEx(
        "shell32.dll", None, win32con.LOAD_LIBRARY_AS_DATAFILE
        | win32con.DONT_RESOLVE_DLL_REFERENCES)
    #TODO: Is the resource-id (#21) same for all builds of Windows 7?
    xml = win32api.LoadResource(handle, "XML", 21)
    return xml
Esempio n. 7
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
Esempio n. 8
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)
Esempio n. 9
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
Esempio n. 10
0
 def GetResource(self, res_id):
     if hasattr(sys, 'frozen') and sys.frozen in ('windows_exe', 'console_exe'):
         return win32api.LoadResource(0, 'beatdown', res_id)
     else:
         res_path = {
             1: './graphics/logo.ico',
         }.get(res_id)
         res_path = os.path.abspath(os.path.join(APP_PATH, res_path))
         return open(res_path, 'rb').read()
Esempio n. 11
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
Esempio n. 12
0
def get_res_data(path):
    if main_is_frozen():
        path = path.replace("/", "\\")
        if RES_ID.has_key(path):
            res = win32api.LoadResource(0, u'RESOURCE', RES_ID[path])
            return StringIO.StringIO(res).read()
        else:
            return None
    else:
        return open(os.path.join(get_res_dir(), path)).read()
Esempio n. 13
0
def extract_manifest(path, resource_name):
    """Reads manifest from |path| and returns it as a string.
  Returns None is there is no such manifest."""
    with LoadLibrary(path) as handle:
        try:
            return win32api.LoadResource(handle, RT_MANIFEST, resource_name)
        except pywintypes.error as error:
            if error.args[0] == winerror.ERROR_RESOURCE_DATA_NOT_FOUND:
                return None
            else:
                raise
Esempio n. 14
0
def serve_resource(path):
    if main_is_frozen():
        path = path.replace("/", "\\")
        if RES_ID.has_key(path):
            return serve_fileobj(
                StringIO.StringIO(win32api.LoadResource(0, u'RESOURCE', RES_ID[path])),
                content_type=get_content_type(path)
                )
        else:
            raise cherrypy.NotFound
    else:
        return serve_file(os.path.abspath(os.path.join(get_res_dir(), path)))
Esempio n. 15
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
Esempio n. 16
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
Esempio n. 17
0
def read_icon(handle, icon):
    must_use_qt()
    resource = win32api.LoadResource(handle, win32con.RT_ICON, icon.id)
    pixmap = QPixmap()
    pixmap.loadFromData(resource)
    hicon = None
    if pixmap.isNull():
        if icon.width > 0 and icon.height > 0:
            hicon = ctypes.windll.user32.CreateIconFromResourceEx(
                resource, len(resource), True, 0x00030000, icon.width, icon.height, win32con.LR_DEFAULTCOLOR)
        else:
            hicon = win32gui.CreateIconFromResource(resource, True)
        pixmap = hicon_to_pixmap(hicon).copy()
        win32gui.DestroyIcon(hicon)
    return pixmap
Esempio n. 18
0
    def _DoCreateIcons(self):
        # Try and find a custom icon
        hinst = win32api.GetModuleHandle(None)

        hicon = win32gui.CreateIconFromResource(
            win32api.LoadResource(None, win32con.RT_ICON, 1), True)

        flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
        nid = (self.hwnd, 0, flags, win32con.WM_USER + 20, hicon,
               "Python Demo")
        try:
            win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)
        except win32gui.error:
            # This is common when windows is starting, and this code is hit
            # before the taskbar has been created.
            print "Failed to add the taskbar icon - is explorer running?"
Esempio n. 19
0
  def ExtractResource(self, res_type, res_lang, res_name, dest_file):
    """Extracts a given resource, specified by type, language id and name,
    to a given file.

    Args:
      res_type: the type of the resource, e.g. "B7".
      res_lang: the language id of the resource e.g. 1033.
      res_name: the name of the resource, e.g. "SETUP.EXE".
      dest_file: path to the file where the resource data will be written.
    """
    _LOGGER.info('Extracting resource "%s", lang "%d" name "%s" '
                 'to file "%s".', res_type, res_lang, res_name, dest_file)

    data = win32api.LoadResource(self.module, res_type, res_name, res_lang)
    with open(dest_file, 'wb') as f:
      f.write(data)
Esempio n. 20
0
 def get(self, ids):
     """get(self, ids)
     Returns the string and html resources for the specified ids as a
     tuple(string, string)
     """
     ids = ids % _MAXI
     # pylint: disable=E1101
     try:
         string = w32.LoadString(self._dll, ids)
     except pywintypes.error:
         string = None
     try:
         html = unicode(w32.LoadResource(self._dll, 23, ids, 1033),
                        encoding='UTF-16')
     except pywintypes.error:
         html = None
     return string, html
Esempio n. 21
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
Esempio n. 22
0
def init(version):
    global dbdir, conn, cur, misc
    global webstyle, webscript
    global windowIcon, styleSheet

    styleSheet = '''
		font-size: 10pt;
		font-family: ConsolasHigh,Meiryo;
		background-color: Black;
		color: DarkGray;
	'''
    if is_exe():
        img = QtGui.QPixmap()
        img.loadFromData(
            StringIO(win32api.LoadResource(0, u'CLOUD_PNG', 1)).getvalue())
        windowIcon = QtGui.QIcon(img)
        webstyle = win32api.LoadResource(0, u'STYLE_CSS', 2)
        webscript = win32api.LoadResource(0, u'SRC_JS', 3)
        QtGui.QFontDatabase().addApplicationFontFromData(
            StringIO(win32api.LoadResource(0, u'CONSOLASHIGH_TTF',
                                           4)).getvalue())
    else:
        windowIcon = QtGui.QIcon('resources/cloud.png')
        with open('resources/style.css', 'r') as fp:
            webstyle = fp.read()
        with open('resources/src.js', 'r') as fp:
            webscript = fp.read()
        QtGui.QFontDatabase().addApplicationFont('resources/ConsolasHigh.ttf')

    # init database
    dbdir = '%s\\LR2RR\\' % os.environ['APPDATA']
    if not os.path.exists(dbdir):
        os.makedirs(dbdir)
    conn = sqlite3.connect(dbdir + 'data.db', check_same_thread=False)
    conn.row_factory = sqlite3.Row
    cur = conn.cursor()
    with dbLock:
        try:
            cur.execute('''
				CREATE TABLE IF NOT EXISTS
				rivals(
					id INTEGER NOT NULL UNIQUE,
					name TEXT,
					lastupdate INTEGER NOT NULL,
					active INTEGER
				)''')
            cur.execute('''
				CREATE TABLE IF NOT EXISTS
				scores(
					hash TEXT NOT NULL,
					id INTEGER NOT NULL,
					clear INTEGER NOT NULL,
					notes INTEGER NOT NULL,
					combo INTEGER NOT NULL,
					pg INTEGER NOT NULL,
					gr INTEGER NOT NULL,
					minbp INTEGER NOT NULL,
					UNIQUE(hash, id)
				)''')
            cur.execute('''
				CREATE TABLE IF NOT EXISTS
				recent(
					hash TEXT NOT NULL,
					id INTEGER NOT NULL,
					title TEXT,
					lastupdate INTEGER NOT NULL,
					UNIQUE(hash, id)
				)''')
            cur.execute('''
				CREATE TABLE IF NOT EXISTS
				misc(
					key TEXT NOT NULL UNIQUE,
					value TEXT
				)''')
            cur.execute('REPLACE INTO misc VALUES("version",?)', (version, ))
            cur.execute('INSERT OR IGNORE INTO misc VALUES("lr2exepath","")')
            cur.execute(
                'INSERT OR IGNORE INTO misc VALUES("irlastupdate","Never")')
            cur.execute(
                'INSERT OR IGNORE INTO misc VALUES("difficultieslastupdate","Never")'
            )
            conn.commit()
            cur.execute('SELECT * FROM misc')
            for tt in cur.fetchall():
                misc[tt['key']] = tt['value']
        except:
            conn.rollback()
            sys.exit()
Esempio n. 23
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')
Esempio n. 24
0
    def __call__(self,
                 title="",
                 msg="",
                 payload=None,
                 iconOpt=ICON_EG,
                 sound=True):
        """
        Show a tip balloon in the Windows Event Center.

        title: Bold text to show in the title of the tip.
        msg: Detail text to show in the tip.
        payload: Python data to include with events triggered from this tip.
        iconOpt: an int or a string:
          0 = No icon
          1 = Info icon
          2 = Warning icon
          3 = Error icon
          4 = EventGhost icon
          string = *full path* to an icon file, a semicolon, and the icon number
            (eg: "C:\\Windows\\system32\\shell32.dll;13")
        sound: Whether to play the notification sound.
        """
        if iconOpt is None:
            iconOpt = self.ICON_EG
        title = eg.ParseString(title or "EventGhost")
        msg = eg.ParseString(msg or "This is a notification from EventGhost.")
        if payload and isinstance(payload, basestring):
            payload = eg.ParseString(payload)

        # https://stackoverflow.com/a/17262942/6692652
        # Create the window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        hwnd = win32gui.CreateWindow(self.plugin.classAtom, "TaskBar", style,
                                     0, 0, win32con.CW_USEDEFAULT,
                                     win32con.CW_USEDEFAULT, 0, 0,
                                     self.plugin.hinst, None)
        win32gui.UpdateWindow(hwnd)
        self.plugin.setPayload(hwnd, payload)

        # Icons management
        # Default to no icon if something goes weird
        hicon = None
        dwInfoFlags = 0x00
        try:
            if iconOpt == self.ICON_INFO:
                dwInfoFlags = NIIF_INFO | NIIF_LARGE_ICON
            elif iconOpt == self.ICON_WARNING:
                dwInfoFlags = NIIF_WARNING | NIIF_LARGE_ICON
            elif iconOpt == self.ICON_ERROR:
                dwInfoFlags = NIIF_ERROR | NIIF_LARGE_ICON
            elif iconOpt == self.ICON_EG:
                # Get the first icon from the EventGhost executable
                hicon = win32gui.CreateIconFromResource(
                    win32api.LoadResource(None, win32con.RT_ICON, 1), True)
                dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON
            elif isinstance(iconOpt, basestring):
                filename, idx = iconOpt.split(";", 1)
                filename = expandvars(filename)
                dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON
                if filename[-4:].upper() == ".ICO":
                    hicon = win32gui.LoadImage(
                        win32api.GetModuleHandle(None),
                        filename,
                        win32con.IMAGE_ICON,
                        0,
                        0,
                        win32con.LR_LOADFROMFILE | win32con.LR_LOADREALSIZE,
                    )
                else:
                    lib = win32api.LoadLibrary(filename)
                    hicon = win32gui.LoadIcon(lib, int(idx) + 1)
                    win32api.FreeLibrary(lib)
        except Exception as ex:
            eg.PrintError(str(ex))
            hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
            dwInfoFlags = 0x00
        if not sound:
            dwInfoFlags |= NIIF_NOSOUND
        flags = win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP
        nid = (hwnd, 0, flags, WM_TRAYICON, hicon, 'Tooltip')

        # Notify
        win32gui.Shell_NotifyIcon(win32gui.NIM_ADD, nid)
        win32gui.Shell_NotifyIcon(
            win32gui.NIM_MODIFY,
            (hwnd, 0, win32gui.NIF_INFO, WM_TRAYICON, hicon, 'Balloon Tooltip',
             msg, 200, title, dwInfoFlags))
        if hicon is not None:
            win32gui.DestroyIcon(hicon)