Esempio n. 1
0
    def saveWindowPosition(self):
        """Save the window position in the configuration handler."""
        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)
        elif sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
            win = display.get_wm_info()['window']
            dis = mcplatform.Xlib.display.Display()
            win = dis.create_resource_object('window', win)
            curDesk = os.environ.get('XDG_CURRENT_DESKTOP')
            if curDesk == 'GNOME':
                wParent = win.query_tree().parent.query_tree().parent
            elif curDesk == 'KDE':
                wParent = win.query_tree().parent.query_tree(
                ).parent.query_tree().parent
            if wParent:
                geom = wParent.get_geometry()
                config.settings.windowX.set(geom.x)
                config.settings.windowY.set(geom.y)
Esempio n. 2
0
    def saveWindowPosition(self):
        """Save the window position in the configuration handler."""
        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)
        elif sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
            win = display.get_wm_info()['window']
            dis = mcplatform.Xlib.display.Display()
            win = dis.create_resource_object('window', win)
            curDesk = os.environ.get('XDG_CURRENT_DESKTOP')
            if curDesk == 'GNOME':
                wParent = win.query_tree().parent.query_tree().parent
            elif curDesk == 'KDE':
                wParent = win.query_tree().parent.query_tree().parent.query_tree().parent
            if wParent:
                geom = wParent.get_geometry()
                config.settings.windowX.set(geom.x)
                config.settings.windowY.set(geom.y)
Esempio n. 3
0
    def saveWindowPosition():
        """Save the window position in the configuration handler."""
        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)
        elif sys.platform == "linux2" and mcplatform.hasXlibDisplay:
            win = display.get_wm_info()["window"]
            dis = mcplatform.Xlib.display.Display()
            win = dis.create_resource_object("window", win)
            curDesk = os.environ.get("XDG_CURRENT_DESKTOP")
            if curDesk in ("GNOME", "X-Cinnamon", "Unity"):
                wParent = win.query_tree().parent.query_tree().parent
            elif curDesk == "KDE":
                wParent = win.query_tree().parent.query_tree().parent.query_tree().parent
            else:
                wParent = None
            if wParent:
                geom = wParent.get_geometry()
                config.settings.windowX.set(geom.x)
                config.settings.windowY.set(geom.y)
Esempio n. 4
0
    def test_get_wm_info(self):
        wm_info = display.get_wm_info()
        # Assert function returns a dictionary type
        self.assertIsInstance(wm_info, dict)

        wm_info_potential_keys = {
            "colorbuffer",
            "connection",
            "data",
            "dfb",
            "display",
            "framebuffer",
            "fswindow",
            "hdc",
            "hglrc",
            "hinstance",
            "lock_func",
            "resolveFramebuffer",
            "shell_surface",
            "surface",
            "taskHandle",
            "unlock_func",
            "wimpVersion",
            "window",
            "wmwindow",
        }

        # If any unexpected dict keys are present, they
        # will be stored in set wm_info_remaining_keys
        wm_info_remaining_keys = set(wm_info.keys()).difference(wm_info_potential_keys)

        # Assert set is empty (& therefore does not
        # contain unexpected dict keys)
        self.assertFalse(wm_info_remaining_keys)
Esempio n. 5
0
def askOpenFileWin32(title, schematics, initialDir):
    try:
        # if schematics:
        f = ('Levels and Schematics\0*.mclevel;*.dat;*.mine;*.mine.gz;*.schematic;*.zip;*.schematic.gz;*.inv\0' +
              '*.*\0*.*\0\0')
        #        else:
#            f = ('Levels (*.mclevel, *.dat;*.mine;*.mine.gz;)\0' +
#                 '*.mclevel;*.dat;*.mine;*.mine.gz;*.zip;*.lvl\0' +
#                 '*.*\0*.*\0\0')

        (filename, customfilter, flags) = win32gui.GetOpenFileNameW(
            hwndOwner=display.get_wm_info()['window'],
            InitialDir=initialDir,
            Flags=(win32con.OFN_EXPLORER
                   | win32con.OFN_NOCHANGEDIR
                   | win32con.OFN_FILEMUSTEXIST
                   | win32con.OFN_LONGNAMES
                   # |win32con.OFN_EXTENSIONDIFFERENT
                   ),
            Title=title,
            Filter=f,
            )
    except Exception, e:
        print "Open File: ", e
        pass
