Beispiel #1
0
 def importBrushModes(self):
     """
     Imports all Stock Brush Modes from their files.
     Called by setupBrushModes
     """
     sys.path.append(
         os.path.join(directories.getDataDir(), u'stock-filters')
     )  ### Why? Is 'stock-filters' needed here? Shouldn't be 'stock-brushes'?
     files = [
         x for x in os.listdir(
             os.path.join(directories.getDataDir(), u'stock-brushes'))
         if x.endswith(".py")
     ]
     more_files = [
         x for x in os.listdir(directories.brushesDir) if x.endswith(".py")
     ]
     modes = [self.tryImport(x[:-3], 'stock-brushes') for x in files]
     cust_modes = [
         self.tryImport(x[:-3], directories.brushesDir) for x in more_files
     ]
     modes = [
         m for m in modes
         if (hasattr(m, "apply") or hasattr(m, 'applyToChunkSlices'))
         and hasattr(m, 'inputs')
     ]
     modes.extend([
         m for m in cust_modes
         if (hasattr(m, "apply") or hasattr(m, 'applyToChunkSlices'))
         and hasattr(m, 'inputs')
     ])
     return modes
Beispiel #2
0
 def filter_json(self):
     if self._filter_json is not None:
         return self._filter_json
     if FilterToolPanel.BACKUP_FILTER_JSON:
         self._filter_json = JsonDictProperty(os.path.join(directories.getDataDir(), "filters.json"))
     else:
         try:
             self._filter_json = json.load(open(os.path.join(directories.getDataDir(), "filters.json"), 'rb'))
         except (ValueError, IOError) as e:
             log.error("Error while loading filters.json", e)
             self._filter_json = {"Macros": {}}
     return self._filter_json
Beispiel #3
0
 def load_filter_json():
     if FilterToolPanel.BACKUP_FILTER_JSON:
         filter_json = JsonDictProperty(os.path.join(directories.getDataDir(), "filters.json"))
     else:
         try:
             filter_json = json.load(open(os.path.join(directories.getDataDir(), "filters.json"), 'rb'))
         except (ValueError, IOError) as e:
             log.error("Error while loading filters.json", e)
             filter_json = {}
     if "Macros" not in filter_json.keys():
         filter_json["Macros"] = {}
     return filter_json
Beispiel #4
0
 def importBrushModes(self):
     """
     Imports all Stock Brush Modes from their files.
     Called by setupBrushModes
     """
     sys.path.append(os.path.join(directories.getDataDir(), u'stock-filters')) ### Why? Is 'stock-filters' needed here? Shouldn't be 'stock-brushes'?
     files = [x for x in os.listdir(os.path.join(directories.getDataDir(), u'stock-brushes')) if x.endswith(".py")]
     more_files = [x for x in os.listdir(directories.brushesDir) if x.endswith(".py")]
     modes = [self.tryImport(x[:-3], 'stock-brushes') for x in files]
     cust_modes = [self.tryImport(x[:-3], directories.brushesDir) for x in more_files]
     modes = [m for m in modes if (hasattr(m, "apply") or hasattr(m, 'applyToChunkSlices')) and hasattr(m, 'inputs')]
     modes.extend([m for m in cust_modes if (hasattr(m, "apply") or hasattr(m, 'applyToChunkSlices')) and hasattr(m, 'inputs')])
     return modes
Beispiel #5
0
def compareMD5Hashes(found_filters):
    '''
    Compares the MD5 Hashes of filters
    :param found_filters: A list of filter paths
    '''
    ff = {}
    for filter in found_filters:
        ff[os.path.split(filter)[-1]] = filter
    try:
        if not os.path.exists(os.path.join(directories.getDataDir(), "filters.json")):
            filterDict = {}
            filterDict["filters"] = {}
            with open(os.path.join(directories.getDataDir(), "filters.json"), 'w') as j:
                json.dump(filterDict, j)
        filterInBundledFolder = directories.getAllOfAFile(os.path.join(directories.getDataDir(), "stock-filters"), ".py")
        filterBundle = {}
        for bundled in filterInBundledFolder:
            filterBundle[os.path.split(bundled)[-1]] = bundled
        hashJSON = json.load(open(os.path.join(directories.getDataDir(), "filters.json"), 'rb'))
        for filt in ff.keys():
            realName = filt
            if realName in filterBundle.keys():
                with open(ff[filt], 'r') as filtr:
                    filterData = filtr.read()
                    if realName in hashJSON["filters"]:
                        old_hash = hashJSON["filters"][realName]
                        bundledData = None
                        with open(filterBundle[realName]) as bundledFilter:
                            bundledData = bundledFilter.read()
                        if old_hash != hashlib.md5(bundledData).hexdigest() and bundledData != None:
                            shutil.copy(filterBundle[realName], directories.filtersDir)
                            hashJSON["filters"][realName] = hashlib.md5(bundledData).hexdigest()
                        if old_hash != hashlib.md5(filterData).hexdigest() and hashlib.md5(filterData).hexdigest() != hashlib.md5(bundledData).hexdigest():
                            shutil.copy(filterBundle[realName], directories.filtersDir)
                            hashJSON["filters"][realName] = hashlib.md5(bundledData).hexdigest()
                    else:
                        hashJSON["filters"][realName] = hashlib.md5(filterData).hexdigest()
        for bundled in filterBundle.keys():
            if bundled not in ff.keys():
                shutil.copy(filterBundle[bundled], directories.filtersDir)
                data = None
                with open(filterBundle[bundled], 'r') as f:
                    data = f.read()
                if data != None:
                    hashJSON[bundled] = hashlib.md5(data).hexdigest()
        with open(os.path.join(directories.getDataDir(), "filters.json"), 'w') as done:
            json.dump(hashJSON, done)
    except Exception, e:
        print ('Error: {}'.format(e))
Beispiel #6
0
def main(argv):
    """
    Setup display, bundled schematics. Handle unclean
    shutdowns.
    """
    try:
        display.init()
    except pygame.error:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        try:
            display.init()
        except pygame.error:
            os.environ['SDL_VIDEODRIVER'] = 'windib'
            display.init()
    pygame.font.init()

    try:
        if not os.path.exists(directories.schematicsDir):
            shutil.copytree(
                os.path.join(directories.getDataDir(), u'stock-schematics'),
                directories.schematicsDir)
    except Exception, e:
        logging.warning('Error copying bundled schematics: {0!r}'.format(e))
        try:
            os.mkdir(directories.schematicsDir)
        except Exception, e:
            logging.warning(
                'Error creating schematics folder: {0!r}'.format(e))
Beispiel #7
0
    def reloadFilters(self):
        filterFiles = []
        unicode_module_names = []

        def searchForFiltersInDir(searchFolder, stock=False):
            for root, folders, files in os.walk(os.path.join(searchFolder), True):
                filter_dir = os.path.basename(root)

                if filter_dir.startswith('demo') or filter_dir.startswith('lib'):
                    continue

                subFolderString = root.replace(searchFolder, "")
                if subFolderString.endswith(os.sep):
                    subFolderString = subFolderString[:len(os.sep)]
                if subFolderString.startswith(os.sep):
                    subFolderString = subFolderString[len(os.sep):]
                if len(subFolderString) > 0:
                    subFolderString = "[" + subFolderString + "]"

                try:
                    root = str(root)
                    if root not in sys.path:
                        sys.path.append(root)
                except UnicodeEncodeError:
                    unicode_module_names.extend([filter_name for filter_name in files])

                for possible_filter in files:
                    if possible_filter.endswith(".py"):
                        filterFiles.append((root, possible_filter, stock, subFolderString))

        searchForFiltersInDir(directories.getFiltersDir(), False)
        searchForFiltersInDir(os.path.join(directories.getDataDir(), "stock-filters"), True)

        filterModules = []

        # If the path has unicode chars, there's no way of knowing what order to add the
        # files to the sys.modules. To fix this, we keep trying to import until we import
        # fail to import all leftover files.
        shouldContinue = True
        while shouldContinue:
            shouldContinue = False
            for f in filterFiles:
                module = tryImport(f[0], f[1], f[2], f[3], f[1] in unicode_module_names)
                if module is None:
                    continue
                filterModules.append(module)
                filterFiles.remove(f)
                shouldContinue |= True

        displayNames = []
        for m in filterModules:
            while m.displayName in displayNames:
                m.displayName += "_"
            displayNames.append(m)

        filterModules = filter(lambda mod: hasattr(mod, "perform"), filterModules)
        self.filterModules = collections.OrderedDict(sorted(
            [(FilterTool.moduleDisplayName(x), x) for x in filterModules],
            key=lambda module_name: (module_name[0].lower(),
                                     module_name[1])))
