Пример #1
0
def setup_for_debug():
    if platform() == 'win':
        # Работаем в отладочном режиме
        Logger.info('WIN mode')
        # Config.write()

    if platform() == 'android':
        # Работаем на устройстве
        # Config.write()
        pass
Пример #2
0
Файл: main.py Проект: fresk/shs
 def get_data_dir(self):
     if platform() == "ios":
         directory = join(expanduser("~"), "Documents")
     elif platform() == "android":
         app_name = self.get_application_name
         directory = join("/sdcard", ".{0}".format(app_name))
     else:
         directory = self.directory
     if not exists(directory):
         makedirs(directory)
     return directory
Пример #3
0
    def build(self):

        data_dir = getattr(
            self, 'user_data_dir')  #get a writable path to save our score
        self.store = JsonStore(join(
            data_dir,
            'score.json'))  # create a JsonScore file in the available location

        if (not self.store.exists('score')
            ):  # if there is no file, we need to save the best score as 1
            self.store.put('score', best=1)

        if platform(
        ) == 'android':  # if we are on Android, we can initialize the ADs service
            revmob.start_session('54c247f420e1fb71091ad44a')

        self.screens = {}  # list of app screens
        self.screens['menu'] = MenuScreen(
            self
        )  #self the MainApp instance, so others objects can change the screen
        self.screens['game'] = GameScreen(self)
        self.root = FloatLayout()

        self.open_screen('menu')

        self.sound = SoundLoader.load(
            'res/background.mp3')  # open the background music
        # kivy support music loop, but it was not working on Android. I coded in a different way to fix it
        # but if fixed, we can just set the loop to True and call the play(), so it'll auto repeat
        # self.sound.loop = True It # was not working on android, so I wrote the following code:
        self.sound.play()  # play the sound
        Clock.schedule_interval(self.check_sound,
                                1)  #every second force the music to be playing

        return self.root
Пример #4
0
    def create_window(self, *largs):
        # ensure the mouse is still not up after window creation, otherwise, we
        # have some weird bugs
        self.dispatch('on_mouse_up', 0, 0, 'all', [])

        # force display to show (available only for fullscreen)
        displayidx = Config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1:
            environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

        # init some opengl, same as before.
        self.flags = pygame.HWSURFACE | pygame.OPENGL | \
                     pygame.DOUBLEBUF

        # right now, activate resizable window only on linux.
        # on window / macosx, the opengl context is lost, and we need to
        # reconstruct everything. Check #168 for a state of the work.
        if platform() in ('linux', 'macosx', 'win') and \
            Config.getint('graphics', 'resizable'):
            self.flags |= pygame.RESIZABLE

        try:
            pygame.display.init()
        except pygame.error, e:
            raise CoreCriticalException(e.message)
Пример #5
0
    def share(self):
        if platform() == 'android':  #check if the app is on Android
            # read more here: http://developer.android.com/training/sharing/send.html
            PythonActivity = autoclass('org.renpy.android.PythonActivity'
                                       )  #request the activity instance
            Intent = autoclass(
                'android.content.Intent')  # get the Android Intend class

            String = autoclass('java.lang.String')  # get the Java object

            intent = Intent()  # create a new Android Intent
            intent.setAction(Intent.ACTION_SEND)  #set the action
            # to send a message, it need to be a Java char array. So we use the cast to convert and Java String to a Java Char array
            intent.putExtra(
                Intent.EXTRA_SUBJECT,
                cast('java.lang.CharSequence', String('Fast Perception')))
            intent.putExtra(
                Intent.EXTRA_TEXT,
                cast(
                    'java.lang.CharSequence',
                    String(
                        'Wow, I just scored %d on Fast Perception. Check this game: https://play.google.com/store/apps/details?id=com.aronbordin.fastperception'
                        % (self.best_score))))

            intent.setType('text/plain')  #text message

            currentActivity = cast('android.app.Activity',
                                   PythonActivity.mActivity)
            currentActivity.startActivity(
                intent)  # show the intent in the game activity
Пример #6
0
    def post_build_init(self, *args):
        if platform() == 'android':
            import android
            android.map_key(android.KEYCODE_BACK, 1001)

        win = Window
        win.bind(on_keyboard=self.my_key_handler)
Пример #7
0
    def create_window(self, *largs):
        # ensure the mouse is still not up after window creation, otherwise, we
        # have some weird bugs
        self.dispatch('on_mouse_up', 0, 0, 'all', [])

        # force display to show (available only for fullscreen)
        displayidx = Config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1:
            environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

        # init some opengl, same as before.
        self.flags = pygame.HWSURFACE | pygame.OPENGL | \
                     pygame.DOUBLEBUF

        # right now, activate resizable window only on linux.
        # on window / macosx, the opengl context is lost, and we need to
        # reconstruct everything. Check #168 for a state of the work.
        if platform() in ('linux', 'macosx', 'win') and \
            Config.getint('graphics', 'resizable'):
            self.flags |= pygame.RESIZABLE

        try:
            pygame.display.init()
        except pygame.error, e:
            raise CoreCriticalException(e.message)