Esempio n. 6
0
    def test_get_wm_info(self):
        wm_info = display.get_wm_info()
        # Assert function returns a dictionary type
        self.assertIsInstance(wm_info,dict)

        wm_info_potential_keys = {
        'colorbuffer',
        'connection',
        'data',
        'dfb',
        'display',
        'framebuffer',
        'fswindow',
        'hdc',
        'hglrc',
        'hinstance',
        'lock_func',
        'resolveFramebuffer',
        'shell_surface',
        'surface',
        'taskHandle',
        'unlock_func',
        'wimpVersion',
        'window',
        'wmwindow'
        }

        # If any unexpected dict keys are present, they
        # will be stored in set wm_info_remaining_keys
        wm_info_remaining_keys = set(wm_info.keys()).difference(wm_info_potential_keys)

        # Assert set is empty (& therefore does not
        # contain unexpected dict keys)
        self.assertFalse(wm_info_remaining_keys)
Esempio n. 7
0
def askOpenFileWin32(title, schematics, initialDir):
    try:
        # if schematics:
        f = (
            'Levels and Schematics\0*.mclevel;*.dat;*.mine;*.mine.gz;*.schematic;*.zip;*.schematic.gz;*.inv\0'
            + '*.*\0*.*\0\0')
        #        else:
        #            f = ('Levels (*.mclevel, *.dat;*.mine;*.mine.gz;)\0' +
        #                 '*.mclevel;*.dat;*.mine;*.mine.gz;*.zip;*.lvl\0' +
        #                 '*.*\0*.*\0\0')

        (filename, customfilter, flags) = win32gui.GetOpenFileNameW(
            hwndOwner=display.get_wm_info()['window'],
            InitialDir=initialDir,
            Flags=(
                win32con.OFN_EXPLORER
                | win32con.OFN_NOCHANGEDIR
                | win32con.OFN_FILEMUSTEXIST
                | win32con.OFN_LONGNAMES
                # |win32con.OFN_EXTENSIONDIFFERENT
            ),
            Title=title,
            Filter=f,
        )
    except Exception, e:
        #print "Open File: ", e
        pass
Esempio n. 8
0
    def saveWindowPosition(self):
        """Save the window position in the configuration handler."""
        if DEBUG_WM:
            print "############################ EXITING ############################"
        win = self.displayContext.win
        # The following Windows specific code will not be executed if we're using '--debug-wm' switch.
        if not USE_WM and 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
            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)
        elif win:
            config.settings.windowMaximized.set(self.maximized)
            if not self.maximized:
                x, y = win.get_position()
            else:
                x, y = self.saved_pos
            if DEBUG_WM:
                print "x", x, "y", y
            config.settings.windowX.set(x)
            config.settings.windowY.set(y)
Esempio n. 9
0
    def saveWindowPosition(self):
        """Save the window position in the configuration handler."""
        if DEBUG_WM:
            print "############################ EXITING ############################"
        win = self.displayContext.win
        # The following Windows specific code will not be executed if we're using '--debug-wm' switch.
        if not USE_WM and 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)
        elif win:
            config.settings.windowMaximized.set(self.maximized)
            if not self.maximized:
                x, y = win.get_position()
            else:
                x, y = self.saved_pos
            if DEBUG_WM:
                print "x", x, "y", y
            config.settings.windowX.set(x)
            config.settings.windowY.set(y)
def restart(mcedit):
    import config
    import mcplatform
    from pygame import display
    from leveleditor import Settings
    if sys.platform == "win32" and 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

        Settings.windowX.set(X)
        Settings.windowY.set(Y)
        Settings.windowShowCmd.set(showCmd)

    config.saveConfig()
    mcedit.editor.renderer.discardAllChunks()
    mcedit.editor.deleteAllCopiedSchematics()
    python = sys.executable
    os.execl(python, python, *sys.argv)
Esempio n. 11
0
 def draw_menu(self, events, overlay):
     try:
         SetForegroundWindow(display.get_wm_info()["window"])
     except:
         pass
     self.menu.update(events)
     self.menu.draw(overlay)
Esempio n. 12
0
    def resized(self, dw, dh):
        """
        Handle window resizing events.
        """
        GLViewport.resized(self, dw, dh)

        (w, h) = self.size
        if w == 0 and h == 0:
            # The window has been minimized, no need to draw anything.
            self.editor.renderer.render = False
            return

        if not self.editor.renderer.render:
            self.editor.renderer.render = True

        dis = None
        if sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
            dis = mcplatform.Xlib.display.Display()
            win = dis.create_resource_object('window',
                                             display.get_wm_info()['window'])
            geom = win.query_tree().parent.get_geometry()

        if w >= 1000 and h >= 700:
            config.settings.windowWidth.set(w)
            config.settings.windowHeight.set(h)
            config.save()
            if dis:
                win.configure(height=geom.height, width=geom.width)
        elif w != 0 and h != 0:
            config.settings.windowWidth.set(1000)
            config.settings.windowHeight.set(700)
            config.save()
            if dis:
                win.configure(height=700, width=1000)
        if dw > 20 or dh > 20:
            if not hasattr(self, 'resizeAlert'):
                self.resizeAlert = self.shouldResizeAlert
            if self.resizeAlert:
                albow.alert(
                    "Window size increased. You may have problems using the cursor until MCEdit is restarted."
                )
                self.resizeAlert = False
        if dis:
            dis.sync()
