def begin_frame(self):
        self.update_packet_speed_label()
        self.update_gyro_labels()

        self.signal_mag_label.text = 'mag: %gx' % self.renderer.multiplier
        self.signal_mag_label.invalidate()

        if dev.battery is not None:
            self.battery_label.text = 'BATT: %d%%' % (dev.battery * 100) 
        else:
            self.battery_label.text = 'NO DATA'
        self.battery_label.invalidate()

        # no sense in updating if we are not going to use it
        if self.render_cursor and (dev.gyro_x is not None) and (dev.gyro_y is not None):
            new_pos_x = max(20, min(800, self.sq_pos[0] + (105 - dev.gyro_x) * 4)) if abs(dev.gyro_x - 105) > 1 else self.sq_pos[0]
            new_pos_y = max(20, min(600, self.sq_pos[1] + (dev.gyro_y - 105) * 4)) if abs(dev.gyro_y - 105) > 1 else self.sq_pos[1]
            self.sq_pos = new_pos_x, new_pos_y

        RootWidget.begin_frame(self)
Example #2
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()
    def __init__(self, surf, **kwds):
        RootWidget.__init__(self, surf, **kwds)
        self.bg_color = (255,255,255)
        self.redraw_every_frame = True
        self.set_timer(50)

        self.recording_in_progress = False

        # signal buffer stores 6 seconds of data
        self.sig_buf = SignalBuffer(768, 14)

        # add status update callbacks to the device monitor
        mon.callbacks.append(self.update_device_status)
        mon.callbacks.append(self.start_device_reader)

        self.gyrox_label = Label('', width = 80, height = 30, bg_color = (30, 30, 255))
        self.gyroy_label = Label('', width = 80, height = 30, bg_color = (30, 30, 255))
        self.signal_mag_label = Label('', width = 80, height = 30)

        small_font = pygame.font.SysFont('Ubuntu', 12)

        self.renderer = SignalRendererWidget(counter_to_sensor_id,
                                             dev,
                                             self.sig_buf,
                                             Rect(0, 0, 880, 660))
        self.add(self.renderer)

        c = Column([
                Button("Start REC",
                       action = self.start_recording,
                       enabled = lambda: not self.recording_in_progress,
                       bg_color = (0, 0, 128),
                       height = 30,
                       margin = 3),
                Button("Stop REC",
                       action = self.stop_recording,
                       enabled = lambda: self.recording_in_progress,
                       bg_color = (0, 0, 128),
                       height = 30,
                       margin = 3),
                Widget(height = 70),
                Label('Gyro Data', height = 30),
                self.gyrox_label,
                self.gyroy_label,
                Button("Cursor",
                       action = self.toggle_cursor_rendering,
                       bg_color = (255, 0, 0),
                       height = 30,
                       margin = 3),
#                Widget(height = 30),
                Label('EEG Mag', height = 30),
                Row( [
                        Button("+",
                               action = lambda: self.renderer.update_magnification(+0.2),
                               bg_color = (80, 100, 40),
                               width = 30,
                               margin = 5),
                        Button("-",
                               action = lambda: self.renderer.update_magnification(-0.2),
                               bg_color = (80, 100, 40),
                               margin = 5,
                               width = 30) ]),
                self.signal_mag_label,
                Button("Clear",
                       action = lambda: self.sig_buf.clear(),
                       bg_color = (255, 0, 0),
                       height = 30,
                       margin = 5),
                Label('Channels', width = 100, bg_color = (50, 50, 255)),
                Grid([ [ Button("F3", font = small_font, action = lambda: self.renderer.toggle_channel(0)),
                         Button("FC5", font = small_font, action = lambda: self.renderer.toggle_channel(1)),
                         Button("AF3", font = small_font, action = lambda: self.renderer.toggle_channel(2)),
                         Button("F7", font = small_font, action = lambda: self.renderer.toggle_channel(3)) ],
                       [ Button("T7", font = small_font, action = lambda: self.renderer.toggle_channel(4)),
                         Button("P7", font = small_font, action = lambda: self.renderer.toggle_channel(5)),
                         Button("O1", font = small_font, action = lambda: self.renderer.toggle_channel(6)),
                         Button("O2", font = small_font, action = lambda: self.renderer.toggle_channel(7)) ],
                       [ Button("P8", font = small_font, action = lambda: self.renderer.toggle_channel(8)),
                         Button("T8", font = small_font, action = lambda: self.renderer.toggle_channel(9)),
                         Button("F8", font = small_font, action = lambda: self.renderer.toggle_channel(10)),
                         Button("AF4", font = small_font, action = lambda: self.renderer.toggle_channel(11)) ],
                       [ Button("FC6", font = small_font, action = lambda: self.renderer.toggle_channel(12)),
                         Button("F4", font = small_font, action = lambda: self.renderer.toggle_channel(13)) ] ],
                     row_spacing = 5,
                     column_spacing = 8,
                     width = 100),
#                Widget(height = 55),
                Button("  QUIT  ",
                       action = self.quit,
                       bg_color = (200, 0, 64),
                       margin = 5
                       )],
                   align = 'c',
                   spacing = 20,
                   bg_color = (50, 50, 50),
                   rect = Rect(880, 0, 120, 690),
                   height = 690,
                   expand = True,
                   margin = 5)

        self.stat_label = Label('', 100, margin = 3)
        self.packet_speed_label = Label('', 100, margin = 3)
        self.recording_label = Label('NOT RECORDING', 400, margin = 3)
        self.battery_label = Label('NO DATA', 100, margin = 3)
        r = Row([ self.stat_label, self.packet_speed_label, self.battery_label, self.recording_label, Widget(width = 50, height = 30) ],
                rect = Rect(0, 660, 880, 30),
                width = 880,
                height = 30,
                expand = True,
                margin = 5,
                spacing = 20,
                bg_color = (50, 50, 50))

        self.add(c)
        self.add(r)

        # first update is manual
        self.update_device_status(mon.check_connected())

        # eeg rendering widget
        self.renderer = SignalRendererWidget(counter_to_sensor_id,
                                             dev,
                                             self.sig_buf,
                                             Rect(0, 0, 880, 660))
        self.add(self.renderer)

        self.update_ps_counter = 0
        self.rec = None

        self.render_cursor = False
        self.sq_pos = (400, 300)
Example #4
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 #5
0
def main():
	display = pygame.display.set_mode(screen_size, flags | OPENGL | DOUBLEBUF)
	root = RootWidget(display)
	root.bg_color = Color("blue")
	add_demo_widgets(root)
	root.run()
Example #6
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()