Пример #8
0
    def handle_android_back(self):
        if platform() == "android":
            import android

            res = android.hide_keyboard()
        print "HANDLING android back..."
        self.go_back()
Пример #9
0
    def build(self):

        data_dir = getattr(self, 'user_data_dir') #get a writable path to save our score
        self.store = JsonStore(join(data_dir, 'score.json')) # create a JsonScore file in the available location

        if(not self.store.exists('score')): # if there is no file, we need to save the best score as 1
            self.store.put('score', best=1)

        if platform() == 'android': # if we are on Android, we can initialize the ADs service
            revmob.start_session('54c247f420e1fb71091ad44a')

        self.screens = {} # list of app screens
        self.screens['menu'] = MenuScreen(self) #self the MainApp instance, so others objects can change the screen
        self.screens['game'] = GameScreen(self)
        self.root = FloatLayout()

        self.open_screen('menu')

        self.sound = SoundLoader.load('res/background.mp3') # open the background music
        # kivy support music loop, but it was not working on Android. I coded in a different way to fix it
        # but if fixed, we can just set the loop to True and call the play(), so it'll auto repeat
        # self.sound.loop = True It # was not working on android, so I wrote the following code:
        self.sound.play() # play the sound
        Clock.schedule_interval(self.check_sound, 1) #every second force the music to be playing

        return self.root
 def get_default_user_files_dir(self):
     if platform() == 'android':
         from jnius import autoclass
         env = autoclass('android.os.Environment')
         return path.join(env.getExternalStorageDirectory().getPath(), 'racecapture')
     else:
         return self.get_default_desktop_config_dir()
    def post_build_init(self, *args):
        if platform() == 'android':
            import android
            android.map_key(android.KEYCODE_BACK, 1001)

        window = EventLoop.window
        window.bind(on_keyboard=self.on_keyboard)
Пример #12
0
        def run_cmd(*args):
            '''Run the command
            '''
            # this is run inside a thread so take care, avoid gui ops
            try:
                _posix = True
                if sys.platform[0] == 'w':
                    _posix = False
                cmd = command
                if PY2 and isinstance(cmd, unicode):
                    cmd = command.encode(get_fs_encoding())
                if not self.shell:
                    cmd = shlex.split(cmd, posix=_posix)
                    for i in range(len(cmd)):
                        cmd[i] = cmd[i].replace('\x01', ' ')
                    map(lambda s: s.decode(get_fs_encoding()), cmd)
            except Exception as err:
                cmd = ''
                self.add_to_cache(''.join((str(err), ' <', command, ' >\n')))
            if len(cmd) > 0:
                prev_stdout = sys.stdout
                sys.stdout = self.stdout
                try:
                    # execute command
                    self.popen_obj = popen = subprocess.Popen(
                        cmd,
                        bufsize=0,
                        stdout=subprocess.PIPE,
                        stdin=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        preexec_fn=None,
                        close_fds=False,
                        shell=self.shell,
                        cwd=self.cur_dir.encode(get_fs_encoding()),
                        universal_newlines=False,
                        startupinfo=None,
                        creationflags=0)
                    popen_stdout_r = popen.stdout.readline
                    popen_stdout_flush = popen.stdout.flush
                    txt = popen_stdout_r()
                    plat = platform()
                    while txt:
                        # skip flush on android
                        if plat[0] != 'a':
                            popen_stdout_flush()

                        if isinstance(txt, bytes):
                            txt = txt.decode(get_fs_encoding())
                        add_to_cache(txt)
                        txt = popen_stdout_r()
                except (OSError, ValueError) as err:
                    add_to_cache(''.join(
                            (str(err),
                             ' < ', command, ' >\n')))
                    self.command_status = 'closed'
                    self.dispatch('on_subprocess_done')
                sys.stdout = prev_stdout
            self.popen_obj = None
            Clock.schedule_once(remove_command_interaction_widgets, 0)
Пример #13
0
 def new_collection(self, newname):
     collection = Collection(name=newname)
     if platform() == "android":
         collection.directory = "/sdcard/noGo/collections"
     else:
         collection.directory = "./games"
     collection.save()
     self.manager.refresh_collections_index()
Пример #14
0
 def get_default_data_dir(self):
     if platform() == 'android':
         from jnius import autoclass
         PythonActivity = autoclass('org.renpy.android.PythonActivity')
         activity = PythonActivity.mActivity
         return activity.getExternalFilesDir(None).getPath()
     else:
         return self.data_dir
Пример #15
0
 def new_collection(self, newname):
     collection = Collection(name=newname)
     if platform() == 'android':
         collection.directory = '/sdcard/noGo/collections'
     else:
         collection.directory = './games'
     collection.save()
     self.manager.refresh_collections_index()