Esempio n. 13
0
    def resized(self, dw, dh):
        """
        Handle window resizing events.
        """
        GLViewport.resized(self, dw, dh)

        (w, h) = self.size
        if w == 0 and h == 0:
            # The window has been minimized, no need to draw anything.
            self.editor.renderer.render = False
            return

        if not self.editor.renderer.render:
            self.editor.renderer.render = True

        dis = None
        if sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
            dis = mcplatform.Xlib.display.Display()
            win = dis.create_resource_object('window', display.get_wm_info()['window'])
            geom = win.query_tree().parent.get_geometry()

        if w >= 1000 and h >= 700:
            config.settings.windowWidth.set(w)
            config.settings.windowHeight.set(h)
            config.save()
            if dis:
                win.configure(height=geom.height, width=geom.width)
        elif w !=0 and h !=0:
            config.settings.windowWidth.set(1000)
            config.settings.windowHeight.set(700)
            config.save()
            if dis:
                win.configure(height=700, width=1000)
        if dw > 20 or dh > 20:
            if not hasattr(self, 'resizeAlert'):
                self.resizeAlert = self.shouldResizeAlert
            if self.resizeAlert:
                albow.alert(
                    "Window size increased. You may have problems using the cursor until MCEdit is restarted.")
                self.resizeAlert = False
        if dis:
            dis.sync()
Esempio n. 14
0
def askSaveFile(initialDir, title, defaultName, filetype, suffix):
    if sys.platform == "win32":
        try:
            (filename, customfilter, flags) = win32gui.GetSaveFileNameW(
                hwndOwner=display.get_wm_info()['window'],
                InitialDir=initialDir,
                Flags=win32con.OFN_EXPLORER | win32con.OFN_NOCHANGEDIR | win32con.OFN_OVERWRITEPROMPT,
                File=defaultName,
                DefExt=suffix,
                Title=title,
                Filter=filetype,
                )
        except Exception, e:
            print "Error getting file name: ", e
            return

        try:
            filename = filename[:filename.index('\0')]
            filename = filename.decode(sys.getfilesystemencoding())
        except: pass
Esempio n. 15
0
def askSaveFile(initialDir, title, defaultName, filetype, suffix):
    if sys.platform == "win32":
        try:
            (filename, customfilter, flags) = win32gui.GetSaveFileNameW(
                hwndOwner=display.get_wm_info()['window'],
                InitialDir=initialDir,
                Flags=win32con.OFN_EXPLORER | win32con.OFN_NOCHANGEDIR
                | win32con.OFN_OVERWRITEPROMPT,
                File=defaultName,
                DefExt=suffix,
                Title=title,
                Filter=filetype,
            )
        except Exception, e:
            print "Error getting file name: ", e
            return

        try:
            filename = filename[:filename.index('\0')]
            filename = filename.decode(sys.getfilesystemencoding())
        except:
            pass
Esempio n. 16
0
def restart(mcedit):
    import config
    import mcplatform
    from pygame import display
    from leveleditor import Settings
    if sys.platform == "win32" and 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

        Settings.windowX.set(X)
        Settings.windowY.set(Y)
        Settings.windowShowCmd.set(showCmd)

    config.saveConfig()
    mcedit.editor.renderer.discardAllChunks()
    mcedit.editor.deleteAllCopiedSchematics()
    python = sys.executable
    os.execl(python, python, * sys.argv)
Esempio n. 17
0
    def main(cls):
        PlayerCache().load()
        displayContext = GLDisplayContext(splash.splash, caption=(('MCEdit ~ ' + release.get_version()%_("for")).encode('utf-8'), 'MCEdit'))

        os.environ['SDL_VIDEO_CENTERED'] = '0'

        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)

        cls.version_lock = threading.Lock()
        cls.version_info = None
        cls.version_checked = False

        fetch_version_thread = threading.Thread(target=cls.fetch_version)
        fetch_version_thread.start()


# 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, KeyboardInterrupt):
                print "Shutting down..."
                exc_txt = traceback.format_exc()
                if mcedit.editor.level:
                    if config.settings.savePositionOnClose.get():
                        mcedit.editor.waypointManager.saveLastPosition(mcedit.editor.mainViewport, mcedit.editor.level.getPlayerDimension())
                    mcedit.editor.waypointManager.save()
                # 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():
                    (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)

                # Restore the previous language if we ran with '-tt' (update translation template).
                if albow.translate.buildTemplate:
                    logging.warning('Restoring %s.'%orglang)
                    config.settings.langCode.set(orglang)
                #
                config.save()
                mcedit.editor.renderer.discardAllChunks()
                mcedit.editor.deleteAllCopiedSchematics()
                if mcedit.editor.level:
                    mcedit.editor.level.close()
                mcedit.editor.root.RemoveEditFiles()
                if 'SystemExit' in traceback.format_exc() or 'KeyboardInterrupt' in traceback.format_exc():
                    raise
                else:
                    if 'SystemExit' in exc_txt:
                        raise SystemExit
                    if 'KeyboardInterrupt' in exc_txt:
                        raise KeyboardInterrupt
            except MemoryError:
                traceback.print_exc()
                mcedit.editor.handleMemoryError()
