Example #1
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
Example #2
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
Example #3
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
Example #4
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
Example #5
0
 def showScreenshotsDir():
     try:
         os.mkdir(os.path.join(directories.getCacheDir(),
                               "screenshots"))
     except OSError:
         pass
     platform_open(
         os.path.join(directories.getCacheDir(), "screenshots"))
Example #6
0
 def check_for_version(self):
     new_version = release.check_for_new_version(self.version_info)
     if new_version is not False:
         answer = albow.ask(_('Version {} is available').format(
             new_version["tag_name"]), ['Download', 'View', 'Ignore'],
                            default=1,
                            cancel=2)
         if answer == "View":
             platform_open(new_version["html_url"])
         elif answer == "Download":
             platform_open(new_version["asset"]["browser_download_url"])
             albow.alert(
                 _(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.'
                   ).format(new_version["asset"]["name"]))
Example #7
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
Example #8
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
Example #9
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.macro_steps = []
        self.current_step = 0
        self._filter_json = None
        self.keys_panel = None
        self.filterOptionsPanel = None
        self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True)
        self.binding_button = Button("", action=self.bind_key,
                                     tooltipText="Click to bind this filter to a key")

        self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir())
        self.filterLabel.tooltipText = "Click to open filters folder"

        self.macro_button = Button("Record Macro", action=self.start_record_macro)
        self.filterSelectRow = Row((self.filterLabel, self.filterSelect,
                                    self.macro_button, self.binding_button))

        self.confirmButton = Button("Filter", action=self.confirm)

        self._recording = False
        self._save_macro = False
        self.tool = tool
        self.selectedName = self.filter_json.get("Last Filter Opened", "")
Example #10
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.macro_steps = []
        self.current_step = 0
        self._filter_json = None
        self.keys_panel = None
        self.filterOptionsPanel = None
        self.filterSelect = ChoiceButton([],
                                         choose=self.filterChanged,
                                         doNotTranslate=True)
        self.binding_button = Button(
            "",
            action=self.bind_key,
            tooltipText="Click to bind this filter to a key")

        self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(
            directories.getFiltersDir())
        self.filterLabel.tooltipText = "Click to open filters folder"

        self.macro_button = Button("Record Macro",
                                   action=self.start_record_macro)
        self.filterSelectRow = Row((self.filterLabel, self.filterSelect,
                                    self.macro_button, self.binding_button))

        self.confirmButton = Button("Filter", action=self.confirm)

        self._recording = False
        self._save_macro = False
        self.tool = tool
        self.selectedName = self.filter_json.get("Last Filter Opened", "")
Example #11
0
    def __init__(self, tool):
        Panel.__init__(self, name="Panel.FilterToolPanel")
        self.macro_steps = []
        self.current_step = 0
        self._filter_json = None
        self.keys_panel = None
        self.filterOptionsPanel = None
        self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True)
        self.binding_button = Button("", action=self.bind_key, tooltipText="Click to bind this filter to a key")

        self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir())
        self.filterLabel.tooltipText = "Click to open filters folder"

        self.macro_button = Button("Record Macro", action=self.start_record_macro)
        self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button))

        self.confirmButton = Button("Filter", action=self.confirm)

        self._recording = False
        self._save_macro = False
        self.tool = tool
        self.selectedName = self.filter_json.get("Last Filter Opened", "")

        utils = FilterUtils(
            editor=tool.editor,
            materials=self.tool.editor.level.materials,
            custom_widget=tool.editor.addExternalWidget,
            resize_selection_box=tool.editor._resize_selection_box,
        )
        utils_module = imp.new_module("filter_utils")
        utils_module = utils
        sys.modules["filter_utils"] = utils_module