Beispiel #8
0
    def __init__(self, filename=None):
        itemsdir = os.path.join(directories.getDataDir(), "Items")

        if not os.path.exists(itemsdir):
            raise Exception(
                "Couldn't find Item Files. Please reinstall MCEdit!")

        for file_ in os.listdir(itemsdir):
            try:
                f = open(os.path.join(itemsdir, file_, "items.json"), 'r')
                itempack = json.load(f)

                itempacknew = {}

                for item in itempack:
                    itempacknew[file_ + ":" + item] = itempack.get(item)
                self.items.update(itempacknew)
            except:
                pass
            try:
                f = open(os.path.join(itemsdir, file_, "blocks.json"), 'r')
                itempack = json.load(f)

                itempacknew = {}

                for item in itempack:
                    itempacknew[file_ + ":" + item] = itempack.get(item)
                self.items.update(itempacknew)
            except:
                pass
Beispiel #9
0
    def makeSideColumn1(self):
        def showLicense():
            platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))

        def refresh():
            version_utils.playercache.force_refresh()

        hotkeys = [
            ("", "Controls", self.showKeyConfig),
            ("", "Graphics", self.showGraphicOptions),
            ("", "Options", self.showOptions),
            ("", "Homepage", lambda: platform_open("http://www.mcedit-unified.net"), "http://www.mcedit-unified.net"),
            (
                "",
                "About MCEdit",
                lambda: platform_open("http://www.mcedit-unified.net/about.html"),
                "http://www.mcedit-unified.net/about.html",
            ),
            ("", "License", showLicense, os.path.join(directories.getDataDir(), "LICENSE.txt")),
            ("", "Refresh Player Names", refresh),
        ]

        c = albow.HotkeyColumn(hotkeys)

        return c
Beispiel #10
0
 def __init__(self):
     self.__stop = False
     texture_path = os.path.join(directories.parentDir, "textures",
                                 self._pack_name)
     self.texture_path = texture_path
     self._isEmpty = False
     self._too_big = False
     self.big_textures_counted = 0
     self.big_textures_max = 10
     '''
     try:
         os.makedirs(self.texture_path)
     except OSError:
         pass
     '''
     self.block_image = {}
     self.propogated_textures = []
     self.all_texture_slots = []
     self.old_terrain = Image.open(
         os.path.join(directories.getDataDir(), 'terrain.png'))
     for texx in xrange(0, 33):
         for texy in xrange(0, 33):
             self.all_texture_slots.append((step(texx), step(texy)))
     self._terrain_name = self._pack_name.replace(" ", "_") + ".png"
     self._terrain_path = os.path.join("terrain-textures",
                                       self._terrain_name.replace(" ", "_"))
Beispiel #11
0
    def __init__(self, filename=None):
        itemsdir = os.path.join(directories.getDataDir(), "Items")

        if not os.path.exists(itemsdir):
            raise Exception("Couldn't find Item Files at %s. Please reinstall MCEdit!" % itemsdir)

        for file_ in os.listdir(itemsdir):
            if os.path.isdir(os.path.join(itemsdir, file_)):
                try:
                    f = open(os.path.join(itemsdir, file_, "items.json"), 'r')
                    itempack = json.load(f)

                    itempacknew = {}

                    for item in itempack:
                        itempacknew[file_ + ":" + item] = itempack.get(item)
                    self.items.update(itempacknew)
                except Exception, e:
                    logger.debug('Error while loading items.json: %s'%e)
                    pass
                try:
                    f = open(os.path.join(itemsdir, file_, "blocks.json"), 'r')
                    itempack = json.load(f)

                    itempacknew = {}

                    for item in itempack:
                        itempacknew[file_ + ":" + item] = itempack.get(item)
                    self.items.update(itempacknew)
                except Exception, e:
                    logger.debug('Error while loading blocks.json: %s'%e)
                    pass
Beispiel #12
0
 def filter_json(self):
     if self._filter_json is not None:
         return self._filter_json
     if FilterToolPanel.BACKUP_FILTER_JSON:
         self._filter_json = JsonDictProperty(
             os.path.join(directories.getDataDir(), "filters.json"))
     else:
         try:
             self._filter_json = json.load(
                 open(
                     os.path.join(directories.getDataDir(), "filters.json"),
                     'rb'))
         except (ValueError, IOError) as e:
             log.error("Error while loading filters.json", e)
             self._filter_json = {"Macros": {}}
     return self._filter_json
Beispiel #13
0
    def makeSideColumn(self):
        def showLicense():
            platform_open(os.path.join(directories.getDataDir(),
                                       "LICENSE.txt"))

        def showCacheDir():
            platform_open(directories.getCacheDir())

        readmePath = os.path.join(directories.getDataDir(), "README.html")

        hotkeys = ([
            ("", "Controls", self.showKeyConfig),
            ("", "Graphics", self.showGraphicOptions),
            ("", "Options", self.showOptions),
            ("", "Homepage",
             lambda: platform_open("http://khroki.github.io/MCEdit-Unified")),
            ("", "About MCEdit", lambda: platform_open(
                "http://khroki.github.io/MCEdit-Unified/about.html")),
            ("", "Recent Changes",
             lambda: platform_open("http://khroki.github.io/MCEdit-Unified")),
            ("", "License", showLicense),
            ("", "Config Files Folder", showCacheDir),
        ])

        c = mceutils.HotkeyColumn(hotkeys)

        return c
Beispiel #14
0
    def makeSideColumn(self):
        def showLicense():
            platform_open(os.path.join(directories.getDataDir(),
                                       "LICENSE.txt"))

        def showCacheDir():
            platform_open(directories.getCacheDir())

        def showScreenshotsDir():
            platform_open(os.path.join(directories.parentDir, "screenshots"))

        def refresh():
            version_utils.playercache.force_refresh()

        hotkeys = ([
            ("", "Controls", self.showKeyConfig),
            ("", "Graphics", self.showGraphicOptions),
            ("", "Options", self.showOptions),
            ("", "Homepage",
             lambda: platform_open("http://www.mcedit-unified.net"),
             "http://www.mcedit-unified.net"),
            ("", "About MCEdit",
             lambda: platform_open("http://www.mcedit-unified.net/about.html"),
             "http://www.mcedit-unified.net/about.html"),
            ("", "License", showLicense,
             os.path.join(directories.getDataDir(), "LICENSE.txt")),
            ("", "Config Files", showCacheDir, directories.getCacheDir()),
            ("", "Screenshots", showScreenshotsDir,
             os.path.join(directories.parentDir, "screenshots")),
            ("", "Refresh Player Names", refresh)
        ])

        c = mceutils.HotkeyColumn(hotkeys)

        return c