Esempio n. 18
0
    def __init__(self, displayContext, *args):
        if DEBUG_WM:
            print "############################ __INIT__ ###########################"
        self.resizeAlert = config.settings.showWindowSizeWarning.get()
        self.maximized = config.settings.windowMaximized.get()
        self.saved_pos = config.settings.windowX.get(), config.settings.windowY.get()
        if displayContext.win and DEBUG_WM:
            print "* self.displayContext.win.state", displayContext.win.get_state()
            print "* self.displayContext.win.position", displayContext.win.get_position()
            self.dis = None
            self.win = None
            self.wParent = None
            self.wGrandParent = None
            self.linux = False
            if sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
                self.linux = True
                self.dis = dis = mcplatform.Xlib.display.Display()
                self.win = win = dis.create_resource_object('window', display.get_wm_info()['window'])
                curDesk = os.environ.get('XDG_CURRENT_DESKTOP')
                if curDesk in ('GNOME', 'X-Cinnamon', 'Unity'):
                    self.geomReciever = self.maximizeHandler = wParent = win.query_tree().parent
                    self.geomSender = wGrandParent = wParent.query_tree().parent
                elif curDesk == 'KDE':
                    self.maximizeHandler = win.query_tree().parent
                    wParent = win.query_tree().parent.query_tree().parent
                    wGrandParent = wParent.query_tree().parent.query_tree().parent
                    self.geomReciever = self.geomSender = win.query_tree().parent.query_tree().parent.query_tree().parent
                else:
                    self.maximizeHandler = self.geomReciever = self.geomSender = wGrandParent = wParent = None
                self.wParent = wParent
                self.wGrandParent = wGrandParent
                root = dis.screen().root
                windowID = root.get_full_property(dis.intern_atom('_NET_ACTIVE_WINDOW'), mcplatform.Xlib.X.AnyPropertyType).value[0]
                print "###\nwindowID", windowID
                window = dis.create_resource_object('window', windowID)
                print "###\nwindow.get_geometry()", window.get_geometry()
                print "###\nself.win", self.win.get_geometry()
                print "###\nself.wParent.get_geometry()", self.wParent.get_geometry()
                print "###\nself.wGrandParent.get_geometry()", self.wGrandParent.get_geometry()
                try:
                    print "###\nself.wGrandParent.query_tree().parent.get_geometry()", self.wGrandParent.query_tree().parent.get_geometry()
                except:
                    pass
                print "###\nself.maximizeHandler.get_geometry()", self.maximizeHandler.get_geometry()
                print "###\nself.geomReciever.get_geometry()", self.geomReciever.get_geometry()
                print "###\nself.geomSender.get_geometry()", self.geomSender.get_geometry()
                print "###\nself.win", self.win
                print "###\nself.wParent", self.wParent
                print "###\nself.wGrandParent", self.wGrandParent
                print "###\nself.maximizeHandler", self.maximizeHandler
                print "###\nself.geomReciever", self.geomReciever
                print "###\nself.geomSender", self.geomSender

        ws = displayContext.getWindowSize()
        r = rect.Rect(0, 0, ws[0], ws[1])
        GLViewport.__init__(self, r)
        if DEBUG_WM:
            print "self.size", self.size, "ws", ws
        if displayContext.win and self.maximized:
            # Send a maximize event now
            displayContext.win.set_state(mcplatform.MAXIMIZED)
            # Flip pygame.display to avoid to see the splash un-centered.
            pygame.display.flip()
        self.displayContext = displayContext
        self.bg_color = (0, 0, 0, 1)
        self.anchor = 'tlbr'

        if not config.config.has_section("Recent Worlds"):
            config.config.add_section("Recent Worlds")
            self.setRecentWorlds([""] * 5)

        self.optionsPanel = panels.OptionsPanel(self)
        if not albow.translate.buildTemplate:
            self.optionsPanel.getLanguageChoices()
            lng = config.settings.langCode.get()
            if lng not in self.optionsPanel.sgnal:
                lng = "en_US"
                config.settings.langCode.set(lng)
            albow.translate.setLang(lng)
        # Set the window caption here again, since the initialization is done through several steps...
        display.set_caption(('MCEdit ~ ' + release.get_version()%_("for")).encode('utf-8'), 'MCEdit')
        self.optionsPanel.initComponents()
        self.graphicsPanel = panels.GraphicsPanel(self)

        #&# Prototype for blocks/items names
        mclangres.buildResources(lang=albow.translate.getLang())
        #&#

        #.#
        self.keyConfigPanel = keys.KeyConfigPanel(self)
        #.#

        self.droppedLevel = None

        self.nbtCopyBuffer = None

        self.reloadEditor()

        """
        check command line for files dropped from explorer
        """
        if len(sys.argv) > 1:
            for arg in sys.argv[1:]:
                f = arg.decode(sys.getfilesystemencoding())
                if os.path.isdir(os.path.join(pymclevel.minecraftSaveFileDir, f)):
                    f = os.path.join(pymclevel.minecraftSaveFileDir, f)
                    self.droppedLevel = f
                    break
                if os.path.exists(f):
                    self.droppedLevel = f
                    break

        self.fileOpener = albow.FileOpener(self)
        self.add(self.fileOpener)

        self.fileOpener.focus()