Пример #16
0
    def post_build_init(self):
        """ Bind the android or the keyboard key """
        if platform() == "android":
            import android

            android.map_key(android.KEYCODE_BACK, 1001)
        win = Window
        win.bind(on_keyboard=self.key_handler)
Пример #17
0
    def density(self):
        '''Return the density of the screen. This value is 1 by default
        on desktop, and varies on android depending the screen.
        '''
        custom_density = environ.get('KIVY_METRICS_DENSITY')
        if custom_density:
            return float(custom_density)

        if platform() == 'android':
            import jnius
            Hardware = jnius.autoclass('org.renpy.android.Hardware')
            return Hardware.metrics.scaledDensity
        elif platform() == 'ios':
            # 0.75 is for mapping the same density as android tablet
            import ios
            return ios.get_scale() * 0.75

        return 1.0
Пример #18
0
 def save(self):
     self.finish_lazy_loading()
     if platform() == "android":
         filen = "/sdcard/noGo/" + self.name + ".json"
     else:
         filen = "." + "/collections/" + self.name + ".json"
     with open(filen, "w") as fileh:
         fileh.write(self.serialise())
     return filen
Пример #19
0
 def save(self):
     self.finish_lazy_loading()
     if platform() == 'android':
         filen = '/sdcard/noGo/' + self.name + '.json'
     else:
         filen = '.' + '/collections/' + self.name + '.json'
     with open(filen,'w') as fileh:
         fileh.write(self.serialise())
     return filen
Пример #20
0
    def post_build_init(self,ev):
        if platform() == 'android':
            import android
            android.map_key(android.KEYCODE_BACK,1001)

        win = Window
        win.bind(on_keyboard=self.my_key_handler)

        Clock.schedule_interval(self.save_all_boards,150)
Пример #21
0
 def on_keyboard(self, key, scancode=None, unicode=None, modifier=None):
     # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w
     # TODO If just CMD+w is pressed, only the window should be closed.
     is_osx = platform() == 'darwin'
     if key == 27 or (is_osx and key in (113, 119) and modifier == 1024):
         stopTouchApp()
         self.close()  #not sure what to do here
         return True
     super(WindowPygame, self).on_keyboard(key, scancode, unicode, modifier)
Пример #22
0
 def on_keyboard(self, key, scancode=None, unicode=None, modifier=None):
     # Quit if user presses ESC or the typical OSX shortcuts CMD+q or CMD+w
     # TODO If just CMD+w is pressed, only the window should be closed.
     is_osx = platform() == 'darwin'
     if key == 27 or (is_osx and key in (113, 119) and modifier == 1024):
         stopTouchApp()
         self.close()  #not sure what to do here
         return True
     super(WindowPygame, self).on_keyboard(key, scancode, unicode, modifier)
Пример #23
0
 def save(self):
     self.finish_lazy_loading()
     if platform() == 'android':
         filen = '/sdcard/noGo/' + self.name + '.json'
     else:
         filen = '.' + '/collections/' + self.name + '.json'
     with open(filen, 'w') as fileh:
         fileh.write(self.serialise())
     return filen
Пример #24
0
 def run(self):
     self.best_score = self.app.store.get('score')[
         'best']  # get the best score saved
     self.ids.label_best.text = 'Best score: ' + str(
         self.best_score)  #show it
     if platform(
     ) == 'android':  # if we are using android, we can show an ADs
         if (random.randint(
                 0, 5) == 1):  # get a random and show a ads in the menu
             revmob.show_popup()
Пример #25
0
 def save(self, filen='default'):
     if filen == 'default':
         if platform() == 'android':
             default_filen = '/sdcard/noGo/collections_list.json'
         else:
             default_filen = '.' + '/collections/collections_list.json'
         filen = default_filen
     colstr = self.serialise()
     with open(filen, 'w') as fileh:
         fileh.write(colstr)
Пример #26
0
 def save(self, filen="default"):
     if filen == "default":
         if platform() == "android":
             default_filen = "/sdcard/noGo/collections_list.json"
         else:
             default_filen = "." + "/collections/collections_list.json"
         filen = default_filen
     colstr = self.serialise()
     with open(filen, "w") as fileh:
         fileh.write(colstr)
Пример #27
0
 def save(self,filen='default'):
     if filen == 'default':
         if platform() == 'android':
             default_filen = '/sdcard/noGo/collections_list.json'
         else:
             default_filen = '.' + '/collections/collections_list.json'
         filen = default_filen
     colstr = self.serialise()
     with open(filen,'w') as fileh:
         fileh.write(colstr)
Пример #28
0
def _on_keyboard_handler(instance, key, scancode, codepoint, modifiers):
    if key == 293 and modifiers == []:  # F12
        instance.screenshot()
    elif key == 292 and modifiers == []:  # F11
        instance.rotation += 90
    elif key == 292 and modifiers == ['shift']:  # Shift + F11
        if platform() in ('win', 'linux', 'macosx'):
            instance.rotation = 0
            w, h = instance.size
            w, h = h, w
            instance.size = (w, h)
