Пример #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'?
     sys.path.append(directories.getDataFile('stock-filters'))
     # files = [x for x in os.listdir(os.path.join(directories.getDataDir(), u'stock-brushes')) if x.endswith(".py")]
     files = [
         x for x in os.listdir(directories.getDataFile('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
Пример #2
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'?
     sys.path.append(directories.getDataFile('stock-filters'))
     #files = [x for x in os.listdir(os.path.join(directories.getDataDir(), u'stock-brushes')) if x.endswith(".py")]
     files = [x for x in os.listdir(directories.getDataFile('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
Пример #3
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:
         with open(directories.getDataFile('filters.json'), 'w') as f:
             json.dump(self.filter_json, f)
Пример #4
0
    def __init__(self, filename=None):
        # itemsdir = os.path.join(directories.getDataDir(), "Items")
        itemsdir = directories.getDataFile('Items')

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

        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 as 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 as e:
                    logger.debug('Error while loading blocks.json: %s' % e)
                    pass
Пример #5
0
    def __init__(self, filename=None):
        #itemsdir = os.path.join(directories.getDataDir(), "Items")
        itemsdir = directories.getDataFile('Items')

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

        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 as 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 as e:
                    logger.debug('Error while loading blocks.json: %s'%e)
                    pass
Пример #6
0
def loadAlphaTerrainTexture():
    #texW, texH, terraindata = loadPNGFile(os.path.join(directories.getDataDir(),  ResourcePackHandler.Instance().get_selected_resource_pack().terrain_path()))
    texW, texH, terraindata = loadPNGFile(directories.getDataFile(ResourcePackHandler.Instance().get_selected_resource_pack().terrain_path()))

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

    tex = glutils.Texture(_loadFunc)
    tex.data = terraindata
    return tex
Пример #7
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
     self.block_image = {}
     self.propogated_textures = []
     self.all_texture_slots = []
     #self.old_terrain = Image.open(os.path.join(directories.getDataDir(), 'terrain.png'))
     self.old_terrain = Image.open(directories.getDataFile('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(" ", "_"))
     self._terrain_path = directories.getDataFile(u'terrain-textures', self._terrain_name.replace(u' ', u'_'))
Пример #8
0
def loadPNGTexture(filename, *a, **kw):
    #filename = os.path.join(directories.getDataDir(), filename)
    filename = directories.getDataFile(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 as e:
        print "Exception loading ", filename, ": ", repr(e)
        return glutils.Texture()
Пример #9
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:
        with open(directories.getDataFile('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
Пример #10
0
    def makeSideColumn1(self):
        def showLicense():
            #platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
            platform_open(directories.getDataFile('LICENSE.txt'))

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

        def update_mcver():
            num = mcver_updater.run()
            if num is None:
                albow.alert("Error Updating")
            elif 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")),
                     directories.getDataFile('LICENSE.txt')),
                    ("",
                     "Refresh Player Names",
                     refresh),
                    ("",
                     "Update Version Definitions",
                     update_mcver)
                    ])

        c = albow.HotkeyColumn(hotkeys)

        return c
Пример #11
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.getDataFile('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.")
            input()

        raise

    return 0
Пример #12
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.getDataFile('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
Пример #13
0
    def makeSideColumn1(self):
        def showLicense():
            #platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
            platform_open(directories.getDataFile('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")),
                     directories.getDataFile('LICENSE.txt')),
                    ("",
                     "Refresh Player Names",
                     refresh),
                    ("",
                     "Update Version Definitions",
                     update_mcver)
                    ])

        c = albow.HotkeyColumn(hotkeys)

        return c
Пример #14
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')
            data = open(directories.getDataFile('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
Пример #15
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')
         f = codecs.open(getDataFile('missingmclangres.txt'), 'a+', encoding='utf_8')
         if line not in f.read():
             f.write(line)
         f.close()
Пример #16
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')
            data = open(directories.getDataFile('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 
Пример #17
0
 def load_filter_json():
     #filter_json_file = os.path.join(directories.getDataDir(), "filters.json")
     filter_json_file = directories.getDataFile('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
Пример #18
0
 def addMissing(name, cat='base'):
     n = ''
     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')
         f = codecs.open(getDataFile('missingmclangres.txt'),
                         'a+',
                         encoding='utf_8')
         if line not in f.read():
             f.write(line)
         f.close()
Пример #19
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"))
     albow.translate.langPath = directories.getDataFile('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)
Пример #20
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"))
     albow.translate.langPath = directories.getDataFile('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)
Пример #21
0
    def __init__(self, current_tick_time=0, **kwds):
        super(TimeEditor, self).__init__(**kwds)

        self._current_tick_time = current_tick_time
        self._current_time = self.fromTicks(self.doTimeAdjustment(self._current_tick_time))

        self.__original_value = current_tick_time
        self.__original_time = self._current_time

        self.last_pos = (None, None)

        self.day_input = IntField(value=self.__original_time[0], min=1)

        __deg = self.ticksToDegrees(current_tick_time)

        self.rot_image = RotatableImage(
            image=pygame.image.load(directories.getDataFile("toolicons", "day_night_cycle.png")),
            min_angle=-self._maxRotation,
            max_angle=0,
            angle=__deg
        )
        self.rot_image.mouse_drag = self.mouse_drag
        self.rot_image.mouse_up = self.mouse_up
        self.rot_image.tooltipText = "Left-Click and drag to the left or the right"

        self.time_field = ModifiedTimeField(
            value=(self.__original_time[1], self.__original_time[2]),
            callback=self._timeFieldCallback
        )
        # __time_field_old_value = self.time_field.value
        self.add(Column((
            Row((Label("Day: "), self.day_input)),
            self.rot_image,
            Row((Label("Time of day:"), self.time_field))
        ))
        )
        self.shrink_wrap()
Пример #22
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")
langPath = directories.getDataFile("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.
#
Пример #23
0
            file_image = Surface((16, 16), SRCALPHA)
            file_image.fill((0, 0, 0, 0))
            draw.lines(file_image, (255, 255, 255, 255), False,
                       [[3, 15], [3, 1], [13, 1]], 2)
            draw.line(file_image, (255, 255, 255, 255), [3, 7], [10, 7], 2)
            folder_image = Surface((16, 16), SRCALPHA)
            folder_image.fill((0, 0, 0, 0))
            draw.line(folder_image, (255, 255, 255, 255), [3, 15], [3, 1], 2)
            draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 0,
                     pi / 1.9, 2)
            draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15],
                     3 * pi / 2, 2 * pi, 2)
    else:  # windows
        # file_image = image.load(os.path.join(getDataDir(), 'file.png'))
        # folder_image = image.load(os.path.join(getDataDir(), 'folder.png'))
        file_image = image.load(getDataFile('file.png'))
        folder_image = image.load(getDataFile('folder.png'))


class DirPathView(Widget):
    def __init__(self, width, client, **kwds):
        Widget.__init__(self, **kwds)
        self.set_size_for_text(width)
        self.client = client

    def draw(self, surf):
        frame = self.get_margin_rect()
        image = self.font.render(self.client.directory, True, self.fg_color)
        tw = image.get_width()
        mw = frame.width
        if tw <= mw:
Пример #24
0
 def showLicense():
     #platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
     platform_open(directories.getDataFile('LICENSE.txt'))
Пример #25
0
        ("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),
        ("defaultBulletImages", "Default Bullet Images", True),
        #("bulletFileName", "Bullet Images File", directories.os.path.join(directories.getDataDir(), 'Nbtsheet.png')),
        ("bulletFileName", 'Bullet Image File', directories.getDataFile('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")
    ],
    ("schematicCopying", "Schematics Copying"): [
        ("cancelCommandBlockOffset", "Cancel Command Block Offset", False)
    ]
}
Пример #26
0
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))
    sys.path.append(directories.getDataFile('pymclevel', 'build', 'lib.{}-2.6'.format(plat)).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)
os.environ['YAML_ROOT'] = directories.getDataFile('pymclevel').encode(enc)

from pygame import display

from albow import request_new_filename, request_old_filename
Пример #27
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")
langPath = directories.getDataFile("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.
#
Пример #28
0
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_name = directories.getDataFile('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:
        #fp = open(os.path.join(cur_dir, "splash.png"), 'rb')
Пример #29
0
 def __init__(self):
     self._isEmpty = False
     self._too_big = False
     # self._terrain_path = os.path.join(directories.getDataDir(), "terrain.png")
     self._terrain_path = directories.getDataFile('terrain.png')
     self._pack_name = "Default"
Пример #30
0
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

if __name__ == "__main__":
    #albow.resource.resource_dir = directories.getDataDir()
    albow.resource.resource_dir = directories.getDataFile()

def create_mocked_pyclark():
    import imp

    class MockedPyClark(object):

        class Clark(object):

            def report(self, *args, **kwargs):
                pass

        global_clark = Clark()

    mod = imp.new_module('pyClark')
    mod = MockedPyClark()
Пример #31
0
 def __init__(self):
     self._isEmpty = False
     self._too_big = False
     #self._terrain_path = os.path.join(directories.getDataDir(), "terrain.png")
     self._terrain_path = directories.getDataFile('terrain.png')
     self._pack_name = "Default"
Пример #32
0
        ("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),
        ("defaultBulletImages", "Default Bullet Images", True),
        #("bulletFileName", "Bullet Images File", directories.os.path.join(directories.getDataDir(), 'Nbtsheet.png')),
        ("bulletFileName", 'Bullet Image File',
         directories.getDataFile('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")],
    ("schematicCopying", "Schematics Copying"): [
        ("cancelCommandBlockOffset", "Cancel Command Block Offset", False)
    ]
}
Пример #33
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 = [" "]
    for ver_str in _versions:
        v1 = LooseVersion(ver_str)
        idx = -1
        for i, cur_ver in enumerate(versions):
            v2 = LooseVersion(cur_ver)
            if v1 >= v2:
                break
        versions.insert(i, ver_str)
    versions = versions[:-1]
    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')
        lines = codecs.open(getDataFile('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)):
        if os.path.exists(getDataFile('Items', lang)):
            log.debug("Found Items/%s" % lang)
            # lines = codecs.open(os.path.join(getDataDir(), 'Items', lang), encoding='utf_8')
            lines = codecs.open(getDataFile('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
Пример #34
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, getDataFile

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')):
if not os.path.exists(getDataFile('bo3.def')):
    log.warning('The `bo3.def` file is missing in `%s`. The BO3 support will not be complete...'%getDataFile())
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)])
    bo3_blocks.update([(a, int(b)) for a, b in re.findall(r'^([A-Z0-9_]+)\(([0-9]*).*\)', open(getDataFile('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
Пример #35
0
    def reset(self, splash=None, caption=("", "")):
        pygame.key.set_repeat(500, 100)

        try:
            display.gl_set_attribute(pygame.GL_SWAP_CONTROL, config.settings.vsync.get())
        except Exception as e:
            logging.warning('Unable to set vertical sync: {0!r}'.format(e))

        display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)

        if DEBUG_WM:
            print "config.settings.windowMaximized.get()", config.settings.windowMaximized.get()
        wwh = self.getWindowSize()
        if DEBUG_WM:
            print "wwh 1", wwh
        d = display.set_mode(wwh, self.displayMode())

        # Let initialize OpenGL stuff after the splash.
        GL.glEnableClientState(GL.GL_VERTEX_ARRAY)
        GL.glAlphaFunc(GL.GL_NOTEQUAL, 0)
        GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
 
        # textures are 256x256, so with this we can specify pixel coordinates
#        GL.glMatrixMode(GL.GL_TEXTURE)
#        GL.glScale(1 / 256., 1 / 256., 1 / 256.)

        display.set_caption(*caption)

        if mcplatform.WindowHandler:
            self.win = mcplatform.WindowHandler(mode=self.displayMode())

        # The following Windows specific code won't be executed if we're using '--debug-wm' switch.
        if not USE_WM and sys.platform == 'win32' and config.settings.setWindowPlacement.get():
            config.settings.setWindowPlacement.set(False)
            config.save()
            X, Y = config.settings.windowX.get(), config.settings.windowY.get()

            if X:
                hwndOwner = display.get_wm_info()['window']

                flags, showCmd, ptMin, ptMax, rect = mcplatform.win32gui.GetWindowPlacement(hwndOwner)
                realW = rect[2] - rect[0]
                realH = rect[3] - rect[1]

                showCmd = config.settings.windowShowCmd.get()
                rect = (X, Y, X + realW, Y + realH)

                mcplatform.win32gui.SetWindowPlacement(hwndOwner, (0, showCmd, ptMin, ptMax, rect))

            config.settings.setWindowPlacement.set(True)
            config.save()
        elif self.win:
            maximized = config.settings.windowMaximized.get()
            if DEBUG_WM:
                print "maximized", maximized
            if maximized:
                geom = self.win.get_root_rect()
                in_w, in_h = self.win.get_size()
                x, y = int((geom[2] - in_w) / 2), int((geom[3] - in_h) / 2)
                os.environ['SDL_VIDEO_CENTERED'] = '1'
            else:
                os.environ['SDL_VIDEO_CENTERED'] = '0'
                x, y = config.settings.windowX.get(), config.settings.windowY.get()
                wwh = self.win.get_size()
            if DEBUG_WM:
                print "x", x, "y", y
                print "wwh 2", wwh

        if splash:
            # Setup the OGL display
            GL.glLoadIdentity()
            GLU.gluOrtho2D(0, wwh[0], 0, wwh[1])
            GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_ACCUM_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT)

            swh = splash.get_size()
            _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2)
            w, h = swh

            try:
                data = image.tostring(splash, 'RGBA_PREMULT', 1)
            except ValueError:
                data = image.tostring(splash, 'RGBA', 1)
            except ValueError:
                data = image.tostring(splash, 'RGB', 1)

            # Set the raster position
            GL.glRasterPos(_x, _y)

            GL.glDrawPixels(w, h,
                            GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, numpy.fromstring(data, dtype='uint8'))

        if splash:
            display.flip()

        if self.win:
            if not maximized:
                wwh = self.getWindowSize()
            if DEBUG_WM:
                print "wwh 3", wwh
            self.win.set_position((x, y), update=True)
            if DEBUG_WM:
                print "* self.win.get_position()", self.win.get_position()

        try:
            #iconpath = os.path.join(directories.getDataDir(), 'favicon.png')
            iconpath = directories.getDataFile('favicon.png')
            iconfile = file(iconpath, 'rb')
            icon = pygame.image.load(iconfile, 'favicon.png')
            display.set_icon(icon)
        except Exception as e:
            logging.warning('Unable to set icon: {0!r}'.format(e))

        # Let initialize OpenGL stuff after the splash.
#         GL.glEnableClientState(GL.GL_VERTEX_ARRAY)
#         GL.glAlphaFunc(GL.GL_NOTEQUAL, 0)
#         GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
 
        # textures are 256x256, so with this we can specify pixel coordinates
        GL.glMatrixMode(GL.GL_TEXTURE)
        GL.glScale(1 / 256., 1 / 256., 1 / 256.)

        self.display = d

        self.loadTextures()
Пример #36
0
import logging
import os
import re
from random import randint

from directories import getDataFile
from pymclevel import schematic, materials
from . import nbt
from .entity import TileEntity

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')):
if not os.path.exists(getDataFile('bo3.def')):
    log.warning(
        'The `bo3.def` file is missing in `%s`. The BO3 support will not be complete...'
        % getDataFile())
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)])
    bo3_blocks.update([
        (a, int(b))
        for a, b in re.findall(r'^([A-Z0-9_]+)\(([0-9]*).*\)',
                               open(getDataFile('bo3.def')).read(), re.M)
    ])
    log.debug('BO3 block definitions loaded. %s entries found' %
              len(list(bo3_blocks.keys())))

# find another way for this.
# keys are block ids in uppercase, values are tuples for ranges, lists for exact states
Пример #37
0
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

if __name__ == "__main__":
    #albow.resource.resource_dir = directories.getDataDir()
    albow.resource.resource_dir = directories.getDataFile()

def create_mocked_pyclark():
    import imp

    class MockedPyClark(object):

        class Clark(object):

            def report(self, *args, **kwargs):
                pass

        global_clark = Clark()

    mod = imp.new_module('pyClark')
    mod = MockedPyClark()
Пример #38
0
    def reloadFilters(self):
        filterFiles = []
        unicode_module_names = []

        # Tracking stock and custom filters names in order to load correctly the translations.
        stock_filters = []
        cust_filters = []

        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'):
                    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"):
                        if stock:
                            stock_filters.append(possible_filter)
                            _stock = True
                        else:
                            cust_filters.append(possible_filter)
                            _stock = False
                        # Force the 'stock' parameter if the filter was found in the stock-filters directory
                        if possible_filter in stock_filters:
                            _stock = True
                        filterFiles.append((root, possible_filter, _stock, subFolderString))

        # Search first for the stock filters.
        #searchForFiltersInDir(os.path.join(directories.getDataDir(), "stock-filters"), True)
        searchForFiltersInDir(directories.getDataFile('stock-filters'), True)
        searchForFiltersInDir(directories.getFiltersDir(), False)

        filterModules = []

        org_lang = albow.translate.lang


        # 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:
                if f[1] in self.not_imported_filters:
                    continue
                module = tryImport(f[0], f[1], org_lang, f[2], f[3], f[1] in unicode_module_names, notify=(not self.optionsPanel.notifications_disabled))
                if module is None:
                    self.not_imported_filters.append(f[1])
                    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])))
Пример #39
0
 def showLicense():
     #platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
     platform_open(directories.getDataFile('LICENSE.txt'))
Пример #40
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 = [" "]
    for ver_str in _versions:
        v1 = LooseVersion(ver_str)
        idx = -1
        for i, cur_ver in enumerate(versions):
            v2 = LooseVersion(cur_ver)
            if v1>= v2:
                break
        versions.insert(i, ver_str)
    versions = versions[:-1]
    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')
        lines = codecs.open(getDataFile('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)):
        if os.path.exists(getDataFile('Items', lang)):
            log.debug("Found Items/%s" % lang)
            #lines = codecs.open(os.path.join(getDataDir(), 'Items', lang), encoding='utf_8')
            lines = codecs.open(getDataFile('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
Пример #41
0
        _ldb = ctypes.CDLL(os.path.join(pth, 'libleveldb.so'))
    elif plat == 'darwin':
        # since on OSX the program is bundled in a .app archive, shall we use the same (or approching) thecnique as for Linux?
        _ldb = ctypes.CDLL(
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         'libleveldb.dylib'))
    elif plat == 'win32':
        if getattr(sys, '_MEIPASS', False):
            import win32api

            win32api.SetDllDirectory(sys._MEIPASS)
        DLL_NAME = 'LevelDB-MCPE-32bit.dll'
        if platform.architecture()[0] == '64bit' or sys.maxsize > 2**32:
            DLL_NAME = 'LevelDB-MCPE-64bit.dll'
        # _ldb = ctypes.CDLL(os.path.join(os.path.dirname(os.path.abspath(__file__)), "LevelDB-MCPE.dll"))
        _ldb = ctypes.CDLL(str(directories.getDataFile('pymclevel', DLL_NAME)))
    log.debug("Binary support v%s.%s for PE 1+ world succesfully loaded." %
              (_ldb.leveldb_major_version(), _ldb.leveldb_minor_version()))
except Exception as e:
    # What shall we do if the library is not found?
    # If the library is not loaded, the _ldb object does not exists, and every call to it will crash MCEdit...
    # We may import this module using try/except statement.
    log.error("The binary support for PE 1+ worlds could not be loaded:")
    log.error(e)
    raise e

_ldb.leveldb_filterpolicy_create_bloom.argtypes = [ctypes.c_int]
_ldb.leveldb_filterpolicy_create_bloom.restype = ctypes.c_void_p
_ldb.leveldb_filterpolicy_destroy.argtypes = [ctypes.c_void_p]
_ldb.leveldb_filterpolicy_destroy.restype = None
_ldb.leveldb_cache_create_lru.argtypes = [ctypes.c_size_t]
Пример #42
0
            from pygame import draw, Surface
            from pygame.locals import SRCALPHA
            from math import pi
            file_image = Surface((16, 16), SRCALPHA)
            file_image.fill((0,0,0,0))
            draw.lines(file_image, (255, 255, 255, 255), False, [[3, 15], [3, 1], [13, 1]], 2)
            draw.line(file_image, (255, 255, 255, 255), [3, 7], [10, 7], 2)
            folder_image = Surface((16, 16), SRCALPHA)
            folder_image.fill((0,0,0,0))
            draw.line(folder_image, (255, 255, 255, 255), [3, 15], [3, 1], 2)
            draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 0, pi/1.9, 2)
            draw.arc(folder_image, (255, 255, 255, 255), [0, 1, 13, 15], 3*pi/2, 2*pi, 2)
    else: # windows
        #file_image = image.load(os.path.join(getDataDir(), 'file.png'))
        #folder_image = image.load(os.path.join(getDataDir(), 'folder.png'))
        file_image = image.load(getDataFile('file.png'))
        folder_image = image.load(getDataFile('folder.png'))

class DirPathView(Widget):
    def __init__(self, width, client, **kwds):
        Widget.__init__(self, **kwds)
        self.set_size_for_text(width)
        self.client = client

    def draw(self, surf):
        frame = self.get_margin_rect()
        image = self.font.render(self.client.directory, True, self.fg_color)
        tw = image.get_width()
        mw = frame.width
        if tw <= mw:
            x = 0