Example #12
0
 def check_for_version(self):
     new_version = release.check_for_new_version(self.version_info)
     if new_version is not False:
         answer = albow.ask(
             _('Version {} is available').format(new_version["tag_name"]),
             [
                 'Download',
                 'View',
                 'Ignore'
             ],
             default=1,
             cancel=2
         )
         if answer == "View":
             platform_open(new_version["html_url"])
         elif answer == "Download":
             platform_open(new_version["asset"]["browser_download_url"])
             albow.alert(_(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.').format(new_version["asset"]["name"]))
Example #13
0
class FilterToolPanel(Panel):
    def __init__(self, tool):
        Panel.__init__(self)

        self.savedOptions = {}

        self.tool = tool
        self.selectedFilterName = None
        if len(self.tool.filterModules):
            self.reload()

    def reload(self):
        for i in list(self.subwidgets):
            self.remove(i)

        tool = self.tool

        if len(tool.filterModules) is 0:
            self.add(Label("No filter modules found!"))
            self.shrink_wrap()
            return

        if self.selectedFilterName is None or self.selectedFilterName not in tool.filterNames:
            self.selectedFilterName = tool.filterNames[0]

        self.filterOptionsPanel = None
        while self.filterOptionsPanel is None:
            module = self.tool.filterModules[self.selectedFilterName]
            try:
                self.filterOptionsPanel = FilterModuleOptions(self.tool, module)
            except Exception, e:
                alert(_("Error creating filter inputs for {0}: {1}").format(module, e))
                traceback.print_exc()
                self.tool.filterModules.pop(self.selectedFilterName)
                self.selectedFilterName = tool.filterNames[0]

            if len(tool.filterNames) == 0:
                raise ValueError("No filters loaded!")

        self.filterSelect = ChoiceButton(tool.filterNames, choose=self.filterChanged)
        self.filterSelect.selectedChoice = self.selectedFilterName

        self.confirmButton = Button("Filter", action=self.tool.confirm)

        filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        filterLabel.mouse_down = lambda x: mcplatform.platform_open(mcplatform.filtersDir)
        filterLabel.tooltipText = "Click to open filters folder"
        filterSelectRow = Row((filterLabel, self.filterSelect))

        self.add(Column((filterSelectRow, self.filterOptionsPanel, self.confirmButton)))

        self.shrink_wrap()
        if self.parent:
            self.centery = self.parent.centery

        if self.selectedFilterName in self.savedOptions:
            self.filterOptionsPanel.options = self.savedOptions[self.selectedFilterName]
Example #14
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
Example #15
0
    def reload(self):
        for i in list(self.subwidgets):
            self.remove(i)

        tool = self.tool

        if len(tool.filterModules) is 0:
            self.add(Label("No filter modules found!"))
            self.shrink_wrap()
            return

        if self.selectedFilterName is None or self.selectedFilterName not in tool.filterNames:
            self.selectedFilterName = tool.filterNames[0]

        self.filterSelect = ChoiceButton(tool.filterNames, choose=self.filterChanged)
        self.filterSelect.selectedChoice = self.selectedFilterName

        filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir())
        filterLabel.tooltipText = "Click to open filters folder"
        self.filterSelectRow = filterSelectRow = Row((filterLabel, self.filterSelect))

        self.confirmButton = Button("Filter", action=self.tool.confirm)

        self.filterOptionsPanel = None
        while self.filterOptionsPanel is None:
            module = self.tool.filterModules[self.selectedFilterName]
            try:
                self.filterOptionsPanel = FilterModuleOptions(self.tool, module, _parent=self)
            except Exception, e:
                alert(_("Error creating filter inputs for {0}: {1}").format(module, e))
                traceback.print_exc()
                self.tool.filterModules.pop(self.selectedFilterName)
                self.selectedFilterName = tool.filterNames[0]

            if len(tool.filterNames) == 0:
                raise ValueError("No filters loaded!")
Example #16
0
    def __init__(self, tool):
        Panel.__init__(self, name='Panel.FilterToolPanel')
        self.macro_steps = []
        self.current_step = 0
        self._filter_json = None
        self.keys_panel = None
        self.filterOptionsPanel = None
        self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True)
        self.binding_button = Button("", action=self.bind_key,
                                     tooltipText="Click to bind this filter to a key")

        self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir())
        self.filterLabel.tooltipText = "Click to open filters folder"

        self.macro_button = Button("Record Macro", action=self.start_record_macro)
        self.filterSelectRow = Row((self.filterLabel, self.filterSelect,
                                    self.macro_button, self.binding_button))

        self.confirmButton = Button("Filter", action=self.confirm)

        self._recording = False
        self._save_macro = False
        self.tool = tool
        self.selectedName = self.filter_json.get("Last Filter Opened", "")
        
        
        utils = FilterUtils(
                            editor=tool.editor, 
                            materials=self.tool.editor.level.materials,
                            custom_widget=tool.editor.addExternalWidget,
                            resize_selection_box=tool.editor._resize_selection_box
                            )
        utils_module = imp.new_module("filter_utils")
        utils_module = utils
        sys.modules["filter_utils"] = utils_module