Пример #29
0
    def dpi(self):
        '''Return the DPI of the screen. Depending of the platform, the DPI can
        be taken from the Window provider (Desktop mainly), or from
        platform-specific module (like android/ios).
        '''
        custom_dpi = environ.get('KIVY_DPI')
        if custom_dpi:
            return float(custom_dpi)

        if platform() == 'android':
            import android
            return android.get_dpi()
        elif platform() == 'ios':
            import ios
            return ios.get_dpi()

        # for all other platforms..
        from kivy.base import EventLoop
        EventLoop.ensure_window()
        return EventLoop.window.dpi
Пример #30
0
 def get_new_comment(self,*args,**kwargs):
     print 'get new comment called'
     if self.comment_text == '[color=444444]Long press to add comment.[/color]':
         popup = Popup(content=CommentInput(board=self,comment=''),title='Edit comment:',size_hint=(0.85,0.85))
     else:
         popup = Popup(content=CommentInput(board=self,comment=self.comment_text),title='Edit comment:',size_hint=(0.85,0.55),pos=(0.075*Window.width, 0.95*Window.height))
     popup.content.popup = popup
     if platform() == 'android':
         import android
         android.vibrate(0.1)
     popup.open()
Пример #31
0
 def get_default_collection(self):
     collections = self.collections.collections
     print "current collections are", collections
     unsaved = filter(lambda j: j.name == "unsaved", collections)
     print "found name unsaved", unsaved
     if len(unsaved) > 0:
         unsaved = unsaved[0]
     else:
         unsaved = self.collections.new_collection("unsaved")
         self.manager.refresh_collections_index()
     if platform() == "android":
         unsaved.defaultdir = "/sdcard/noGo/collections/unsaved"
     return unsaved
Пример #32
0
 def get_default_collection(self):
     collections = self.collections.collections
     print 'current collections are', collections
     unsaved = filter(lambda j: j.name == 'unsaved', collections)
     print 'found name unsaved', unsaved
     if len(unsaved) > 0:
         unsaved = unsaved[0]
     else:
         unsaved = self.collections.new_collection('unsaved')
         self.manager.refresh_collections_index()
     if platform() == 'android':
         unsaved.defaultdir = '/sdcard/noGo/collections/unsaved'
     return unsaved
Пример #33
0
 def build(self):
     self.screens = ScreenManager(transition=FadeTransition(duration=0.4))
     self.gamescreen = GameScreen(name='game')
     self.screens.add_widget(HomeScreen(name='home'))
     self.screens.add_widget(self.gamescreen)
     self.screens.add_widget(AboutScreen(name='about'))
     parent = Window
     if platform() == 'ios' and (
         Window.width > 2000 or Window.height > 2000):
         self._scaler = Scaler(size=Window.size, scale=2)
         Window.add_widget(self._scaler)
         parent = self._scaler
     parent.add_widget(self.screens)
Пример #34
0
    def on_enter(self):
        if not self.fold2D is None:
            self.remove_widget(self.fold2D)
            self.fold2D = None
        self.fold2D = Fold2D(sequence = self.manager.curSequence, maxScore = self.manager.curMaxScore)
        self.add_widget(self.fold2D)

        from kivy.utils import platform
        if platform() == 'android':
            import android
            android.map_key(android.KEYCODE_BACK, 1001)

        win = Window
        win.bind(on_keyboard=self.hook_keyboard)
Пример #35
0
    def create_window(self, *largs):
        '''Will create the main window and configure it.

        .. warning::
            This method is called automatically at runtime. If you call it, it
            will recreate a RenderContext and Canvas. This mean you'll have a
            new graphics tree, and the old one will be unusable.

            This method exist to permit the creation of a new OpenGL context
            AFTER closing the first one. (Like using runTouchApp() and
            stopTouchApp()).

            This method have been only tested in unittest environment, and will
            be not suitable for Applications.

            Again, don't use this method unless you know exactly what you are
            doing !
        '''
        # just to be sure, if the trigger is set, and if this method is manually
        # called, unset the trigger
        Clock.unschedule(self.create_window)

        if not self.initialized:
            from kivy.core.gl import init_gl
            init_gl()

            # create the render context and canvas, only the first time.
            from kivy.graphics import RenderContext, Canvas
            self.render_context = RenderContext()
            self.canvas = Canvas()
            self.render_context.add(self.canvas)

        else:
            # if we get initialized more than once, then reload opengl state
            # after the second time.
            # XXX check how it's working on embed platform.
            if platform() == 'linux':
                # on linux, it's safe for just sending a resize.
                self.dispatch('on_resize', *self.system_size)

            else:
                # on other platform, window are recreated, we need to reload.
                from kivy.graphics.context import get_context
                get_context().reload()
                def ask_update(dt):
                    self.canvas.ask_update()
                Clock.schedule_once(ask_update, 0)

        # ensure the gl viewport is correct
        self.update_viewport()