Esempio n. 19
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()
Esempio n. 20
0
    def main(cls):
        PlayerCache().load()
        displayContext = GLDisplayContext(splash.splash, caption=(
        ('MCEdit ~ ' + release.get_version() % _("for")).encode('utf-8'), 'MCEdit'))

        os.environ['SDL_VIDEO_CENTERED'] = '0'

        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 mcedit.droppedLevel:
            mcedit.loadFile(mcedit.droppedLevel)

        cls.version_lock = threading.Lock()
        cls.version_info = None
        cls.version_checked = False

        fetch_version_thread = threading.Thread(target=cls.fetch_version)
        fetch_version_thread.start()

        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)

        if not config.settings.reportCrashesAsked.get():
            answer = albow.ask(
                'Would you like to send anonymous error reports to the MCEdit-Unified Team to help with improving future releases?\n\nError reports are stripped of any identifying user information before being sent.\n\nPyClark, the library used, is open source under the GNU LGPL v3 license and is maintained by Podshot. The source code can be located here: https://github.com/Podshot/pyClark.\n\nThere has been no modification to the library in any form.',
                ['Allow', 'Deny'], default=1, cancel=1
            )
            if answer == 'Allow':
                albow.alert("Error reporting will be enabled next time MCEdit-Unified is launched")
            config.settings.reportCrashes.set(answer == 'Allow')
            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.6.0.0")
        config.save()
        if "-causeError" in sys.argv:
            raise ValueError("Error requested via -causeError")

        while True:
            try:
                rootwidget.run()
            except (SystemExit, KeyboardInterrupt):
                print "Shutting down..."
                exc_txt = traceback.format_exc()
                if mcedit.editor.level:
                    if config.settings.savePositionOnClose.get():
                        mcedit.editor.waypointManager.saveLastPosition(mcedit.editor.mainViewport,
                                                                       mcedit.editor.level.dimNo)
                    mcedit.editor.waypointManager.save()
                # 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():
                    (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement(
                        display.get_wm_info()['window'])
                    X, Y, r, b = rect
                    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)

                # Restore the previous language if we ran with '-tt' (update translation template).
                if albow.translate.buildTemplate:
                    logging.warning('Restoring %s.' % orglang)
                    config.settings.langCode.set(orglang)
                #
                config.save()
                mcedit.editor.renderer.discardAllChunks()
                mcedit.editor.deleteAllCopiedSchematics()
                if mcedit.editor.level:
                    mcedit.editor.level.close()
                mcedit.editor.root.RemoveEditFiles()
                if 'SystemExit' in traceback.format_exc() or 'KeyboardInterrupt' in traceback.format_exc():
                    raise
                else:
                    if 'SystemExit' in exc_txt:
                        raise SystemExit
                    if 'KeyboardInterrupt' in exc_txt:
                        raise KeyboardInterrupt
            except MemoryError:
                traceback.print_exc()
                mcedit.editor.handleMemoryError()