Example #17
0
 def showLicense():
     platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
Example #18
0
 def revealCache():
     mcplatform.platform_open(MCServerChunkGenerator.worldCacheDir)
Example #19
0
 def revealStorage():
     mcplatform.platform_open(jarStorage.cacheDir)
Example #20
0
 def open_screenshots_folder(self):
     from mcplatform import platform_open
     platform_open(os.path.join(directories.getCacheDir(), "screenshots"))
     self.screenshot_notify()
Example #21
0
 def showCacheDir():
     try:
         os.mkdir(directories.getCacheDir())
     except OSError:
         pass
     platform_open(directories.getCacheDir())
Example #22
0
    def main(self):
        displayContext = GLDisplayContext()

        rootwidget = RootWidget(displayContext.display)
        mcedit = MCEdit(displayContext)
        rootwidget.displayContext = displayContext
        rootwidget.confirm_quit = mcedit.confirm_quit
        rootwidget.mcedit = mcedit

        rootwidget.add(mcedit)
        rootwidget.focus_switch = mcedit
        if 0 == len(pymclevel.alphaMaterials.yamlDatas):
            albow.alert("Failed to load minecraft.yaml. Check the console window for details.")

        if mcedit.droppedLevel:
            mcedit.loadFile(mcedit.droppedLevel)

        new_version = release.check_for_new_version()
        if new_version is not False:
            answer = albow.ask(
                _('Version {} is available').format(new_version["tag_name"]),
                [
                    'Download',
                    'View',
                    'Ignore'
                ],
                default=1,
                cancel=2
            )
            if answer == "View":
                platform_open(new_version["html_url"])
            elif answer == "Download":
                platform_open(new_version["asset"]["browser_download_url"])
                albow.alert(_(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.').format(new_version["asset"]["name"]))

# Disabled old update code
#       if hasattr(sys, 'frozen'):
#           # We're being run from a bundle, check for updates.
#           import esky
#
#           app = esky.Esky(
#               sys.executable.decode(sys.getfilesystemencoding()),
#               'https://bitbucket.org/codewarrior0/mcedit/downloads'
#           )
#           try:
#               update_version = app.find_update()
#           except:
#               # FIXME: Horrible, hacky kludge.
#               update_version = None
#               logging.exception('Error while checking for updates')
#
#           if update_version:
#               answer = albow.ask(
#                   'Version "%s" is available, would you like to '
#                   'download it?' % update_version,
#                   [
#                       'Yes',
#                       'No',
#                   ],
#                   default=0,
#                   cancel=1
#               )
#               if answer == 'Yes':
#                   def callback(args):
#                       status = args['status']
#                       status_texts = {
#                           'searching': u"Finding updates...",
#                           'found':  u"Found version {new_version}",
#                           'downloading': u"Downloading: {received} / {size}",
#                           'ready': u"Downloaded {path}",
#                           'installing': u"Installing {new_version}",
#                           'cleaning up': u"Cleaning up...",
#                           'done': u"Done."
#                       }
#                       text = status_texts.get(status, 'Unknown').format(**args)
#
#                       panel = Dialog()
#                       panel.idleevent = lambda event: panel.dismiss()
#                       label = albow.Label(text, width=600)
#                       panel.add(label)
#                       panel.size = (500, 250)
#                       panel.present()
#
#                   try:
#                       app.auto_update(callback)
#                   except (esky.EskyVersionError, EnvironmentError):
#                       albow.alert(_("Failed to install update %s") % update_version)
#                   else:
#                       albow.alert(_("Version %s installed. Restart MCEdit to begin using it.") % update_version)
#                       raise SystemExit()

        if config.settings.closeMinecraftWarning.get():
            answer = albow.ask(
                "Warning: Only open a world in one program at a time. If you open a world at the same time in MCEdit and in Minecraft, you will lose your work and possibly damage your save file.\n\n If you are using Minecraft 1.3 or earlier, you need to close Minecraft completely before you use MCEdit.",
                ["Don't remind me again.", "OK"], default=1, cancel=1)
            if answer == "Don't remind me again.":
                config.settings.closeMinecraftWarning.set(False)

# Disabled Crash Reporting Option
#       if not config.settings.reportCrashesAsked.get():
#           answer = albow.ask(
#               "When an error occurs, MCEdit can report the details of the error to its developers. "
#               "The error report will include your operating system version, MCEdit version, "
#               "OpenGL version, plus the make and model of your CPU and graphics processor. No personal "
#               "information will be collected.\n\n"
#               "Error reporting can be enabled or disabled in the Options dialog.\n\n"
#               "Enable error reporting?",
#               ["Yes", "No"],
#               default=0)
#           config.settings.reportCrashes.set(answer == "Yes")
#           config.settings.reportCrashesAsked.set(True)
        config.settings.reportCrashes.set(False)
        config.settings.reportCrashesAsked.set(True)

        config.save()
        if "update" in config.version.version.get():
            answer = albow.ask("There are new default controls. Do you want to replace your current controls with the new ones?", ["Yes", "No"])
            if answer == "Yes":
                for configKey, k in keys.KeyConfigPanel.presets["WASD"]:
                    config.keys[config.convert(configKey)].set(k)
        config.version.version.set("1.1.2.0")
        config.save()
        if "-causeError" in sys.argv:
            raise ValueError, "Error requested via -causeError"

        while True:
            try:
                rootwidget.run()
            except SystemExit:
                if sys.platform == "win32" and config.settings.setWindowPlacement.get():
                    (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement(
                        display.get_wm_info()['window'])
                    X, Y, r, b = rect
                    #w = r-X
                    #h = b-Y
                    if (showCmd == mcplatform.win32con.SW_MINIMIZE or
                                showCmd == mcplatform.win32con.SW_SHOWMINIMIZED):
                        showCmd = mcplatform.win32con.SW_SHOWNORMAL

                    config.settings.windowX.set(X)
                    config.settings.windowY.set(Y)
                    config.settings.windowShowCmd.set(showCmd)

                config.save()
                mcedit.editor.renderer.discardAllChunks()
                mcedit.editor.deleteAllCopiedSchematics()
                raise
            except MemoryError:
                traceback.print_exc()
                mcedit.editor.handleMemoryError()
Example #23
0
 def open_screenshots_folder(self):
     from mcplatform import platform_open
     platform_open(os.path.join(directories.getCacheDir(), "screenshots"))
     self.screenshot_notify()
Example #24
0
 def showCacheDir():
     platform_open(directories.getCacheDir())
Example #25
0
 def revealCache():
     mcplatform.platform_open(MCServerChunkGenerator.worldCacheDir)
Example #26
0
 def revealStorage():
     mcplatform.platform_open(jarStorage.cacheDir)
Example #27
0
 def showCacheDir():
     platform_open(directories.getCacheDir())
Example #28
0
 def open_screenshots_folder():
     from mcplatform import platform_open
     platform_open(os.path.join(directories.parentDir, "screenshots"))
Example #29
0
 def showCacheDir():
     try:
         os.mkdir(directories.getCacheDir())
     except OSError:
         pass
     platform_open(directories.getCacheDir())
Example #30
0
 def showScreenshotsDir():
     platform_open(os.path.join(directories.parentDir, "screenshots"))
Example #31
0
 def showScreenshotsDir():
     try:
         os.mkdir(os.path.join(directories.getCacheDir(), "screenshots"))
     except OSError:
         pass
     platform_open(os.path.join(directories.getCacheDir(), "screenshots"))
Example #32
0
 def showLicense():
     #platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
     platform_open(directories.getDataFile('LICENSE.txt'))
Example #33
0
def perform(level, box, options):
    import WorldConverter
    reload(WorldConverter)

    answer = None
    try:
        update_data = urllib2.urlopen(
            'https://raw.githubusercontent.com/gentlegiantJGC/Minecraft-World-Converter/master/version.txt'
        ).read().split(';')
        if filter_version != update_data[0]:
            #this part I found in the MCedit source code so credit to the MCedit team
            answer = albow.ask(
                ('Version {} is available').format(update_data[0]),
                ['Download', 'Ignore'],
                default=0,
                cancel=1)
    except:
        print 'Tried checking if there was an update however there was an issue'

    if answer == "Download":
        from mcplatform import platform_open
        platform_open(update_data[1])
        raise Exception(update_data[2].replace('\\n', '\n\n'))

    skippedBlocks = []
    convertFrom = options['Convert From']
    convertTo = options['Convert To']
    if convertFrom == convertTo:
        raise Exception(
            "due to some bug that I can't work out this doesn't currently work"
        )

    # needs cleaning up (ideally idenfifying map by actual map type rather than user input?)
    filePath = None
    filePath = mcplatform.askOpenFile(title="Select a PC world to read from",
                                      schematics=False)
    if filePath is not None:
        levelOld = mclevel.fromFile(filePath)
    else:
        raise Exception('no file given')

    if len(list(levelOld.allChunks)) > options["Break Every"]:
        chunksDonePath = None
        chunksDonePath = mcplatform.askOpenFile(
            title="Select somewhere to save chunk list", schematics=False)
        if chunksDonePath is not None:
            chunksDoneFO = open(chunksDonePath).read()
            if chunksDoneFO == '':
                chunksDoneList = []
            else:
                chunksDoneList = json.loads(chunksDoneFO)
        else:
            raise Exception('no file given')
    else:
        chunksDoneList = []
        chunksDonePath = None

    # level.showProgress("Processed 0 chunks of {}".format(len(list(levelOld.allChunks))),)

    # def convertWorld
    chunksDone = 0
    import time
    t = time.time()
    for chunkOldCoords in levelOld.allChunks:
        cx, cz = chunkOldCoords
        if [cx, cz] in chunksDoneList:
            chunksDone += 1
            continue
        else:
            chunksDoneList.append(chunkOldCoords)
        chunkOld = levelOld.getChunk(cx, cz)
        generateChunk(level, True, cx, cz, 15)
        chunk = level.getChunk(cx, cz)
        chunk.Blocks[:] = copy.deepcopy(chunkOld.Blocks)
        chunk.Data[:] = copy.deepcopy(chunkOld.Data)
        if options["NBT"] == "Delete":
            for e in chunk.TileEntities[:]:
                del e
            for e in chunk.Entities[:]:
                del e

        for e in chunkOld.TileEntities:
            # try:

            # except:
            # pass
            chunk.TileEntities.append(copy.deepcopy(e))
        '''
		copying entities to bedrock seems to cause issues so removed this code until a fix is found
		for e in chunkOld.Entities:
			chunk.Entities.append(copy.deepcopy(e))
		'''
        # chunk.TileEntities = copy.deepcopy(chunkOld.TileEntities)
        # chunk.Entities = copy.deepcopy(chunkOld.Entities)
        #else:
        #need to work out how to copy entities across to the PC version. The above code errors

        # get a list of all the unique blocks
        chunkBlockList = np.unique(np.add(chunkOld.Blocks * 16, chunkOld.Data))
        # go through every block in that list and find the converted id, data and tile entity
        for block in chunkBlockList:
            blockID = block >> 4
            blockData = block % 16
            blockIDNew, blockDataNew, nbtNew = WorldConverter.convertBlock(
                convertFrom, convertTo, blockID, blockData)
            # if  blockIDNew is equal to -1 then there is a tile enitity requirement
            if blockIDNew == -1:
                # for every location with that block id+data combo
                for coord in np.argwhere(
                        np.logical_and(chunkOld.Blocks == blockID,
                                       chunkOld.Data == blockData)):
                    x, z, y = coord
                    x += cx * 16
                    z += cz * 16
                    # get the tile entity
                    te = level.tileEntityAt(x, y, z)
                    if te is None:
                        # if the tile entity does not exist, use fallback id
                        blockIDNew, blockDataNew, nbtNew = WorldConverter.convertBlock(
                            convertFrom,
                            convertTo,
                            blockID,
                            blockData,
                            fallBack=True)
                        if nbtNew is not None:
                            te = WorldConverter.createBlockEntity(
                                chunk, convertTo, blockIDNew, x, y, z)
                    else:
                        # if it does exist
                        blockIDNew, blockDataNew, nbtNew = WorldConverter.convertBlock(
                            convertFrom, convertTo, blockID, blockData, te)
                    level.setBlockAt(x, y, z, blockIDNew)
                    level.setBlockDataAt(x, y, z, blockDataNew)
                    if te is not None and nbtNew is not None:
                        # merge nbtNew with tile entity
                        for nbtToSet in nbtNew:
                            te[nbtToSet['key']] = strToNBT['nbtType'](
                                nbtToSet['value'])

            # if -2 then there was an exception
            elif blockIDNew == -2:
                # print chunkOldCoords
                # print block
                # raise Exception
                skippedBlocks.append((blockID, blockData))
            elif blockIDNew != blockID or blockDataNew != blockData:
                convertTheseBlocks = np.logical_and(chunkOld.Blocks == blockID,
                                                    chunkOld.Data == blockData)
                if blockIDNew != blockID:
                    chunk.Blocks[convertTheseBlocks] = blockIDNew
                if blockDataNew != blockData:
                    chunk.Data[convertTheseBlocks] = blockDataNew
            if nbtNew is not None and blockIDNew not in [-1, -2]:
                # for all blocks where there was not a tile entity requirement
                for coord in np.argwhere(
                        np.logical_and(chunkOld.Blocks == blockID,
                                       chunkOld.Data == blockData)):
                    x, z, y = coord
                    x += cx * 16
                    z += cz * 16
                    # get the tile entity
                    te = level.tileEntityAt(x, y, z)
                    if te is None:
                        te = WorldConverter.createBlockEntity(
                            chunk, convertTo, blockIDNew, x, y, z)
                    # merge nbtNew with tile entity
                    for nbtToSet in nbtNew:
                        te[nbtToSet['key']] = strToNBT['nbtType'](
                            nbtToSet['value'])
            if blockIDNew in requiresBlockEntity[convertTo]:
                for coord in np.argwhere(
                        np.logical_and(chunkOld.Blocks == blockID,
                                       chunkOld.Data == blockData)):
                    x, z, y = coord
                    x += cx * 16
                    z += cz * 16
                    if level.tileEntityAt(x, y, z) is None:
                        WorldConverter.createBlockEntity(
                            chunk, convertTo, blockIDNew, x, y, z)
        for te in chunk.TileEntities[:]:
            WorldConverter.convertBlockEntity(convertFrom, convertTo, te)

        for e in chunk.Entities[:]:
            WorldConverter.convertEntity(convertFrom, convertTo, e)

        # biomes
        if options['Biomes']:
            if convertFrom == 'PC':
                if chunkOld.root_tag and 'Level' in chunkOld.root_tag.keys(
                ) and 'Biomes' in chunkOld.root_tag["Level"].keys():
                    array = copy.deepcopy(
                        chunkOld.root_tag["Level"]["Biomes"].value)
                else:
                    array = np.ones(256)
            elif convertFrom == 'PE':
                array = np.fromstring(chunkOld.Biomes.tostring(), 'uint8')
            if convertTo == 'PC':
                if chunk.root_tag and 'Level' in chunk.root_tag.keys(
                ) and 'Biomes' in chunk.root_tag["Level"].keys():
                    chunk.root_tag["Level"]["Biomes"].value = array
            elif convertTo == 'PE':
                array.shape = (16, 16)
                for biomeID in np.unique(array):
                    chunk.Biomes[array == biomeID] = biomeID
                # chunk.Biomes[:] = array

        chunk.chunkChanged()
        chunksDone += 1
        print '{}/{}'.format(chunksDone, len(list(levelOld.allChunks)))
        if chunksDone % options["Break Every"] == options["Break Every"] - 1:
            break
    if skippedBlocks != []:
        WorldConverter.bugReport(
            submitThis='skippedBlocks:{}'.format(skippedBlocks))
        # print skippedBlocks

    # for _ in levelNew.saveInPlaceGen():
    # pass

    levelOld.close()
    print time.time() - t
    if chunksDonePath is not None:
        chunksDoneFO = open(chunksDonePath, 'w')
        json.dump(chunksDoneList, chunksDoneFO)
        chunksDoneFO.close()
Example #34
0
    def main(self):
        displayContext = GLDisplayContext()

        rootwidget = RootWidget(displayContext.display)
        mcedit = MCEdit(displayContext)
        rootwidget.displayContext = displayContext
        rootwidget.confirm_quit = mcedit.confirm_quit
        rootwidget.mcedit = mcedit

        rootwidget.add(mcedit)
        rootwidget.focus_switch = mcedit
        if 0 == len(pymclevel.alphaMaterials.yamlDatas):
            albow.alert(
                "Failed to load minecraft.yaml. Check the console window for details."
            )

        if mcedit.droppedLevel:
            mcedit.loadFile(mcedit.droppedLevel)

        new_version = release.check_for_new_version()
        if new_version is not False:
            answer = albow.ask(_('Version {} is available').format(
                new_version["tag_name"]), ['Download', 'View', 'Ignore'],
                               default=1,
                               cancel=2)
            if answer == "View":
                platform_open(new_version["html_url"])
            elif answer == "Download":
                platform_open(new_version["asset"]["browser_download_url"])
                albow.alert(
                    _(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.'
                      ).format(new_version["asset"]["name"]))

# Disabled old update code
#       if hasattr(sys, 'frozen'):
#           # We're being run from a bundle, check for updates.
#           import esky
#
#           app = esky.Esky(
#               sys.executable.decode(sys.getfilesystemencoding()),
#               'https://bitbucket.org/codewarrior0/mcedit/downloads'
#           )
#           try:
#               update_version = app.find_update()
#           except:
#               # FIXME: Horrible, hacky kludge.
#               update_version = None
#               logging.exception('Error while checking for updates')
#
#           if update_version:
#               answer = albow.ask(
#                   'Version "%s" is available, would you like to '
#                   'download it?' % update_version,
#                   [
#                       'Yes',
#                       'No',
#                   ],
#                   default=0,
#                   cancel=1
#               )
#               if answer == 'Yes':
#                   def callback(args):
#                       status = args['status']
#                       status_texts = {
#                           'searching': u"Finding updates...",
#                           'found':  u"Found version {new_version}",
#                           'downloading': u"Downloading: {received} / {size}",
#                           'ready': u"Downloaded {path}",
#                           'installing': u"Installing {new_version}",
#                           'cleaning up': u"Cleaning up...",
#                           'done': u"Done."
#                       }
#                       text = status_texts.get(status, 'Unknown').format(**args)
#
#                       panel = Dialog()
#                       panel.idleevent = lambda event: panel.dismiss()
#                       label = albow.Label(text, width=600)
#                       panel.add(label)
#                       panel.size = (500, 250)
#                       panel.present()
#
#                   try:
#                       app.auto_update(callback)
#                   except (esky.EskyVersionError, EnvironmentError):
#                       albow.alert(_("Failed to install update %s") % update_version)
#                   else:
#                       albow.alert(_("Version %s installed. Restart MCEdit to begin using it.") % update_version)
#                       raise SystemExit()

        if config.settings.closeMinecraftWarning.get():
            answer = albow.ask(
                "Warning: Only open a world in one program at a time. If you open a world at the same time in MCEdit and in Minecraft, you will lose your work and possibly damage your save file.\n\n If you are using Minecraft 1.3 or earlier, you need to close Minecraft completely before you use MCEdit.",
                ["Don't remind me again.", "OK"],
                default=1,
                cancel=1)
            if answer == "Don't remind me again.":
                config.settings.closeMinecraftWarning.set(False)


# Disabled Crash Reporting Option
#       if not config.settings.reportCrashesAsked.get():
#           answer = albow.ask(
#               "When an error occurs, MCEdit can report the details of the error to its developers. "
#               "The error report will include your operating system version, MCEdit version, "
#               "OpenGL version, plus the make and model of your CPU and graphics processor. No personal "
#               "information will be collected.\n\n"
#               "Error reporting can be enabled or disabled in the Options dialog.\n\n"
#               "Enable error reporting?",
#               ["Yes", "No"],
#               default=0)
#           config.settings.reportCrashes.set(answer == "Yes")
#           config.settings.reportCrashesAsked.set(True)
        config.settings.reportCrashes.set(False)
        config.settings.reportCrashesAsked.set(True)

        config.save()
        if "update" in config.version.version.get():
            answer = albow.ask(
                "There are new default controls. Do you want to replace your current controls with the new ones?",
                ["Yes", "No"])
            if answer == "Yes":
                for configKey, k in keys.KeyConfigPanel.presets["WASD"]:
                    config.keys[config.convert(configKey)].set(k)
        config.version.version.set("1.1.2.0")
        config.save()
        if "-causeError" in sys.argv:
            raise ValueError, "Error requested via -causeError"

        while True:
            try:
                rootwidget.run()
            except SystemExit:
                if sys.platform == "win32" and config.settings.setWindowPlacement.get(
                ):
                    (flags, showCmd, ptMin, ptMax,
                     rect) = mcplatform.win32gui.GetWindowPlacement(
                         display.get_wm_info()['window'])
                    X, Y, r, b = rect
                    #w = r-X
                    #h = b-Y
                    if (showCmd == mcplatform.win32con.SW_MINIMIZE or showCmd
                            == mcplatform.win32con.SW_SHOWMINIMIZED):
                        showCmd = mcplatform.win32con.SW_SHOWNORMAL

                    config.settings.windowX.set(X)
                    config.settings.windowY.set(Y)
                    config.settings.windowShowCmd.set(showCmd)

                config.save()
                mcedit.editor.renderer.discardAllChunks()
                mcedit.editor.deleteAllCopiedSchematics()
                raise
            except MemoryError:
                traceback.print_exc()
                mcedit.editor.handleMemoryError()