Пример #36
0
    def create_window(self, *largs):
        '''Will create the main window and configure it.

        .. warning::
            This method is called automatically at runtime. If you call it, it
            will recreate a RenderContext and Canvas. This mean you'll have a
            new graphics tree, and the old one will be unusable.

            This method exist to permit the creation of a new OpenGL context
            AFTER closing the first one. (Like using runTouchApp() and
            stopTouchApp()).

            This method have been only tested in unittest environment, and will
            be not suitable for Applications.

            Again, don't use this method unless you know exactly what you are
            doing !
        '''
        # just to be sure, if the trigger is set, and if this method is manually
        # called, unset the trigger
        Clock.unschedule(self.create_window)

        if not self.initialized:
            from kivy.core.gl import init_gl
            init_gl()

            # create the render context and canvas, only the first time.
            from kivy.graphics import RenderContext, Canvas
            self.render_context = RenderContext()
            self.canvas = Canvas()
            self.render_context.add(self.canvas)

        else:
            # if we get initialized more than once, then reload opengl state
            # after the second time.
            # XXX check how it's working on embed platform.
            if platform() == 'linux':
                # on linux, it's safe for just sending a resize.
                self.dispatch('on_resize', *self.system_size)

            else:
                # on other platform, window are recreated, we need to reload.
                from kivy.graphics.context import get_context
                get_context().reload()
                Clock.schedule_once(lambda x: self.canvas.ask_update(), 0)
                self.dispatch('on_resize', *self.system_size)

        # ensure the gl viewport is correct
        self.update_viewport()
Пример #37
0
 def run_cmd(*l):
     '''Run the command
     '''
     # this is run inside a thread so take care, avoid gui ops
     try:
         _posix = True
         if sys.platform[0] == 'w':
             _posix = False
         cmd = shlex.split(str(command), posix=_posix)\
             if not self.shell else command
     except Exception as err:
         cmd = ''
         self.add_to_cache(u''.join((str(err), ' <', command, ' >\n')))
     if len(cmd) > 0:
         prev_stdout = sys.stdout
         sys.stdout = self.stdout
         try:
             # execute command
             self.popen_obj = popen = subprocess.Popen(
                 cmd,
                 bufsize=0,
                 stdout=subprocess.PIPE,
                 stdin=subprocess.PIPE,
                 stderr=subprocess.STDOUT,
                 preexec_fn=None,
                 close_fds=False,
                 shell=self.shell,
                 cwd=self.cur_dir,
                 env=self.environment,
                 universal_newlines=False,
                 startupinfo=None,
                 creationflags=0)
             popen_stdout_r = popen.stdout.readline
             popen_stdout_flush = popen.stdout.flush
             txt = popen_stdout_r()
             plat = platform()
             while txt != '':
                 # skip flush on android
                 if plat[0] != 'a':
                     popen_stdout_flush()
                 add_to_cache(txt.decode('utf8'))
                 txt = popen_stdout_r()
         except (OSError, ValueError) as err:
             add_to_cache(u''.join((str(err.strerror),
                                    ' < ', command, ' >\n')))
             self.command_status = 'closed'
         sys.stdout = prev_stdout
     self.popen_obj = None
     Clock.schedule_once(remove_command_interaction_widgets, 0)
Пример #38
0
 def run_cmd(*l):
     # this is run inside a thread so take care, avoid gui ops
     try:
         comand = command.encode('utf-8')
         _posix = True
         if sys.platform[0] == 'w':
             _posix = False
         cmd = shlex.split(str(command), posix=_posix)\
             if not self.shell else command
     except Exception as err:
         cmd = ''
         self.add_to_cache(u''.join((str(err), ' <', command, ' >\n')))
     if len(cmd) > 0:
         prev_stdout = sys.stdout
         sys.stdout = self.stdout
         Clock_schedule_once = Clock.schedule_once
         try:
             # execute command
             self.popen_obj = popen = subprocess.Popen(
                 cmd,
                 bufsize=0,
                 stdout=subprocess.PIPE,
                 stdin=subprocess.PIPE,
                 stderr=subprocess.STDOUT,
                 preexec_fn=None,
                 close_fds=False,
                 shell=self.shell,
                 cwd=self.cur_dir,
                 env=self.environment,
                 universal_newlines=False,
                 startupinfo=None,
                 creationflags=0)
             popen_stdout_r = popen.stdout.readline
             popen_stdout_flush = popen.stdout.flush
             txt = popen_stdout_r()
             plat = platform()
             while txt != '':
                 # skip flush on android
                 if plat[0] != 'a':
                     popen_stdout_flush()
                 add_to_cache(txt.decode('utf8'))
                 txt = popen_stdout_r()
         except (OSError, ValueError) as err:
             add_to_cache(u''.join((str(err.strerror),
                                    ' < ', command, ' >\n')))
         sys.stdout = prev_stdout
     self.popen_obj = None
     Clock.schedule_once(remove_command_interaction_widgets)
     self.command_status = 'closed'