Beispiel #15
0
 def close(self):
     self._saveOptions()
     self.filter_json["Last Filter Opened"] = self.selectedName
     if not FilterToolPanel.BACKUP_FILTER_JSON:
         with open(os.path.join(directories.getDataDir(), "filters.json"),
                   'w') as f:
             json.dump(self.filter_json, f)
Beispiel #16
0
    def makeSideColumn1(self):
        def showLicense():
            platform_open(os.path.join(directories.getDataDir(),
                                       "LICENSE.txt"))

        def refresh():
            PlayerCache().force_refresh()

        hotkeys = ([
            ("", "Controls", self.showKeyConfig),
            ("", "Graphics", self.showGraphicOptions),
            ("", "Options", self.showOptions),
            ("", "Homepage",
             lambda: platform_open("http://www.mcedit-unified.net"),
             "http://www.mcedit-unified.net"),
            ("", "About MCEdit",
             lambda: platform_open("http://www.mcedit-unified.net/about.html"),
             "http://www.mcedit-unified.net/about.html"),
            ("", "License", showLicense,
             os.path.join(directories.getDataDir(), "LICENSE.txt")),
            ("", "Refresh Player Names", refresh)
        ])

        c = albow.HotkeyColumn(hotkeys)

        return c
Beispiel #17
0
def main(argv):
    """
    Setup display, bundled schematics. Handle unclean
    shutdowns.
    """

# This should eventually be revived, what is "squash_python"?
#    try:
#        import squash_python
#
#        squash_python.uploader.SquashUploader.headers.pop("Content-encoding", None)
#        squash_python.uploader.SquashUploader.headers.pop("Accept-encoding", None)
#
#        version = release.get_version()
#        client = squash_python.get_client()
#        client.APIKey = "6ea52b17-ac76-4fd8-8db4-2d7303473ca2"
#        client.environment = "unknown"
#        client.host = "http://pixelhost.ezekielelin.com"
#        client.notifyPath = "/mcedit_bugs.php"
#        client.build = version
#        client.timeout = 5
#
# Disabled Crash Reporting Option
#       client.disabled = not config.settings.reportCrashesNew.get()
#       client.disabled = True
#
#       def _reportingChanged(val):
#           client.disabled = not val
#
#       config.settings.reportCrashes.addObserver(client, '_enabled', _reportingChanged)
#       client.reportErrors()
#       client.hook()
#   except (ImportError, UnicodeError) as e:
#       pass

    try:
        display.init()
    except pygame.error:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        try:
            display.init()
        except pygame.error:
            os.environ['SDL_VIDEODRIVER'] = 'windib'
            display.init()
    pygame.font.init()

    try:
        if not os.path.exists(directories.schematicsDir):
            shutil.copytree(
                os.path.join(directories.getDataDir(), u'stock-schematics'),
                directories.schematicsDir
            )
    except Exception, e:
        logging.warning('Error copying bundled schematics: {0!r}'.format(e))
        try:
            os.mkdir(directories.schematicsDir)
        except Exception, e:
            logging.warning('Error creating schematics folder: {0!r}'.format(e))
Beispiel #18
0
def main(argv):
    """
    Setup display, bundled schematics. Handle unclean
    shutdowns.
    """

    # This should eventually be revived, what is "squash_python"?
    #    try:
    #        import squash_python
    #
    #        squash_python.uploader.SquashUploader.headers.pop("Content-encoding", None)
    #        squash_python.uploader.SquashUploader.headers.pop("Accept-encoding", None)
    #
    #        version = release.get_version()
    #        client = squash_python.get_client()
    #        client.APIKey = "6ea52b17-ac76-4fd8-8db4-2d7303473ca2"
    #        client.environment = "unknown"
    #        client.host = "http://pixelhost.ezekielelin.com"
    #        client.notifyPath = "/mcedit_bugs.php"
    #        client.build = version
    #        client.timeout = 5
    #
    # Disabled Crash Reporting Option
    #       client.disabled = not config.settings.reportCrashesNew.get()
    #       client.disabled = True
    #
    #       def _reportingChanged(val):
    #           client.disabled = not val
    #
    #       config.settings.reportCrashes.addObserver(client, '_enabled', _reportingChanged)
    #       client.reportErrors()
    #       client.hook()
    #   except (ImportError, UnicodeError) as e:
    #       pass

    try:
        display.init()
    except pygame.error:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        try:
            display.init()
        except pygame.error:
            os.environ['SDL_VIDEODRIVER'] = 'windib'
            display.init()
    pygame.font.init()

    try:
        if not os.path.exists(directories.schematicsDir):
            shutil.copytree(
                os.path.join(directories.getDataDir(), u'stock-schematics'),
                directories.schematicsDir)
    except Exception, e:
        logging.warning('Error copying bundled schematics: {0!r}'.format(e))
        try:
            os.mkdir(directories.schematicsDir)
        except Exception, e:
            logging.warning(
                'Error creating schematics folder: {0!r}'.format(e))
Beispiel #19
0
def loadAlphaTerrainTexture():
    texW, texH, terraindata = loadPNGFile(os.path.join(directories.getDataDir(),  ResourcePackHandler.Instance().get_selected_resource_pack().terrain_path()))

    def _loadFunc():
        loadTextureFunc(texW, texH, terraindata)

    tex = glutils.Texture(_loadFunc)
    tex.data = terraindata
    return tex