Esempio n. 21
0
    def __init__(self, displayContext, *args):
        if DEBUG_WM:
            print "############################ __INIT__ ###########################"
        self.resizeAlert = config.settings.showWindowSizeWarning.get()
        self.maximized = config.settings.windowMaximized.get()
        self.saved_pos = config.settings.windowX.get(), config.settings.windowY.get()
        if displayContext.win and DEBUG_WM:
            print "* self.displayContext.win.state", displayContext.win.get_state()
            print "* self.displayContext.win.position", displayContext.win.get_position()
            self.dis = None
            self.win = None
            self.wParent = None
            self.wGrandParent = None
            self.linux = False
            if sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
                self.linux = True
                self.dis = dis = mcplatform.Xlib.display.Display()
                self.win = win = dis.create_resource_object('window', display.get_wm_info()['window'])
                curDesk = os.environ.get('XDG_CURRENT_DESKTOP')
                if curDesk in ('GNOME', 'X-Cinnamon', 'Unity'):
                    self.geomReciever = self.maximizeHandler = wParent = win.query_tree().parent
                    self.geomSender = wGrandParent = wParent.query_tree().parent
                elif curDesk == 'KDE':
                    self.maximizeHandler = win.query_tree().parent
                    wParent = win.query_tree().parent.query_tree().parent
                    wGrandParent = wParent.query_tree().parent.query_tree().parent
                    self.geomReciever = self.geomSender = win.query_tree().parent.query_tree().parent.query_tree().parent
                else:
                    self.maximizeHandler = self.geomReciever = self.geomSender = wGrandParent = wParent = None
                self.wParent = wParent
                self.wGrandParent = wGrandParent
                root = dis.screen().root
                windowID = root.get_full_property(dis.intern_atom('_NET_ACTIVE_WINDOW'), mcplatform.Xlib.X.AnyPropertyType).value[0]
                print "###\nwindowID", windowID
                window = dis.create_resource_object('window', windowID)
                print "###\nwindow.get_geometry()", window.get_geometry()
                print "###\nself.win", self.win.get_geometry()
                print "###\nself.wParent.get_geometry()", self.wParent.get_geometry()
                print "###\nself.wGrandParent.get_geometry()", self.wGrandParent.get_geometry()
                try:
                    print "###\nself.wGrandParent.query_tree().parent.get_geometry()", self.wGrandParent.query_tree().parent.get_geometry()
                except:
                    pass
                print "###\nself.maximizeHandler.get_geometry()", self.maximizeHandler.get_geometry()
                print "###\nself.geomReciever.get_geometry()", self.geomReciever.get_geometry()
                print "###\nself.geomSender.get_geometry()", self.geomSender.get_geometry()
                print "###\nself.win", self.win
                print "###\nself.wParent", self.wParent
                print "###\nself.wGrandParent", self.wGrandParent
                print "###\nself.maximizeHandler", self.maximizeHandler
                print "###\nself.geomReciever", self.geomReciever
                print "###\nself.geomSender", self.geomSender

        ws = displayContext.getWindowSize()
        r = rect.Rect(0, 0, ws[0], ws[1])
        GLViewport.__init__(self, r)
        if DEBUG_WM:
            print "self.size", self.size, "ws", ws
        if displayContext.win and self.maximized:
            # Send a maximize event now
            displayContext.win.set_state(mcplatform.MAXIMIZED)
            # Flip pygame.display to avoid to see the splash un-centered.
            pygame.display.flip()
        self.displayContext = displayContext
        self.bg_color = (0, 0, 0, 1)
        self.anchor = 'tlbr'

        if not config.config.has_section("Recent Worlds"):
            config.config.add_section("Recent Worlds")
            self.setRecentWorlds([""] * 5)

        self.optionsPanel = panels.OptionsPanel(self)
        if not albow.translate.buildTemplate:
            self.optionsPanel.getLanguageChoices()
            lng = config.settings.langCode.get()
            if lng not in self.optionsPanel.sgnal:
                lng = "en_US"
                config.settings.langCode.set(lng)
            albow.translate.setLang(lng)
        # Set the window caption here again, since the initialization is done through several steps...
        display.set_caption(('MCEdit ~ ' + release.get_version() % _("for")).encode('utf-8'), 'MCEdit')
        self.optionsPanel.initComponents()
        self.graphicsPanel = panels.GraphicsPanel(self)

        #.#
        self.keyConfigPanel = keys.KeyConfigPanel(self)
        #.#

        self.droppedLevel = None

        self.nbtCopyBuffer = None

        self.reloadEditor()

        """
        check command line for files dropped from explorer
        """
        if len(sys.argv) > 1:
            for arg in sys.argv[1:]:
                f = arg.decode(sys.getfilesystemencoding())
                if os.path.isdir(os.path.join(pymclevel.minecraftSaveFileDir, f)):
                    f = os.path.join(pymclevel.minecraftSaveFileDir, f)
                    self.droppedLevel = f
                    break
                if os.path.exists(f):
                    self.droppedLevel = f
                    break

        self.fileOpener = albow.FileOpener(self)
        self.add(self.fileOpener)

        self.fileOpener.focus()