Пример #39
0
 def new_collection(self, newname):
     if platform() == 'android':
         dirn = '/sdcard/noGo/collections/{0}'.format(newname)
     else:
         dirn = './games/{0}'.format(newname)
     print 'Making dir for new collection:', dirn
     try:
         mkdir(dirn)
     except OSError:
         print 'File exists! Add an error popup.'
     col = Collection(name=newname, defaultdir=dirn)
     col.save()
     self.collections = [col] + self.collections
     self.save()
     return col
Пример #40
0
    def fontscale(self):
        '''Return the fontscale user preference. This value is 1 by default, and
        can varies between 0.8-1.2.
        '''
        custom_fontscale = environ.get('KIVY_METRICS_FONTSCALE')
        if custom_fontscale:
            return float(custom_fontscale)

        if platform() == 'android':
            import jnius
            PythonActivity = jnius.autoclass('org.renpy.android.PythonActivity')
            config = PythonActivity.mActivity.getResources().getConfiguration()
            return config.fontScale

        return 1.0
Пример #41
0
 def _ensure_clipboard(self):
     global Clipboard
     if Clipboard is not None:
         return
     from kivy.core.clipboard import Clipboard
     _platform = platform()
     if _platform == 'win':
         self._clip_mime_type = 'text/plain;charset=utf-8'
         #windows clipboard uses a utf-16 encoding
         self._encoding = 'utf-16'
     elif _platform == 'linux':
         self._clip_mime_type = 'UTF8_STRING'
         self._encoding = 'utf-8'
     else:
         self._clip_mime_type = 'text/plain'
         self._encoding = 'utf-8'
Пример #42
0
    def _on_keyboard_settings(self, window, *largs):
        key = largs[0]
        setting_key = 282  # F1

        # android hack, if settings key is pygame K_MENU
        if platform() == 'android':
            import pygame
            setting_key = pygame.K_MENU

        if key == setting_key:
            # toggle settings panel
            if not self.open_settings():
                self.close_settings()
            return True
        if key == 27:
            return self.close_settings()
Пример #43
0
 def get_new_comment(self, *args, **kwargs):
     print 'get new comment called'
     if self.comment_text == '[color=444444]Long press to add comment.[/color]':
         popup = Popup(content=CommentInput(board=self, comment=''),
                       title='Edit comment:',
                       size_hint=(0.85, 0.85))
     else:
         popup = Popup(content=CommentInput(board=self,
                                            comment=self.comment_text),
                       title='Edit comment:',
                       size_hint=(0.85, 0.55),
                       pos=(0.075 * Window.width, 0.95 * Window.height))
     popup.content.popup = popup
     if platform() == 'android':
         import android
         android.vibrate(0.1)
     popup.open()
Пример #44
0
        def run_cmd(*l):
            # this is run inside a thread so take care, avoid gui ops
            try:
                comand = command.encode('utf-8')
                cmd = shlex.split(str(command))\
                   if not self.shell else command
            except Exception as err:
                cmd = ''
                self.add_to_cache(u''.join((str(err), ' <', command, ' >\n')))
            if len(cmd) > 0:
                prev_stdout = sys.stdout
                sys.stdout = self.stdout
                Clock_schedule_once = Clock.schedule_once
                try:
                    #execute command
                    #~ logger.Info('test command %s' % cmd)
                    self.popen_obj = popen = subprocess.Popen(
                        cmd,
                        bufsize=0,
                        stdout=subprocess.PIPE,
                        stdin=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        preexec_fn=None,
                        close_fds=False,
                        shell=self.shell,
                        cwd=self.cur_dir,
                        env=self.environment,
                        universal_newlines=False,
                        startupinfo=None,
                        creationflags=0)
                    popen_stdout_r = popen.stdout.readline
                    popen_stdout_flush = popen.stdout.flush
                    txt = popen_stdout_r()
                    plat = platform()
                    while txt != '':
                        # skip flush on android
                        if plat[0] != 'a':
                            popen_stdout_flush()

                        add_to_cache(txt.decode('utf8'))

                        txt = popen_stdout_r()
                except OSError or ValueError, err:
                    add_to_cache(u''.join(
                        (str(err.strerror), ' < ', command, ' >\n')))
                sys.stdout = prev_stdout
Пример #45
0
    def call_App(self):
        if platform() == "android":
            from jnius import cast
            from jnius import autoclass

            PythonActivity = autoclass('org.renpy.android.PythonActivity')
            PythonActivity = autoclass('org.renpy.android.PythonActivity')
            Intent = autoclass('android.content.Intent')
            Context = autoclass('android.content.Context')
            activity = cast('android.app.Activity', PythonActivity.mActivity)

            # manager = autoclass('android.content.pm.PackageManager')
            # or:
            manager = activity.getPackageManager()

            intent = manager.getLaunchIntentForPackage(
                "com.navikey.seven_ways")
            intent.addCategory(Intent.CATEGORY_LAUNCHER)

            activity.startActivity(intent)