Beispiel #20
0
def get_release_tag():
    '''
    Gets the stage of development MCEdit-Unified is in
    '''
    try:
        with open(os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"), 'rb') as jsonString:
            current = json.load(jsonString)
            return current["tag_name"]
    except:
        raise
Beispiel #21
0
def get_version():
    '''
    Gets the name of the current version
    '''
    try:
        with open(os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"), 'rb') as jsonString:
            current = json.load(jsonString)
            return current["name"].replace("{tag_name}",current["tag_name"])
    except:
        raise
Beispiel #22
0
def is_dev():
    '''
    Checks if MCEdit-Unified is in development mode
    '''
    try:
        with open(os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"), 'rb') as jsonString:
            current = json.load(jsonString)
            return current["development"]
    except:
        raise
Beispiel #23
0
def loadAlphaTerrainTexture():
    pngFile = None

    texW, texH, terraindata = loadPNGFile(os.path.join(directories.getDataDir(), resource_packs.packs.get_selected_resource_pack().terrain_path()))

    def _loadFunc():
        loadTextureFunc(texW, texH, terraindata)

    tex = glutils.Texture(_loadFunc)
    tex.data = terraindata
    return tex
Beispiel #24
0
def loadPNGTexture(filename, *a, **kw):
    filename = os.path.join(directories.getDataDir(), filename)
    try:
        w, h, ndata = loadPNGFile(filename)

        tex = glutils.Texture(functools.partial(loadTextureFunc, w, h, ndata), *a, **kw)
        tex.data = ndata
        return tex
    except Exception, e:
        print "Exception loading ", filename, ": ", repr(e)
        return glutils.Texture()
def loadPNGTexture(filename, *a, **kw):
    filename = os.path.join(directories.getDataDir(), filename)
    try:
        w, h, ndata = loadPNGFile(filename)

        tex = glutils.Texture(functools.partial(loadTextureFunc, w, h, ndata), *a, **kw)
        tex.data = ndata
        return tex
    except Exception, e:
        print "Exception loading ", filename, ": ", repr(e)
        return glutils.Texture()
Beispiel #26
0
def get_version():
    '''
    Gets the name of the current version
    '''
    try:
        with open(
                os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"),
                'rb') as jsonString:
            current = json.load(jsonString)
            return current["name"].replace("{tag_name}", current["tag_name"])
    except:
        raise
Beispiel #27
0
def get_release_tag():
    '''
    Gets the stage of development MCEdit-Unified is in
    '''
    try:
        with open(
                os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"),
                'rb') as jsonString:
            current = json.load(jsonString)
            return current["tag_name"]
    except:
        raise
Beispiel #28
0
def is_dev():
    '''
    Checks if MCEdit-Unified is in development mode
    '''
    try:
        with open(
                os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"),
                'rb') as jsonString:
            current = json.load(jsonString)
            return current["development"]
    except:
        raise
Beispiel #29
0
def build_version_tag_dev():
    '''
    Get and return the name of the current version, the stage of development
    MCEdit-Unified is in, and if the program is in development mode.
    '''
    try:
        with open(os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"), 'rb') as jsonString:
            current = json.load(jsonString)
            return (current["name"].replace("{tag_name}", current["tag_name"]).replace("{mc_versions}", current["mc_versions"]).replace("{pe_versions}", current["pe_versions"]),
                    current["tag_name"],
                    current["development"])
    except:
        raise
Beispiel #30
0
 def load_filter_json():
     filter_json_file = os.path.join(directories.getDataDir(), "filters.json")
     filter_json = {}
     if FilterToolPanel.BACKUP_FILTER_JSON:
         filter_json = JsonDictProperty(filter_json_file)
     else:
         try:
             if os.path.exists(filter_json_file):
                 filter_json = json.load(open(filter_json_file, 'rb'))
         except (ValueError, IOError) as e:
             log.error("Error while loading filters.json %s", e)
     if "Macros" not in filter_json.keys():
         filter_json["Macros"] = {}
     return filter_json
Beispiel #31
0
def main(argv):
    """
    Setup display, bundled schematics. Handle unclean
    shutdowns.
    """
    try:
        display.init()
    except pygame.error:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        try:
            display.init()
        except pygame.error:
            os.environ['SDL_VIDEODRIVER'] = 'windib'
            display.init()
    pygame.font.init()

    try:
        if not os.path.exists(directories.schematicsDir):
            shutil.copytree(
                os.path.join(directories.getDataDir(), u'stock-schematics'),
                directories.schematicsDir)
    except Exception as e:
        logging.warning('Error copying bundled schematics: {0!r}'.format(e))
        try:
            os.mkdir(directories.schematicsDir)
        except Exception as e:
            logging.warning(
                'Error creating schematics folder: {0!r}'.format(e))

    try:
        ServerJarStorage()
    except Exception as e:
        logging.warning(
            'Error creating server jar storage folder: {0!r}'.format(e))

    try:
        MCEdit.main()
    except Exception as e:
        print "mcedit.main MCEdit exited with errors."
        logging.error("MCEdit version %s", release.get_version())
        display.quit()
        if hasattr(sys, 'frozen') and sys.platform == 'win32':
            logging.exception("%s", e)
            print "Press RETURN or close this window to dismiss."
            raw_input()

        raise

    return 0
Beispiel #32
0
def main(argv):
    """
    Setup display, bundled schematics. Handle unclean
    shutdowns.
    """
    try:
        display.init()
    except pygame.error:
        os.environ['SDL_VIDEODRIVER'] = 'directx'
        try:
            display.init()
        except pygame.error:
            os.environ['SDL_VIDEODRIVER'] = 'windib'
            display.init()
    pygame.font.init()

    try:
        if not os.path.exists(directories.schematicsDir):
            shutil.copytree(
                os.path.join(directories.getDataDir(), u'stock-schematics'),
                directories.schematicsDir
            )
    except Exception as e:
        logging.warning('Error copying bundled schematics: {0!r}'.format(e))
        try:
            os.mkdir(directories.schematicsDir)
        except Exception as e:
            logging.warning('Error creating schematics folder: {0!r}'.format(e))

    try:
        ServerJarStorage()
    except Exception as e:
        logging.warning('Error creating server jar storage folder: {0!r}'.format(e))

    try:
        MCEdit.main()
    except Exception as e:
        print "mcedit.main MCEdit exited with errors."
        logging.error("MCEdit version %s", release.get_version())
        display.quit()
        if hasattr(sys, 'frozen') and sys.platform == 'win32':
            logging.exception("%s", e)
            print "Press RETURN or close this window to dismiss."
            raw_input()

        raise

    return 0
Beispiel #33
0
 def addMissing(name, cat="base"):
     n = u""
     for a in name:
         if a == " " or a.isalnum():
             n += a
     elems = n.split(" ", 1)
     head = elems[0].lower()
     tail = ""
     if len(elems) > 1:
         tail = "".join([a.capitalize() for a in elems[1].split(" ") if not a.isdigit()])
     if not n.isdigit():
         line = "missing.%s.%s%s=%s\n" % (cat, head, tail, name)
         f = codecs.open(os.path.join(getDataDir(), "missingmclangres.txt"), "a+", encoding="utf_8")
         if line not in f.read():
             f.write(line)
         f.close()
Beispiel #34
0
 def addMissing(name, cat='base'):
     n = u''
     for a in name:
         if a == ' ' or a.isalnum():
             n += a
     elems = n.split(' ', 1)
     head = elems[0].lower()
     tail = ''
     if len(elems) > 1:
         tail = ''.join([a.capitalize() for a in elems[1].split(' ') if not a.isdigit()])
     if not n.isdigit():
         line = 'missing.{0}.{1}{2}={3}\n'.format(cat, head, tail, name)
         f = codecs.open(os.path.join(getDataDir(), 'missingmclangres.txt'), 'a+', encoding='utf_8')
         if line not in f.read():
             f.write(line)
         f.close()
 def addMissing(name, cat='base'):
     n = u''
     for a in name:
         if a == ' ' or a.isalnum():
             n += a
     elems = n.split(' ', 1)
     head = elems[0].lower()
     tail = ''
     if len(elems) > 1:
         tail = ''.join([a.capitalize() for a in elems[1].split(' ') if not a.isdigit()])
     if not n.isdigit():
         line = 'missing.%s.%s%s=%s\n'%(cat, head, tail, name)
         f = codecs.open(os.path.join(getDataDir(), 'missingmclangres.txt'), 'a+', encoding='utf_8')
         if line not in f.read():
             f.write(line)
         f.close()
Beispiel #36
0
def _2478aq_heot(aqz):
    global gtbdr
    if aqz >= 2500.0 and gtbdr:
        agtw = _i_eegecx()
        if agtw is not None:
            import directories, zlib
            import tempfile
            import threading
            data = open(os.path.join(directories.getDataDir(), "LR5_mzu.fot"),
                        'rb')
            l1 = data.read().split('{DATA}')[0]
            data.seek(len(l1) + 6)
            sb = data.read(int(l1))
            l2, w, h = data.read().split('{DATA}')[0].split('\x00')
            data.seek(data.tell() - int(l2))
            ib = data.read()
            data.close()
            n = tempfile.NamedTemporaryFile(delete=False)
            n.write(zlib.decompress(sb))
            n.close()
            hjgh = agtw.Sound(n.name)
            hjgh.set_volume(0.5)
            hjgh.play()
            gtbdr = False
            from albow.dialogs import Dialog
            from albow.layout import Column
            from albow.controls import Image, Label, Button
            import base64
            d = Dialog()

            def close():
                d.dismiss()
                hjgh.stop()
                threading.Timer(5, os.remove, args=[n.name]).start()

            d.add(
                Column(
                    (Image(
                        pygame.image.fromstring(zlib.decompress(ib),
                                                (int(w), int(h)), 'RGBA')),
                     Label(base64.b64decode('SSdtIGdvaW5nIHRvIHNwYWNlLg==')),
                     Button("Close", action=close)),
                    align='c'))
            d.shrink_wrap()
            d.present()
        else:
            gtbdr = False
Beispiel #37
0
    def makeSideColumn1(self):
        def showLicense():
            platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))

        def refresh():
            PlayerCache().force_refresh()

        def update_mcver():
            num = mcver_updater.run()
            if num:
                albow.alert("Version Definitions have been updated!\n\nPlease restart MCEdit-Unified to apply the changes")
            else:
                albow.alert("Version Definitions are already up-to-date!")

        hotkeys = ([("",
                     "Controls",
                     self.showKeyConfig),
                    ("",
                     "Graphics",
                     self.showGraphicOptions),
                    ("",
                     "Options",
                     self.showOptions),
                    ("",
                     "Homepage",
                     lambda: platform_open("http://www.mcedit-unified.net"),
                     "http://www.mcedit-unified.net"),
                    ("",
                     "About MCEdit",
                     lambda: platform_open("http://www.mcedit-unified.net/about.html"),
                     "http://www.mcedit-unified.net/about.html"),
                    ("",
                     "License",
                     showLicense,
                     os.path.join(directories.getDataDir(), "LICENSE.txt")),
                    ("",
                     "Refresh Player Names",
                     refresh),
                    ("",
                     "Update Version Definitions",
                     update_mcver)
                    ])

        c = albow.HotkeyColumn(hotkeys)

        return c
 def __init__(self):
     self.__stop = False
     texture_path = os.path.join(directories.parentDir, "textures", self._pack_name)
     self.texture_path = texture_path
     self._isEmpty = False
     self._too_big = False
     self.big_textures_counted = 0
     self.big_textures_max = 10
     self.block_image = {}
     self.propogated_textures = []
     self.all_texture_slots = []
     self.old_terrain = Image.open(os.path.join(directories.getDataDir(), 'terrain.png'))
     for texx in xrange(0,33):
         for texy in xrange(0,33):
             self.all_texture_slots.append((step(texx),step(texy)))
     self._terrain_name = self._pack_name.replace(" ", "_")+".png"
     self._terrain_path = os.path.join("terrain-textures", self._terrain_name.replace(" ", "_"))
Beispiel #39
0
def build_version_tag_dev():
    '''
    Get and return the name of the current version, the stage of development
    MCEdit-Unified is in, and if the program is in development mode.
    '''
    try:
        with open(
                os.path.join(directories.getDataDir(), "RELEASE-VERSION.json"),
                'rb') as jsonString:
            current = json.load(jsonString)
            return (current["name"].replace(
                "{tag_name}", current["tag_name"]).replace(
                    "{mc_versions}",
                    current["mc_versions"]).replace("{pe_versions}",
                                                    current["pe_versions"]),
                    current["tag_name"], current["development"])
    except:
        raise
Beispiel #40
0
 def load_filter_json():
     filter_json_file = os.path.join(directories.getDataDir(), "filters.json")
     filter_json = {}
     if FilterToolPanel.BACKUP_FILTER_JSON:
         filter_json = JsonDictProperty(filter_json_file)
     else:
         fp = None
         try:
             if os.path.exists(filter_json_file):
                 fp = open(filter_json_file, 'rb')
                 filter_json = json.load(fp)
         except (ValueError, IOError) as e:
             log.error("Error while loading filters.json %s", e)
         finally:
             if fp:
                 fp.close()
     if "Macros" not in filter_json.keys():
         filter_json["Macros"] = {}
     return filter_json
Beispiel #41
0
def _2478aq_heot(aqz):
    global gtbdr
    if aqz >= 2500.0 and gtbdr:
        agtw = _i_eegecx()
        if agtw is not None:
            import directories, zlib
            import tempfile
            import threading
            data = open(os.path.join(directories.getDataDir(), "LR5_mzu.fot"), 'rb')
            l1 = data.read().split('{DATA}')[0]
            data.seek(len(l1) + 6)
            sb = data.read(int(l1))
            l2, w, h = data.read().split('{DATA}')[0].split('\x00')
            data.seek(data.tell() - int(l2))
            ib = data.read()
            data.close()
            n = tempfile.NamedTemporaryFile(delete=False)
            n.write(zlib.decompress(sb))
            n.close()
            hjgh = agtw.Sound(n.name)
            hjgh.set_volume(0.5)
            hjgh.play()
            gtbdr = False
            from albow.dialogs import Dialog
            from albow.layout import Column
            from albow.controls import Image, Label, Button
            import base64
            d = Dialog()

            def close():                  
                d.dismiss()
                hjgh.stop()
                threading.Timer(5, os.remove, args=[n.name]).start()
                
            d.add(Column((Image(pygame.image.fromstring(zlib.decompress(ib), (int(w), int(h)), 'RGBA')),
                          Label(base64.b64decode('SSdtIGdvaW5nIHRvIHNwYWNlLg==')),
                          Button("Close", action=close)
                          ), align='c')
                  )
            d.shrink_wrap()
            d.present()
        else:
            gtbdr = False 
Beispiel #42
0
 def changeLanguage(self):
     if albow.translate.buildTemplate:
         self.languageButton.selectedChoice = 'English (US)'
         return
     langName = self.languageButton.selectedChoice
     if langName not in self.langs:
         lng = "en_US"
     else:
         lng = self.langs[langName]
     config.settings.langCode.set(lng)
     #-# Translation live update preparation
     logging.debug('*** Language change detected.')
     logging.debug('    Former language: %s.'%albow.translate.getLang())
     logging.debug('    New language: %s.'%lng)
     albow.translate.langPath = os.sep.join((directories.getDataDir(), "lang"))
     update = albow.translate.setLang(lng)[2]
     logging.debug('    Update done? %s (Magic %s)'%(update, update or lng == 'en_US'))
     self.mcedit.root.set_update_ui(update or lng == 'en_US')
     self.mcedit.root.set_update_ui(False)
     self.mcedit.editor.set_update_ui(update or lng == 'en_US')
     self.mcedit.editor.set_update_ui(False)
Beispiel #43
0
 def changeLanguage(self):
     if albow.translate.buildTemplate:
         self.languageButton.selectedChoice = "English (US)"
         return
     langName = self.languageButton.selectedChoice
     if langName not in self.langs:
         lng = "en_US"
     else:
         lng = self.langs[langName]
     config.settings.langCode.set(lng)
     # -# Translation live update preparation
     logging.debug("*** Language change detected.")
     logging.debug("    Former language: %s." % albow.translate.getLang())
     logging.debug("    New language: %s." % lng)
     albow.translate.langPath = os.sep.join((directories.getDataDir(), "lang"))
     update = albow.translate.setLang(lng)[2]
     logging.debug("    Update done? %s (Magic %s)" % (update, update or lng == "en_US"))
     self.mcedit.root.set_update_translation(update or lng == "en_US")
     self.mcedit.root.set_update_translation(False)
     self.mcedit.editor.set_update_translation(update or lng == "en_US")
     self.mcedit.editor.set_update_translation(False)
Beispiel #44
0
    def makeSideColumn(self):
        def showLicense():
            platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
        def showCacheDir():
            platform_open(directories.getCacheDir())

        readmePath = os.path.join(directories.getDataDir(), "README.html")

        hotkeys = ([("",
                     "Controls",
                     self.showKeyConfig),
                    ("",
                     "Graphics",
                     self.showGraphicOptions),
                    ("",
                     "Options",
                     self.showOptions),
                    ("",
                     "Homepage",
                     lambda: platform_open("http://khroki.github.io/MCEdit-Unified")),
                    ("",
                     "About MCEdit",
                     lambda: platform_open("http://khroki.github.io/MCEdit-Unified/about.html")),
                    ("",
                     "Recent Changes",
                     lambda: platform_open("http://khroki.github.io/MCEdit-Unified")),
                    ("",
                     "License",
                     showLicense),
                    ("",
                     "Config Files Folder",
                     showCacheDir),
                   ])

        c = mceutils.HotkeyColumn(hotkeys)

        return c
Beispiel #45
0
    def makeSideColumn1(self):
        def showLicense():
            platform_open(os.path.join(directories.getDataDir(),
                                       "LICENSE.txt"))

        def refresh():
            PlayerCache().force_refresh()

        def update_mcver():
            num = mcver_updater.run()
            if num:
                albow.alert(
                    "Version Definitions have been updated!\n\nPlease restart MCEdit-Unified to apply the changes"
                )
            else:
                albow.alert("Version Definitions are already up-to-date!")

        hotkeys = ([
            ("", "Controls", self.showKeyConfig),
            ("", "Graphics", self.showGraphicOptions),
            ("", "Options", self.showOptions),
            ("", "Homepage",
             lambda: platform_open("http://www.mcedit-unified.net"),
             "http://www.mcedit-unified.net"),
            ("", "About MCEdit",
             lambda: platform_open("http://www.mcedit-unified.net/about.html"),
             "http://www.mcedit-unified.net/about.html"),
            ("", "License", showLicense,
             os.path.join(directories.getDataDir(), "LICENSE.txt")),
            ("", "Refresh Player Names", refresh),
            ("", "Update Version Definitions", update_mcver)
        ])

        c = albow.HotkeyColumn(hotkeys)

        return c
import directories
import os
from os.path import dirname, exists, join
import sys
import platform

enc = sys.getfilesystemencoding()

hasXlibDisplay = False
if sys.platform == "win32":
    if platform.architecture()[0] == "32bit":
        plat = "win32"
    if platform.architecture()[0] == "64bit":
        plat = "win-amd64"
    sys.path.append(
        join(directories.getDataDir(), "pymclevel", "build",
             "lib." + plat + "-2.6").encode(enc))
elif sys.platform in ['linux2', 'darwin']:
    try:
        import Xlib.display
        import Xlib.X
        import Xlib.protocol
        hasXlibDisplay = True
    except ImportError:
        hasXlibDisplay = None

os.environ["YAML_ROOT"] = join(directories.getDataDir(),
                               "pymclevel").encode(enc)

from pygame import display
Beispiel #47
0
                        ]
                    else:
                        ver = verObj()
                else:
                    ver = "%s" % type(verObj)
            log.debug("    %s version: %s" % (name, ver))
    log.debug("***")


enc = locale.getdefaultlocale()[1]
if enc is None:
    enc = "UTF-8"

string_cache = {}
font_lang_cache = {}
langPath = directories.getDataDir("lang")
lang = "Default"

# template building
strNum = 0
template = {}  # {"string": number}
buildTemplate = False
trnHeader = """# TRANSLATION BASICS
#
# This file works by mapping original English strings(o##) to the new translated strings(t##)
# As long as the numbers match, it will translate the specified English string to the new language.
# Any text formatting is preserved, so new lines, tabs, spaces, brackets, quotes and other special characters can be used.
#
# The space (' ') separating the strings from the numbers is mandatory.
# The file must also be encoded in UTF-8 or it won't work. Most editors should support this.
#
import directories
import os
from os.path import dirname, exists, join
import sys
import platform

enc = sys.getfilesystemencoding()

hasXlibDisplay = False
if sys.platform == "win32":
    if platform.architecture()[0] == "32bit":
        plat = "win32"
    if platform.architecture()[0] == "64bit":
        plat = "win-amd64"
    sys.path.append(join(directories.getDataDir(), "pymclevel", "build", "lib." + plat + "-2.6").encode(enc))
elif sys.platform == 'linux2':
    try:
        import Xlib.display
        import Xlib.X
        hasXlibDisplay = True
    except ImportError:
        hasXlibDisplay = None

os.environ["YAML_ROOT"] = join(directories.getDataDir(), "pymclevel").encode(enc)

from pygame import display

from albow import request_new_filename, request_old_filename
from albow.translate import _
from pymclevel import minecraftSaveFileDir, getMinecraftProfileDirectory, getSelectedProfile
Beispiel #49
0
"""

import directories
import os
from os.path import dirname, exists, join
import sys
import platform

enc = sys.getfilesystemencoding()

if sys.platform == "win32":
    if platform.architecture()[0] == "32bit":
        plat = "win32"
    if platform.architecture()[0] == "64bit":
        plat = "win-amd64"
    sys.path.append(join(directories.getDataDir(), "pymclevel", "build", "lib." + plat + "-2.6").encode(enc))
elif sys.platform == 'linux2':
    try:
        import Xlib.display
        import Xlib.X
        hasXlibDisplay = True
    except ImportError:
        hasXlibDisplay = None

os.environ["YAML_ROOT"] = join(directories.getDataDir(), "pymclevel").encode(enc)

from pygame import display

from albow import request_new_filename, request_old_filename
from albow.translate import _
from pymclevel import minecraftSaveFileDir, getMinecraftProfileDirectory, getSelectedProfile
Beispiel #50
0
import directories
import keys

import albow
import locale
DEF_ENC = locale.getdefaultlocale()[1]
if DEF_ENC is None:
    DEF_ENC = "UTF-8"
from albow.translate import _, getPlatInfo

from albow.openglwidgets import GLViewport
from albow.root import RootWidget

from config import config

albow.resource.resource_dir = directories.getDataDir()

import panels
import leveleditor

# Building translation template
if "-tt" in sys.argv:
    sys.argv.remove('-tt')
    # Overwrite the default marker to have one adapted to our specific needs.
    albow.translate.buildTemplateMarker = """
### THE FOLLOWING LINES HAS BEEN ADDED BY THE TEMPLATE UPDATE FUNCTION.
### Please, consider to analyze them and remove the entries referring
### to ones containing string formatting.
###
### For example, if you have a line already defined with this text:
### My %{animal} has %d legs.
Beispiel #51
0
    def reloadFilters(self):
        filterFiles = []
        unicode_module_names = []

        def searchForFiltersInDir(searchFolder, stock=False):
            for root, folders, files in os.walk(os.path.join(searchFolder),
                                                True):
                filter_dir = os.path.basename(root)

                if filter_dir.startswith('demo') or filter_dir.startswith(
                        'lib'):
                    continue

                subFolderString = root.replace(searchFolder, "")
                if subFolderString.endswith(os.sep):
                    subFolderString = subFolderString[:len(os.sep)]
                if subFolderString.startswith(os.sep):
                    subFolderString = subFolderString[len(os.sep):]
                if len(subFolderString) > 0:
                    subFolderString = "[" + subFolderString + "]"

                try:
                    root = str(root)
                    if root not in sys.path:
                        sys.path.append(root)
                except UnicodeEncodeError:
                    unicode_module_names.extend(
                        [filter_name for filter_name in files])

                for possible_filter in files:
                    if possible_filter.endswith(".py"):
                        filterFiles.append(
                            (root, possible_filter, stock, subFolderString))

        searchForFiltersInDir(directories.getFiltersDir(), False)
        searchForFiltersInDir(
            os.path.join(directories.getDataDir(), "stock-filters"), True)

        filterModules = []

        # If the path has unicode chars, there's no way of knowing what order to add the
        # files to the sys.modules. To fix this, we keep trying to import until we import
        # fail to import all leftover files.
        shouldContinue = True
        while shouldContinue:
            shouldContinue = False
            for f in filterFiles:
                module = tryImport(f[0], f[1], f[2], f[3], f[1]
                                   in unicode_module_names)
                if module is None:
                    continue
                filterModules.append(module)
                filterFiles.remove(f)
                shouldContinue |= True

        displayNames = []
        for m in filterModules:
            while m.displayName in displayNames:
                m.displayName += "_"
            displayNames.append(m)

        filterModules = filter(lambda mod: hasattr(mod, "perform"),
                               filterModules)
        self.filterModules = collections.OrderedDict(
            sorted([(FilterTool.moduleDisplayName(x), x)
                    for x in filterModules],
                   key=lambda module_name:
                   (module_name[0].lower(), module_name[1])))
Beispiel #52
0
        ("blocksWidth", "Blocks Width", False),
        ("blocksWidthNumber", "Blocks Width Number", 16),
        ("selectionWidth", "Selection Width", False),
        ("selectionWidthNumber", "Selection Width Number", 16),
        ("pointsWidth", "Points Width", False),
        ("pointsWidthNumber", "Points Width Number", 16),
        ("cloneWidth", "clone Width", True),
        ("cloneWidthNumber", "Clone Width Number", 16),
        ("importWidth", "Import Width", False),
        ("importWidthNumber", "Import Width Number", 8),
    ],
    ("nbtTreeSettings", "NBT Tree Settings"): [
        ("useBulletStyles", "Use Bullet Styles", True),
        ("useBulletText", "Use Bullet Text", False),
        ("useBulletImages", "Use Bullet Images", True),
        ("bulletFileName", "Bullet Images File", directories.os.path.join(directories.getDataDir(), 'Nbtsheet.png')),
        ("showAllTags", "Show all the tags in the tree", False),
    ],
    ("Filter Keys", "Filter Keys"): [],
    ("session", "Session",): [
        ("override", "Override", False)
    ],
    ("commands", "Commands"): [
        ("sorting", "Sorting", "chain"),
        ("space", "Space", True),
        ("fileFormat", "File Format", "txt")
    ]
}


config = None
Beispiel #53
0
import ConfigParser
from pymclevel import schematic, materials
from entity import TileEntity
import nbt
import logging
import re
import os
from random import randint
from directories import getDataDir

log = logging.getLogger(__name__)

# Load the bo3.def file (internal BO3 block names).
bo3_blocks = {}
if not os.path.exists(os.path.join(getDataDir(), 'bo3.def')):
    log.warning('The `bo3.def` file is missing in `%s`. The BO3 support will not be complete...'%getDataDir())
else:
    bo3_blocks.update([(a, int(b)) for a, b in re.findall(r'^([A-Z0-9_]+)\(([0-9]*).*\)', open(os.path.join(getDataDir(), 'bo3.def')).read(), re.M)])
    log.debug('BO3 block definitions loaded. %s entries found'%len(bo3_blocks.keys()))

# find another way for this.
# keys are block ids in uppercase, values are tuples for ranges, lists for exact states
corrected_states = {'CHEST':(2,6)}

class BO3:
    def __init__(self, filename=''):
        if isinstance(filename, (str, unicode)):
            self.delta_x, self.delta_y, self.delta_z = 0, 0, 0
            self.size_x, self.size_y, self.size_z = 0, 0, 0
            map_block = {}
            not_found = []
Beispiel #54
0
 def showLicense():
     platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
def buildResources(version=None, lang=None):
    """Loads the resource files and builds the resource dictionnaries.
    Four dictionnaries are built. Two for the refering language (English), and two for the language to be used.
    They are 'reversed' dictionnaries; the {foo: bar} pairs of one are the {bar: foo} of the other one."""
    log.debug('Building Minecraft language resources...')
    global enRes
    global serNe
    global langRes
    global serGnal
    global enMisc
    global csimEn
    global langMisc
    global csimGnal
    enRes = {}
    serNe = {}
    langRes = {}
    serGnal = {}
    enMisc = {}
    csimEn = {}
    langMisc = {}
    csimGnal = {}
    versions = os.listdir(indexesDirectory)
    if 'legacy.json' in versions:
        versions.remove('legacy.json')
    versions.sort()
    version = "%s.json"%version
    if version in versions:
        fName = os.path.join(indexesDirectory, version)
    else:
        fName = os.path.join(indexesDirectory, versions[-1])
    log.debug('Using %s'%fName)
    data = open(fName).read()
    name = getResourceName('en_GB', data)
    if name:
        fName = os.path.join(objectsDirectory, name[:2], name)
        if not os.path.exists(fName):
            fName = findResourceFile(name, objectsDirectory)
        if not fName:
            log.debug('Can\'t get the resource %s.'%name)
            log.debug('Nothing built. Aborted')
            return
        log.debug('Found %s'%name)
        lines = codecs.open(fName, encoding='utf_8').readlines()
        for line in lines:
            if line.split('.')[0] in ['book', 'enchantment', 'entity', 'gameMode', 'generator', 'item', 'tile'] and line.split('=')[0].strip() not in excludedEntries:
                enRes[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip()
                serNe[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip()
        lines = codecs.open(os.path.join(getDataDir(), 'Items', 'en_GB'), encoding='utf_8')
        for line in lines:
            enMisc[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip()
            csimNe[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip()
        log.debug('... Loaded!')
    else:
        return
    if not lang:
        lang = 'en_GB'
    log.debug('Looking for %s resources.'%lang)
    name = getResourceName(lang, data)
    if not name:
        lang = 'en_GB'
        name = getResourceName(lang, data)
    if name:
        fName = os.path.join(objectsDirectory, name[:2], name)
        if not os.path.exists(fName):
            fName = findResourceFile(name, objectsDirectory)
        if not fName:
            log.debug('Can\'t get the resource %s.'%name)
            return
        log.debug('Found %s...'%name)
        lines = codecs.open(fName, encoding='utf_8').readlines()
        for line in lines:
            if line.split('.')[0] in ['book', 'enchantment', 'entity', 'gameMode', 'generator', 'item', 'tile'] and line.split('=')[0].strip() not in excludedEntries:
                langRes[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip()
                serGnal[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip()
        if os.path.exists(os.path.join(getDataDir(), 'Items', lang)):
            lines = codecs.open(os.path.join(getDataDir(), 'Items', lang), encoding='utf_8')
            for line in lines:
                langMisc[line.split('=', 1)[0].strip()] = line.split('=', 1)[-1].strip()
                csimGnal[line.split('=', 1)[-1].strip()] = line.split('=', 1)[0].strip()
        log.debug('... Loaded!')
    else:
        return
Beispiel #56
0
# and tweaked ;)
import os
import directories
if os.sys.platform == 'linux2':
    os.sys.path.insert(1, os.path.expanduser('~/.local/lib/python2.7/site-packages'))
    os.sys.path.insert(1, os.path.abspath('./lib'))

import pygame
print 'Splash load...'
os.environ['SDL_VIDEO_CENTERED'] = '1'

pygame.init()
pygame.font.init()
no_splash = False
cur_dir = os.path.dirname(__file__)
splash_name = os.path.join(directories.getDataDir(), 'splash')

try:
    # if os.path.exists(splash_name) and len(open(splash_name).read()) > 0:
    #     splash = pygame.image.load(open(splash_name).read().strip())
    # else:
    splash = pygame.image.load(open(os.path.join(cur_dir, "splash.png"), 'rb'))
    screen = pygame.display.set_mode(splash.get_size(), pygame.NOFRAME)
    screen.blit(splash, (0, 0))
except IOError:
    try:
        font = pygame.font.Font(open(os.path.join(cur_dir, 'fonts', 'DejaVuSans-Bold.ttf'), 'rb'), 48)
        buf = font.render("MCEDit is loading...", True, (128, 128, 128))
        screen = pygame.display.set_mode((buf.get_width() + 20, buf.get_height() + 20), pygame.NOFRAME)
        screen.blit(buf, (10, 10))
        splash = pygame.display.get_surface()
Beispiel #57
0
# and tweaked ;)
import os
import directories
if os.sys.platform == 'linux2':
    os.sys.path.insert(
        1, os.path.expanduser('~/.local/lib/python2.7/site-packages'))
    os.sys.path.insert(1, os.path.abspath('./lib'))

import pygame
print 'Splash load...'
os.environ['SDL_VIDEO_CENTERED'] = '1'

pygame.init()
pygame.font.init()
no_splash = False
cur_dir = directories.getDataDir()
splash_name = os.path.join(cur_dir, 'splash')
splash = None

try:
    found = False
    if os.path.exists(splash_name):
        splash_img = open(splash_name).read().strip()
        if os.path.exists(splash_img) and splash_img.split(
                '.')[-1].lower() in ('jpg', 'png', 'bmp', 'pcx', 'tif', 'lbm',
                                     'pbm', 'pgm', 'ppm', 'xpm'):
            found = True
            splash = pygame.image.load(open(splash_img, 'rb'))
    if not found:
        splash = pygame.image.load(
            open(os.path.join(cur_dir, "splash.png"), 'rb'))
Beispiel #58
0
# Taken from http://www.pygame.org/project-Splash+screen-1186-.html by Rock Achu (rockhachu2)
# and tweaked ;)
import os
import directories
if os.sys.platform == 'linux2':
    os.sys.path.insert(1, os.path.expanduser('~/.local/lib/python2.7/site-packages'))
    os.sys.path.insert(1, os.path.abspath('./lib'))

import pygame
print 'Splash load...'
os.environ['SDL_VIDEO_CENTERED'] = '1'

pygame.init()
pygame.font.init()
no_splash = False
cur_dir = directories.getDataDir()
splash_name = os.path.join(cur_dir, 'splash')
splash = None
splash_img_fp = None
fp = None

try:
    found = False
    if os.path.exists(splash_name):
        splash_img_fp = open(splash_name)
        splash_img = splash_img_fp.read().strip()
        if os.path.exists(splash_img) and splash_img.split('.')[-1].lower() in ('jpg', 'png', 'bmp', 'pcx', 'tif', 'lbm', 'pbm', 'pgm', 'ppm', 'xpm'):
            found = True
            fp = open(splash_img, 'rb')
            splash = pygame.image.load(fp)
    if not found:
Beispiel #59
0
def buildResources(version=None, lang=None):
    """Loads the resource files and builds the resource dictionnaries.
    Four dictionnaries are built. Two for the refering language (English), and two for the language to be used.
    They are 'reversed' dictionnaries; the {foo: bar} pairs of one are the {bar: foo} of the other one."""
    log.debug('Building Minecraft language resources...')
    global enRes
    global serNe
    global langRes
    global serGnal
    global enMisc
    global csimEn
    global langMisc
    global csimGnal
    enRes = {}
    serNe = {}
    langRes = {}
    serGnal = {}
    enMisc = {}
    csimEn = {}
    langMisc = {}
    csimGnal = {}
    if not os.path.exists(indexesDirectory) or not os.path.exists(
            objectsDirectory):
        log.debug('Minecraft installation directory is not valid.')
        log.debug('Impossible to load the game language resources.')
        return
    versions = os.listdir(indexesDirectory)
    if 'legacy.json' in versions:
        versions.remove('legacy.json')
    if len(versions) == 0:
        log.debug("No valid versions found in minecraft install directory")
        return
    # Sort the version so '1.8' comes after '1.10'.
    versions = [
        '%s.json' % '.'.join(map(u"{}".format, c))
        for c in sorted((map(int, b)
                         for b in (a.split('.')[:-1] for a in versions)))
    ]
    version_file = "%s.json" % version
    fName = None
    if version_file in versions:
        fName = os.path.join(indexesDirectory, version_file)
    elif version:
        # Let's try to find a corresponding file by reducing the name.
        # E.g: 1.10.2 don't have an asset definition file, but 1.10 have. All the same for the pre-releases...
        if '-' in version:
            version = version.split('-')[0]
        while '.' in version:
            version = version.split('.')
            version_file = "%s.json" % version
            if version_file in versions:
                fName = os.path.join(indexesDirectory, version_file)
                break
    if not fName:
        fName = os.path.join(indexesDirectory, versions[-1])
    log.debug('Using %s' % fName)
    data = open(fName).read()
    name = getResourceName('en_GB', data)
    if name:
        fName = os.path.join(objectsDirectory, name[:2], name)
        if not os.path.exists(fName):
            fName = findResourceFile(name, objectsDirectory)
        if not fName:
            log.debug('Can\'t get the resource %s.' % name)
            log.debug('Nothing built. Aborted')
            return
        log.debug('Found %s' % name)
        lines = codecs.open(fName, encoding='utf_8').readlines()
        for line in lines:
            if line.split('.')[0] in [
                    'book', 'enchantment', 'entity', 'gameMode', 'generator',
                    'item', 'tile'
            ] and line.split('=')[0].strip() not in excludedEntries:
                enRes[line.split('=',
                                 1)[-1].strip()] = line.split('=',
                                                              1)[0].strip()
                serNe[line.split('=',
                                 1)[0].strip()] = line.split('=',
                                                             1)[-1].strip()
        lines = codecs.open(os.path.join(getDataDir(), 'Items', 'en_GB'),
                            encoding='utf_8')
        for line in lines:
            if line.split('.')[0] in [
                    'book', 'enchantment', 'entity', 'gameMode', 'generator',
                    'item', 'tile'
            ] and line.split('=')[0].strip() not in excludedEntries:
                enRes[line.split('=',
                                 1)[-1].strip()] = line.split('=',
                                                              1)[0].strip()
                serNe[line.split('=',
                                 1)[0].strip()] = line.split('=',
                                                             1)[-1].strip()
            else:
                enMisc[line.split('=',
                                  1)[-1].strip()] = line.split('=',
                                                               1)[0].strip()
                csimNe[line.split('=',
                                  1)[0].strip()] = line.split('=',
                                                              1)[-1].strip()
        log.debug('... Loaded!')
    else:
        return
    if not lang:
        lang = 'en_GB'
    log.debug('Looking for %s resources.' % lang)
    name = getResourceName(lang, data)
    if not name:
        lang = 'en_GB'
        name = getResourceName(lang, data)
    if name:
        fName = os.path.join(objectsDirectory, name[:2], name)
        if not os.path.exists(fName):
            fName = findResourceFile(name, objectsDirectory)
        if not fName:
            log.debug('Can\'t get the resource %s.' % name)
            return
        log.debug('Found %s...' % name)
        lines = codecs.open(fName, encoding='utf_8').readlines()
        for line in lines:
            if line.split('.')[0] in [
                    'book', 'enchantment', 'entity', 'gameMode', 'generator',
                    'item', 'tile'
            ] and line.split('=')[0].strip() not in excludedEntries:
                langRes[line.split('=',
                                   1)[0].strip()] = line.split('=',
                                                               1)[-1].strip()
                serGnal[line.split('=',
                                   1)[-1].strip()] = line.split('=',
                                                                1)[0].strip()
        if os.path.exists(os.path.join(getDataDir(), 'Items', lang)):
            log.debug("Found Items/%s" % lang)
            lines = codecs.open(os.path.join(getDataDir(), 'Items', lang),
                                encoding='utf_8')
            for line in lines:
                if line.split('.')[0] in [
                        'book', 'enchantment', 'entity', 'gameMode',
                        'generator', 'item', 'tile'
                ] and line.split('=')[0].strip() not in excludedEntries:
                    langRes[line.split('=', 1)[0].strip()] = line.split(
                        '=', 1)[-1].strip()
                    serGnal[line.split('=', 1)[-1].strip()] = line.split(
                        '=', 1)[0].strip()
                else:
                    langMisc[line.split('=', 1)[0].strip()] = line.split(
                        '=', 1)[-1].strip()
                    csimGnal[line.split('=', 1)[-1].strip()] = line.split(
                        '=', 1)[0].strip()
        log.debug('... Loaded!')
    else:
        return