Esempio n. 22
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()
Esempio n. 23
0
    def main(cls):
        PlayerCache().load()
        displayContext = GLDisplayContext(
            splash.splash,
            caption=(('MCEdit ~ ' +
                      release.get_version() % _("for")).encode('utf-8'),
                     'MCEdit'))

        os.environ['SDL_VIDEO_CENTERED'] = '0'

        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)

        cls.version_lock = threading.Lock()
        cls.version_info = None
        cls.version_checked = False

        fetch_version_thread = threading.Thread(target=cls.fetch_version)
        fetch_version_thread.start()

        # 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, KeyboardInterrupt):
                print "Shutting down..."
                exc_txt = traceback.format_exc()
                if mcedit.editor.level:
                    if config.settings.savePositionOnClose.get():
                        mcedit.editor.waypointManager.saveLastPosition(
                            mcedit.editor.mainViewport,
                            mcedit.editor.level.getPlayerDimension())
                    mcedit.editor.waypointManager.save()
                # 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(
                ):
                    (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)

                # Restore the previous language if we ran with '-tt' (update translation template).
                if albow.translate.buildTemplate:
                    logging.warning('Restoring %s.' % orglang)
                    config.settings.langCode.set(orglang)
                #
                config.save()
                mcedit.editor.renderer.discardAllChunks()
                mcedit.editor.deleteAllCopiedSchematics()
                if mcedit.editor.level:
                    mcedit.editor.level.close()
                mcedit.editor.root.RemoveEditFiles()
                if 'SystemExit' in traceback.format_exc(
                ) or 'KeyboardInterrupt' in traceback.format_exc():
                    raise
                else:
                    if 'SystemExit' in exc_txt:
                        raise SystemExit
                    if 'KeyboardInterrupt' in exc_txt:
                        raise KeyboardInterrupt
            except MemoryError:
                traceback.print_exc()
                mcedit.editor.handleMemoryError()
Esempio n. 24
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')
            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()
Esempio n. 25
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()
class GLDisplayContext(object):
    def __init__(self):
        self.reset()

    def getWindowSize(self):
        w, h = (config.settings.windowWidth.get(),
                config.settings.windowHeight.get())
        return max(20, w), max(20, h)

    def displayMode(self):
        return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF

    def reset(self):
        pygame.key.set_repeat(500, 100)

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

        display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)

        d = display.set_mode(self.getWindowSize(), self.displayMode())
        try:
            pygame.scrap.init()
        except:
            logging.warning('PyGame clipboard integration disabled.')

        display.set_caption('MCEdit ~ ' + release.get_version(), 'MCEdit')
        if 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:
                w, h = self.getWindowSize()
                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 sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
            # Looks like KDE need to loose time or to instanciate Xlib atoms to get the right window to place at screen
            # Keep this code untill the end of the 'for windowID in windowIDs' loop
            dis = mcplatform.Xlib.display.Display()
            root = dis.screen().root
            windowIDs = root.get_full_property(
                dis.intern_atom('_NET_CLIENT_LIST'),
                mcplatform.Xlib.X.AnyPropertyType).value
            for windowID in windowIDs:
                window = dis.create_resource_object('window', windowID)
                name = window.get_wm_name()  # Title
                pid = window.get_full_property(
                    dis.intern_atom('_NET_WM_PID'),
                    mcplatform.Xlib.X.AnyPropertyType)  # PID

            dis = mcplatform.Xlib.display.Display()
            dRoot = dis.screen().root
            win = dRoot.get_full_property(
                dis.intern_atom('_NET_ACTIVE_WINDOW'),
                mcplatform.Xlib.X.AnyPropertyType).value[0]
            win = dis.create_resource_object('window', win)
            win.configure(x=config.settings.windowX.get(),
                          y=config.settings.windowY.get())
            #            self.win = win
            dis.sync()

        try:
            iconpath = os.path.join(directories.getDataDir(), 'favicon.png')
            iconfile = file(iconpath, 'rb')
            icon = pygame.image.load(iconfile, 'favicon.png')
            display.set_icon(icon)
        except Exception, e:
            logging.warning('Unable to set icon: {0!r}'.format(e))