Пример #46
0
    def share(self):
        if platform() == 'android': #check if the app is on Android
            # read more here: http://developer.android.com/training/sharing/send.html
           
            PythonActivity = autoclass('org.renpy.android.PythonActivity') #request the Kivy activity instance
            Intent = autoclass('android.content.Intent') # get the Android Intend class

            String = autoclass('java.lang.String') # get the Java object

            intent = Intent() # create a new Android Intent
            intent.setAction(Intent.ACTION_SEND) #set the action

            # to send a message, it need to be a Java char array. So we use the cast to convert and Java String to a Java Char array
            intent.putExtra(Intent.EXTRA_SUBJECT, cast('java.lang.CharSequence', String('Byte::Debugger() Tutorial #7')))
            intent.putExtra(Intent.EXTRA_TEXT, cast('java.lang.CharSequence', String("Testing Byte::Debugger() Tutorial #7, with Python for Android")))

            intent.setType('text/plain') #text message

            currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
            currentActivity.startActivity(intent) # show the intent in the game activity
Пример #47
0
    def share(self):
        if platform() == 'android':
            record = 'Мой рекорд в Against the Stream: ' + str(
                StreamGame.store.get('tito')['inpud']) + ' баллов.'

            # Запросить экземпляр Kivy activity
            PythonActivity = autoclass('org.renpy.android.PythonActivity')

            # Получить Intend-класс Android
            Intent = autoclass('android.content.Intent')

            # Получить Java-объект
            String = autoclass('java.lang.String')

            # Создать запрос на выполнение действия
            intent = Intent()

            # Установить действие
            intent.setAction(Intent.ACTION_SEND)

            # Чтобы отправить сообщение, нам нужен символьный массив Java. Поэтому преобразуем наше сообщение из Java String в массив Java Char
            intent.putExtra(
                Intent.EXTRA_SUBJECT,
                cast('java.lang.CharSequence',
                     String(
                         'Мой рекорд в Against the Stream'.decode('utf-8'))))
            intent.putExtra(
                Intent.EXTRA_TEXT,
                cast('java.lang.CharSequence', String(record.decode('utf-8'))))

            # Следующее сообщение
            intent.setType('text/plain')

            currentActivity = cast('android.app.Activity',
                                   PythonActivity.mActivity)

            # Показать действие во время игры
            currentActivity.startActivity(intent)
Пример #48
0
    def dpi(self):
        '''Return the DPI of the screen. Depending of the platform, the DPI can
        be taken from the Window provider (Desktop mainly), or from
        platform-specific module (like android/ios).

        On desktop, you can overload the value returned by the Window object
        (96 by default), by setting the environ KIVY_DPI::

            KIVY_DPI=200 python main.py

        .. versionadded:: 1.4.0
        '''
        custom_dpi = environ.get('KIVY_DPI')
        if custom_dpi:
            return float(custom_dpi)

        plat = platform()
        if plat == 'android':
            import android
            return android.get_dpi()

        # for all other platforms..
        self.ensure_window()
        return self.window.dpi
Пример #49
0
Файл: main.py Проект: zqqqq/2048
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, OptionProperty, ObjectProperty
from kivy.graphics import Color, BorderImage
from kivy.clock import Clock
from kivy.vector import Vector
from kivy.metrics import dp
from kivy.animation import Animation
from kivy.utils import get_color_from_hex
from kivy.core.window import Window
from kivy.utils import platform
from kivy.factory import Factory
from random import choice, random

platform = platform()
app = None

if platform == 'android':
    # Support for Google Play
    import gs_android
    leaderboard_highscore = 'CgkI0InGg4IYEAIQBg'
    achievement_block_32 = 'CgkI0InGg4IYEAIQCg'
    achievement_block_64 = 'CgkI0InGg4IYEAIQCQ'
    achievement_block_128 = 'CgkI0InGg4IYEAIQAQ'
    achievement_block_256 = 'CgkI0InGg4IYEAIQAg'
    achievement_block_512 = 'CgkI0InGg4IYEAIQAw'
    achievement_block_1024 = 'CgkI0InGg4IYEAIQBA'
    achievement_block_2048 = 'CgkI0InGg4IYEAIQBQ'
    achievement_block_4096 = 'CgkI0InGg4IYEAIQEg'
    achievement_100x_block_512 = 'CgkI0InGg4IYEAIQDA'
Пример #50
0
)

__version__ = '1.3.0-dev'

import sys
import shutil
from getopt import getopt, GetoptError
from os import environ, mkdir
from os.path import dirname, join, basename, exists, expanduser
from kivy.logger import Logger, LOG_LEVELS
from kivy.utils import platform

