Esempio n. 1
0
File: main.py Progetto: johtso/noGo
 def build_collections_list(self):
     if self.collections is None:
         self.collections = CollectionsList()
         cl = self.collections
         #progress = CollectionProgress()
         #cl.popup = progress
         #progress.open()
         #sleep(1)
         cl.from_file()
Esempio n. 2
0
import os
import glob

from sgfcollections import Collection, CollectionSgf, CollectionsList
from abstractboard import get_gameinfo_from_file

default_cols = ['Pro10','IMeijin','Kisei','ITengen','Gosei','Honinbo','Shusaku','Meijin','CJSuperGo','Tengen','Judan','Oza','NihonKiin','Ing']

collectionslist = CollectionsList()

for entry in default_cols:
    collection = Collection(name=entry,defaultdir='./games/' + entry)
    sgfs = glob.glob('./games/' + entry + '/*.sgf')
    for sgf in sgfs:
        info = get_gameinfo_from_file(sgf)
        game = collection.add_game(False)
        game.filen = sgf
        game.gameinfo = info
        game.save()
    collectionslist.collections.append(collection)
    collectionslist.save('indexed_collections.json')
Esempio n. 3
0
File: main.py Progetto: johtso/noGo
class GobanApp(App):
    version = StringProperty('0.4.0')
    manager = ObjectProperty(None, allownone=True)
    navdrawer = ObjectProperty(None, allownone=True)
    cache = ObjectProperty(WidgetCache())
    collections = ObjectProperty(None, allownone=True)

    stone_type = StringProperty('default')
    board_type = StringProperty('./media/boards/none.png')

    sounds = BooleanProperty(True)

    use_kivy_settings = True

    settings_widget = SettingsWithNoMenu

    title = 'noGo'
    name = 'noGo'

    prev_opened_file = StringProperty('')

    def build(self):
        print 'ENTERED BUILD()'
        t1 = time()
        # Load config
        #print 'user data dir is', self.user_data_dir
        config = self.config
        #print 'my config is',config

        sound = SoundLoader.load('./media/sounds/stone_sound5.mp3')
        sound.volume = 0.05
        self.stone_sound = sound

        # Get any json collection backups if on android
        if platform() == 'android':
            if not exists('/sdcard/noGo'):
                mkdir('/sdcard/noGo')
            if not exists('/sdcard/noGo/collections'):
                mkdir('/sdcard/noGo/collections')
            if not exists('/sdcard/noGo/collections/unsaved'):
                mkdir('/sdcard/noGo/collections/unsaved')
            json_backups = glob('/sdcard/noGo/*.json')
            for filen in json_backups:
                with open(filen,'r') as fileh:
                    filestr = fileh.read()
                if len(filestr) > 1:
                    name = filen.split('/')[-1]
                    copyfile(filen,'./collections/'+name)
           

        # Load collections
        # self.collections = CollectionsList().from_file()
        #self.build_collections_list()

        
        # Construct GUI
        sm = NogoManager(transition=SlideTransition(direction='left'))
        self.manager = sm
        sm.app = self

        # hv = Screen(name="Home")
        # hs = HomeScreen(managedby=sm)
        # hv.add_widget(hs)
        # sm.add_widget(hv)
        # sm.create_collections_index()

        t2 = time()
        print 'CONSTRUCTED manager and home',t2-t1

        # Get initial settings from config panel
        config = self.config
        sm.propagate_input_mode(config.getdefault('Board','input_mode','phone'))
        sm.propagate_coordinates_mode(config.getdefault('Board','coordinates','1'))
        self.stone_type = config.getdefault('Board','stone_graphics','simple')
        self.boardtype = config.getdefault('Board','board_graphics','simple')
        sm.propagate_boardtype_mode(self.boardtype)
        sm.propagate_view_mode(config.getdefault('Board','view_mode','phone'))
        self.set_sounds(config.getdefault('Board','sounds','0'))

        # Rebuild homescreen *after* setting phone/tablet mode
        #sm.add_widget(Screen(name='emptyscreen'))
        sm.rebuild_homescreen()
        sm.current = 'Home'


        self.bind(on_start=self.post_build_init)

        if platform() == 'android':
            from android import activity
            activity.bind(on_new_intent=self.on_intent)

            self.PythonActivity = autoclass('org.renpy.android.PythonActivity')
            self.ActivityInfo = autoclass('android.content.pm.ActivityInfo')
            
            

        t3 = time()
        print 'RETURNING SM',t3-t2, t3-t1

        #drawer = NogoDrawer()
        #drawer.add_widget(NavigationButtons())
        #drawer.add_widget(Image(source='media/logo_big2.png',
        #                        allow_stretch=True,
        #                        mipmap=True))
        #drawer.add_widget(sm)

        #self.navdrawer = drawer

        #return drawer
        
        return sm

    def build_collections_list(self):
        if self.collections is None:
            self.collections = CollectionsList()
            cl = self.collections
            #progress = CollectionProgress()
            #cl.popup = progress
            #progress.open()
            #sleep(1)
            cl.from_file()
            #progress.dismiss()
 
            
    def try_android_rotate(self,dir='portrait'):
        if dir == 'landscape':
            self.PythonActivity.mActivity.setRequestedOrientation(self.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
        else:
            self.PythonActivity.mActivity.setRequestedOrientation(self.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
        

    def on_intent(self,intent):
        print 'INTENT'
        print 'INTENT'
        print 'INTENT'
        print 'INTENT'
        print 'INTENT'
        print '!!!!!'
        print 'on_intent called'
        action = intent.getAction()
        print 'action is',action
        if action == 'android.intent.action.VIEW':
            print 'Trying to act on intent'
            #sleep(5)
            print 'Slept briefly'
            path = intent.getData().getPath()
            print 'going for path',path
            #self.manager.go_home()
            Clock.schedule_once(lambda j: self.manager.open_from_intentpath(path),1.1)
            #self.manager.open_from_intentpath(path)
    # def on_resume(self,*args):
    #     print 'RESUMED'
    #     print 'RESUMED'
    #     print 'RESUMED'
    #     print 'RESUMED'
    #     print 'RESUMED'
        

    def on_start(self,*args,**kwargs):
        print '\nON_START',args,kwargs,'\n'
        print 'environment',environ.get('PYTHON_OPENFILE')
        open_file = getenv('PYTHON_OPENFILE','').replace('%20',' ')
        print 'open_file is',open_file
        if open_file != '':
            putenv('PYTHON_OPENFILE','')
            Clock.schedule_once(lambda j: self.manager.open_from_intentpath(open_file),1.1)
        super(GobanApp,self).on_start(*args,**kwargs)

    # def on_resume(self,*args,**kwargs):
    #     # print 'ON_RESUME',args,kwargs
    #     # print 'environment',environ.get('PYTHON_OPENFILE')
    #     # open_file = getenv('PYTHON_OPENFILE','').replace('%20',' ')
    #     # print 'open_file is',open_file
    #     # if open_file != '' and open_file != self.prev_opened_file:
    #     #     self.prev_opened_file = open_file
    #     #     self.manager.new_board(from_file=open_file,mode='Navigate')
    #     super(GobanApp,self).on_resume(*args,**kwargs)

    def get_application_config(self):
        if platform() == 'android':
            dirn = self.user_data_dir + '/nogo.ini'
            return dirn
        return super(GobanApp,self).get_application_config()

    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)

    def my_key_handler(self,window,keycode1,keycode2,text,modifiers):
        if keycode1 == 27 or keycode1 == 1001:
            self.manager.handle_android_back()
            return True
        return False

    def _on_keyboard_settings(self, *args):
        pass

    # def display_settings(self, settings):
    #     try:
    #         p = self.settings_popup
    #     except AttributeError:
    #         self.settings_popup = Popup(content=settings,
    #                                     title='Settings',
    #                                     size_hint=(0.8, 0.8))
    #         p = self.settings_popup
    #     if p.content is not settings:
    #         p.content = settings
    #     p.open()
    # def close_settings(self, *args):
    #     try:
    #         p = self.settings_popup
    #         p.dismiss()
    #     except AttributeError:
    #         pass # Settings popup doesn't exist

    def display_settings(self, settings):
        manager = self.manager
        if not manager.has_screen('Settings'):
            s = Screen(name='Settings')
            s.add_widget(settings)
            manager.add_widget(s)
        manager.switch_and_set_back('Settings')

    def close_settings(self, *args):
        print 'Closing settings'
        if self.manager.current == 'Settings':
            self.manager.go_back()

    # def get_settings_widget(self):
    #     return SettingsWithNoMenu()
    #     # return SettingsWithTabbedPanel()
    #     # return SettingsWithSpinner()
    #     # return Settings()
    #     # s = Settings()
    #     # s.menu.width = dp(300)
    #     # return s

    def build_settings(self,settings):
        jsondata = json.dumps([
            {"type": "options",
             "title": "Input method",
             "desc": "Stone input method",
             "section": "Board",
             "key": "input_mode",
             "options": ["phone","tablet/stylus"]},
            {"type": "options",
             "title": "View mode",
             "desc": "Use compact phone view or expanded tablet view.",
             "section": "Board",
             "key": "view_mode",
             "options": ["phone","tablet"]},
            {"type": "bool",
             "title": "Show coordinates",
             "desc": "Whether or not to display coordinates on the board.",
             "section": "Board",
             "key": "coordinates",
             "true": "auto"},
            {"type": "bool",
             "title": "Show markers",
             "desc": "Whether to display board markers (square, triangle, letters, numbers etc.) when navigating games.",
             "section": "Board",
             "key": "markers",
             "true": "auto"},
            {"type": "options",
             "title": "Board graphics",
             "desc": "What kind of board graphics to use",
             "section": "Board",
             "key": "board_graphics",
             "options": ["plain light","plain dark","full board photo","board section photo 1","lightened board photo 1","board section photo 2"]},
            {"type": "options",
             "title": "Stone graphics",
             "desc": "What kind of stone graphics to use",
             "section": "Board",
             "key": "stone_graphics",
             "options": ["simple","slate and shell","bordered slate and shell","drawn by noGo"]},
            {"type": "bool",
             "title": "Play sounds",
             "desc": "Whether to play stone clack sound",
             "section": "Board",
             "key": "sounds",
             "true": "auto"},
            ])
        settings.add_json_panel('Board',
                                self.config,
                                data=jsondata)

    def build_config(self, config):
        config.setdefaults('Board',{'input_mode':'phone','view_mode':'phone','coordinates':False,'markers':True,'stone_graphics':'slate and shell','board_graphics':'board section photo 1','sounds':False})


    def on_pause(self,*args,**kwargs):
        print 'App asked to pause'
        self.save_all_boards()
        return True

    def on_stop(self,*args,**kwargs):
        print 'App asked to stop'
        self.save_all_boards()
        return super(GobanApp,self).on_stop()

    def save_all_boards(self,*args):
        names = self.manager.screen_names
        for name in names:
            if name[:5] == 'Board':
                board = self.manager.get_screen(name)
                try:
                    board.children[0].board.save_sgf()
                except IndexError:
                    print 'Tried to save board that doesn\'t exist, maybe didn\'t load properly'

    def on_config_change(self, config, section, key, value):
        super(GobanApp,self).on_config_change(config,section,key,value)
        print '%%% config change',config,section,key,value
        if key == 'input_mode':
            self.manager.propagate_input_mode(value)
        elif key == 'view_mode':
            self.manager.propagate_view_mode(value)
            self.manager.go_home()
        elif key == 'coordinates':
            print 'coordinates key pressed',config,section,key,value
            self.manager.propagate_coordinates_mode(int(value))
        elif key == 'markers':
            self.manager.propagate_markerdisplay_mode(int(value))
        elif key == 'stone_graphics':
            self.stone_type = value
            self.manager.propagate_stonegraphics_mode()
        elif key == 'board_graphics':
            self.board_type = value
            self.manager.propagate_boardtype_mode(value)
        elif key == 'sounds':
            print 'sounds key changed',value
            self.set_sounds(value)
        else:
            super(GobanApp,self).on_config_change(config,section,key,value)

    def new_collection_query(self):
        popup = Popup(content=CollectionNameChooser(manager=self),title='Pick a collection name...',size_hint_x=0.95,size_hint_y=None,height=(130,'sp'),pos_hint={'top':0.85})
        popup.content.popup = popup
        popup.open()
    def new_collection(self,newname):
        self.collections.new_collection(newname)
        self.collections.save()
        self.manager.refresh_collections_index()
    def query_delete_collection(self,sel):
        if len(sel)>0:
            popup = Popup(content=DeleteCollectionQuestion(manager=self,selection=sel),height=(140,'sp'),size_hint=(0.85,None),title='Are you sure?')
            popup.content.popup = popup
            popup.open()
    def delete_collection(self,selection):
        print 'asked to delete collection using',selection,type(selection)
        self.collections.delete_collection(selection[0].colname)
        self.manager.refresh_collections_index()
    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
    def move_collectionsgf(self,collectionsgf,selection,board=None):
        if len(selection) > 0:
            collection = selection[0].collection
        else:
            return False
        oldcollection = collectionsgf.collection
        collectionsgf.delete()
        collectionsgf.collection = collection
        collectionsgf.filen = collectionsgf.get_default_filen() + '.sgf'
        collection.games.append(collectionsgf)
        collection.save()
        self.manager.add_collection_refresh_reminder(collection)
        self.manager.add_collection_refresh_reminder(oldcollection)
        self.manager.collectionindex_to_refresh = True
        if board is not None:
            board.get_game_info()
            board.save_sgf()
            collectionsgf.save()
    def set_sounds(self,val):
        if val == 'False':
            val = False
        elif val == 'True':
            val = True
        else:
            val = int(val)
        self.sounds = bool(val)
    def play_stone_sound(self,*args):
        #print 'asked to play sound', self.sounds
        if self.sounds:
            self.stone_sound.seek(0)
            self.stone_sound.play()