Esempio n. 27
0
    def main(cls):
        PlayerCache().load()
        displayContext = GLDisplayContext(splash.splash, caption=(
        ('MCEdit ~ ' + release.get_version() % _("for")).encode('utf-8'), 'MCEdit'))

        os.environ['SDL_VIDEO_CENTERED'] = '0'

        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 mcedit.droppedLevel:
            mcedit.loadFile(mcedit.droppedLevel)

        cls.version_lock = threading.Lock()
        cls.version_info = None
        cls.version_checked = False

        fetch_version_thread = threading.Thread(target=cls.fetch_version)
        fetch_version_thread.start()

        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)

        if not config.settings.reportCrashesAsked.get():
            answer = albow.ask(
                'Would you like to send anonymous error reports to the MCEdit-Unified Team to help with improving future releases?\n\nError reports are stripped of any identifying user information before being sent.\n\nPyClark, the library used, is open source under the GNU LGPL v3 license and is maintained by Podshot. The source code can be located here: https://github.com/Podshot/pyClark.\n\nThere has been no modification to the library in any form.',
                ['Allow', 'Deny'], default=1, cancel=1
            )
            if answer == 'Allow':
                albow.alert("Error reporting will be enabled next time MCEdit-Unified is launched")
            config.settings.reportCrashes.set(answer == 'Allow')
            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.6.0.0")
        config.save()
        if "-causeError" in sys.argv:
            raise ValueError("Error requested via -causeError")

        while True:
            try:
                rootwidget.run()
            except (SystemExit, KeyboardInterrupt):
                print "Shutting down..."
                exc_txt = traceback.format_exc()
                if mcedit.editor.level:
                    if config.settings.savePositionOnClose.get():
                        mcedit.editor.waypointManager.saveLastPosition(mcedit.editor.mainViewport,
                                                                       mcedit.editor.level.dimNo)
                    mcedit.editor.waypointManager.save()
                # 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():
                    (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement(
                        display.get_wm_info()['window'])
                    X, Y, r, b = rect
                    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)

                # Restore the previous language if we ran with '-tt' (update translation template).
                if albow.translate.buildTemplate:
                    logging.warning('Restoring %s.' % orglang)
                    config.settings.langCode.set(orglang)
                #
                config.save()
                mcedit.editor.renderer.discardAllChunks()
                mcedit.editor.deleteAllCopiedSchematics()
                if mcedit.editor.level:
                    mcedit.editor.level.close()
                mcedit.editor.root.RemoveEditFiles()
                if 'SystemExit' in traceback.format_exc() or 'KeyboardInterrupt' in traceback.format_exc():
                    raise
                else:
                    if 'SystemExit' in exc_txt:
                        raise SystemExit
                    if 'KeyboardInterrupt' in exc_txt:
                        raise KeyboardInterrupt
            except MemoryError:
                traceback.print_exc()
                mcedit.editor.handleMemoryError()
Esempio n. 28
0
class GLDisplayContext(object):
    def __init__(self, splash=None, caption=("", "")):
        self.win = None
        self.reset(splash, caption=caption)

    @staticmethod
    def getWindowSize():
        w, h = (config.settings.windowWidth.get(), config.settings.windowHeight.get())
        return max(20, w), max(20, h)

    @staticmethod
    def displayMode():
        return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF

    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, 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())

        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:
            GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
            GL.glWindowPos2d(0, 0)
            back = Surface(wwh)
            back.fill((0, 0, 0))
            GL.glDrawPixels(wwh[0], wwh[1], GL.GL_RGBA, GL.GL_UNSIGNED_BYTE,
                            numpy.fromstring(image.tostring(back, 'RGBA'), dtype='uint8'))
            swh = splash.get_size()
            _x, _y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2)
            w, h = swh
            data = image.tostring(splash, 'RGBA', 1)
            GL.glWindowPos2d(_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')
            iconfile = file(iconpath, 'rb')
            icon = pygame.image.load(iconfile, 'favicon.png')
            display.set_icon(icon)
        except Exception, e:
            logging.warning('Unable to set icon: {0!r}'.format(e))
Esempio n. 29
0
class GLDisplayContext(object):
    def __init__(self, splash=None):
        self.reset(splash)

    @staticmethod
    def getWindowSize():
        w, h = (config.settings.windowWidth.get(),
                config.settings.windowHeight.get())
        return max(20, w), max(20, h)

    @staticmethod
    def displayMode():
        return pygame.OPENGL | pygame.RESIZABLE | pygame.DOUBLEBUF

    def reset(self, splash=None):
        pygame.key.set_repeat(500, 100)

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

        display.gl_set_attribute(pygame.GL_ALPHA_SIZE, 8)

        wwh = self.getWindowSize()
        d = display.set_mode(wwh, self.displayMode())

        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.)

        if splash:
            swh = splash.get_size()
            x, y = (wwh[0] / 2 - swh[0] / 2, wwh[1] / 2 - swh[1] / 2)
            w, h = swh
            data = image.tostring(splash, 'RGBA', 1)
            GL.glWindowPos2d(x, y)
            GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
            GL.glDrawPixels(w, h, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE,
                            numpy.fromstring(data, dtype='uint8'))
            display.flip()

        display.set_caption('MCEdit ~ ' + release.get_version(), 'MCEdit')
        if 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 sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
            dis = mcplatform.Xlib.display.Display()
            root = dis.screen().root
            windowIDs = root.get_full_property(
                dis.intern_atom('_NET_CLIENT_LIST'),
                mcplatform.Xlib.X.AnyPropertyType).value
            for windowID in windowIDs:
                window = dis.create_resource_object('window', windowID)
                name = window.get_wm_name()
                if "MCEdit ~ Unified" in name:
                    win = window
            win.configure(x=config.settings.windowX.get(),
                          y=config.settings.windowY.get())
            self.win = win
            dis.sync()

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