# internals for post-configuration
__kivy_post_configuration = []

if platform() == 'macosx' and sys.maxint < 9223372036854775807:
    r = '''Unsupported Python version detected!:
    Kivy requires a 64 bit version of Python to run on OS X. We strongly advise
    you to use the version of Python that is provided by Apple (don't use ports,
    fink or homebrew unless you know what you're doing).
    See http://kivy.org/docs/installation/installation-macosx.html for details.
    '''
    Logger.critical(r)


def require(version):
    '''Require can be used to check the minimum version required to run a Kivy
    application. For example, you can start your application code like this::

        import kivy
        kivy.require('1.0.1')
Пример #51
0
        '''Play the file'''
        self.state = 'play'
        self.dispatch('on_play')

    def stop(self):
        '''Stop playback'''
        self.state = 'stop'
        self.dispatch('on_stop')

    def seek(self, position):
        '''Seek to the <position> (in seconds)'''
        pass

    def on_play(self):
        pass

    def on_stop(self):
        pass


# Little trick here, don't activate gstreamer on window
# seem to have lot of crackle or something...
# XXX test in macosx
audio_libs = []
if platform() != 'win':
    audio_libs += [('gstreamer', 'audio_gstreamer')]
audio_libs += [('sdl', 'audio_sdl')]
audio_libs += [('pygame', 'audio_pygame')]

core_register_libs('audio', audio_libs)
Пример #52
0
class WindowPygame(WindowBase):

    def create_window(self, *largs):
        # ensure the mouse is still not up after window creation, otherwise, we
        # have some weird bugs
        self.dispatch('on_mouse_up', 0, 0, 'all', [])

        # force display to show (available only for fullscreen)
        displayidx = Config.getint('graphics', 'display')
        if not 'SDL_VIDEO_FULLSCREEN_HEAD' in environ and displayidx != -1:
            environ['SDL_VIDEO_FULLSCREEN_HEAD'] = '%d' % displayidx

        # init some opengl, same as before.
        self.flags = pygame.HWSURFACE | pygame.OPENGL | \
                     pygame.DOUBLEBUF

        # right now, activate resizable window only on linux.
        # on window / macosx, the opengl context is lost, and we need to
        # reconstruct everything. Check #168 for a state of the work.
        if platform() in ('linux', 'macosx', 'win') and \
            Config.getint('graphics', 'resizable'):
            self.flags |= pygame.RESIZABLE

        try:
            pygame.display.init()
        except pygame.error, e:
            raise CoreCriticalException(e.message)

        multisamples = Config.getint('graphics', 'multisamples')

        if multisamples > 0:
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
            pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES,
                multisamples)
        pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 16)
        pygame.display.gl_set_attribute(pygame.GL_STENCIL_SIZE, 1)
        pygame.display.set_caption(self.title)

        if self.position == 'auto':
            self._pos = None
        elif self.position == 'custom':
            self._pos = self.left, self.top
        else:
            raise ValueError('position token in configuration accept only '
                             '"auto" or "custom"')

        if self.fullscreen == 'fake':
            Logger.debug('WinPygame: Set window to fake fullscreen mode')
            self.flags |= pygame.NOFRAME
            # if no position set, in fake mode, we always need to set the
            # position. so replace 0, 0.
            if self._pos is None:
                self._pos = (0, 0)
            environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        elif self.fullscreen in ('auto', True):
            Logger.debug('WinPygame: Set window to fullscreen mode')
            self.flags |= pygame.FULLSCREEN

        elif self._pos is not None:
            environ['SDL_VIDEO_WINDOW_POS'] = '%d,%d' % self._pos

        # never stay with a None pos, application using w.center will be fired.
        self._pos = (0, 0)

        # prepare keyboard
        repeat_delay = int(Config.get('kivy', 'keyboard_repeat_delay'))
        repeat_rate = float(Config.get('kivy', 'keyboard_repeat_rate'))
        pygame.key.set_repeat(repeat_delay, int(1000. / repeat_rate))

        # set window icon before calling set_mode
        try:
            #filename_icon = Config.get('kivy', 'window_icon')
            filename_icon = self.icon or Config.get('kivy', 'window_icon')
            if filename_icon == '':
                logo_size = 512 if platform() == 'macosx' else 32
                filename_icon = join(kivy_home_dir, 'icon', 'kivy-icon-%d.png' %
                        logo_size)
            self.set_icon(filename_icon)
        except:
            Logger.exception('Window: cannot set icon')

        # try to use mode with multisamples
        try:
            self._pygame_set_mode()
        except pygame.error, e:
            if multisamples:
                Logger.warning('WinPygame: Video: failed (multisamples=%d)' %
                               multisamples)
                Logger.warning('WinPygame: trying without antialiasing')
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0)
                pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0)
                multisamples = 0
                try:
                    self._pygame_set_mode()
                except pygame.error, e:
                    raise CoreCriticalException(e.message)