def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList("/usr/share/zoneinfo/posix")

        icon_for_list = MultiIconItem()
        icon_for_list._ImgSurf = MyIconPool.GiveIconSurface("sys")
        icon_for_list._MyType = ICON_TYPES["STAT"]
        icon_for_list._Parent = self

        icon_for_list.Adjust(0, 0, 18, 18, 0)
        self._Icons["sys"] = icon_for_list

        self._BGpng = IconItem()
        self._BGpng._ImgSurf = MyIconPool.GiveIconSurface("empty")
        self._BGpng._MyType = ICON_TYPES["STAT"]
        self._BGpng._Parent = self
        self._BGpng.AddLabel("No timezones found on system!",
                             MyLangManager.TrFont("varela22"))
        self._BGpng.SetLableColor(MySkinManager.GiveColor('Disabled'))
        self._BGpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
Пример #2
0
    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList("/")

        icon_for_list = MultiIconItem()
        icon_for_list._ImgSurf = MyIconPool._Icons["sys"]
        icon_for_list._MyType = ICON_TYPES["STAT"]
        icon_for_list._Parent = self

        icon_for_list.Adjust(0, 0, 18, 18, 0)
        self._Icons["sys"] = icon_for_list

        self._BGpng = IconItem()
        self._BGpng._ImgSurf = MyIconPool._Icons["empty"]
        self._BGpng._MyType = ICON_TYPES["STAT"]
        self._BGpng._Parent = self
        self._BGpng.AddLabel(MyLangManager.Tr("Please upload data over Wi-Fi"),
                             MyLangManager.TrFont("varela22"))
        self._BGpng.SetLableColor(MySkinManager.GiveColor('Disabled'))
        self._BGpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
Пример #3
0
    def GenList(self):
        
        self._MyList = []
        if self._NetworkId != -1:
            self._AList["ip"]["value"] = "Not Connected"
            
            if self._Wireless.GetCurrentNetworkID(self._Wireless.GetIwconfig()) == self._NetworkId:
                ip = self._Wireless.GetWirelessIP('')
            
                if ip is not None:
                    self._AList["ip"]["value"] = ip
            
            self._AList["bssid"]["value"] = self._Wireless.GetWirelessProperty(self._NetworkId,"bssid")
        
        start_x  = 0
        start_y  = 0
        
        for i,v in enumerate( self._AList):
            li = InfoPageListItem()
            li._Parent = self
            li._PosX   = start_x
            li._PosY   = start_y + i*InfoPageListItem._Height
            li._Width  = Width
            li._Fonts["normal"] = self._ListFontObj
            li._Fonts["small"] = MyLangManager.TrFont("varela12")
            
            if self._AList[v]["label"] != "":
                li.Init(  self._AList[v]["label"] )
            else:
                li.Init( self._AList[v]["key"] )

            li._Flag = self._AList[v]["key"]

            li.SetSmallText( self._AList[v]["value"] )
            
            self._MyList.append(li)
Пример #4
0
class AirplanePage(Page):
    _FootMsg =  ["Nav","Rescue","","Back","Toggle"]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela13")
    
    _AList = {}

    _Scrolled = 0
    
    _BGwidth = 320
    _BGheight = 240-24-20

    _DrawOnce = False
    _Scroller = None

    _EasingDur = 30

    _airwire_y = 0
    _dialog_index = 0
    
    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

    def GenList(self):
        
        self._MyList = []
        
        
            
    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface( (self._Screen._Width,self._BGheight) )

        self._PosX = self._Index*self._Screen._Width 
        self._Width = self._Screen._Width ## equal to screen width
        self._Height = self._Screen._Height



        airwire = IconItem()
        airwire._ImgSurf = MyIconPool._Icons["airwire"]
        airwire._MyType = ICON_TYPES["STAT"]
        airwire._Parent = self
        airwire.Adjust(0,0,5,43,0)
        self._Icons["airwire"] = airwire

        GS = IconItem()
        GS._ImgSurf = MyIconPool._Icons["GS"]
        GS._MyType = ICON_TYPES["STAT"]
        GS._Parent = self
        GS.Adjust(0,0,72,95,0)
        self._Icons["GS"] = GS

        DialogBoxs = MultiIconItem()
        DialogBoxs._ImgSurf = MyIconPool._Icons["DialogBoxs"]
        DialogBoxs._MyType = ICON_TYPES["STAT"]
        DialogBoxs._Parent = self
        DialogBoxs._IconWidth = 134
        DialogBoxs._IconHeight = 93
        DialogBoxs.Adjust(0,0,134,372,0)
        self._Icons["DialogBoxs"] = DialogBoxs

        
        """
        bgpng = MultiIconItem()
        bgpng._ImgSurf = MyIconPool._Icons["about_bg"]
        bgpng._MyType = ICON_TYPES["STAT"]
        bgpng._Parent = self
        bgpng.Adjust(0,0,self._BGwidth,self._BGheight,0)
        self._Icons["bg"] = bgpng
        """
        
        
        self.GenList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
        self._Scroller.SetCanvasHWND(self._HWND)
        
        self.OnLoadCb()
        
    def ScrollDown(self):
        dis = 10
        if abs(self._Scrolled) <  (self._BGheight - self._Height)/2 + 0:
            self._PosY -= dis
            self._Scrolled -= dis
        
    def ScrollUp(self):
        dis = 10
        if self._PosY < 0:
            self._PosY += dis
            self._Scrolled += dis

    def ToggleModeAni(self): ## with animation
        out = commands.getstatusoutput('sudo rfkill list | grep yes | cut -d " " -f3')
        if "yes" in out[1]:
            data = self.EasingData(0,43)
            for _,v in enumerate(data):
                self._airwire_y -= v
                self._dialog_index = 2
                pygame.time.delay(40)

                self._Screen.Draw()
                self._Screen.SwapAndShow()
                
            commands.getstatusoutput("sudo rfkill unblock all")
            self._Screen._TitleBar._InAirPlaneMode = False

        else:
            data = self.EasingData(0,43)
            data.reverse()
            for _,v in enumerate(data):
                self._airwire_y += v
                self._dialog_index = 3
                pygame.time.delay(40)
                self._Screen.Draw()
                self._Screen.SwapAndShow()

            commands.getstatusoutput("sudo rfkill block all")
            self._Screen._TitleBar._InAirPlaneMode = True

        
    def ToggleMode(self):
        out = commands.getstatusoutput('sudo rfkill list | grep yes | cut -d " " -f3')
        print out
        if "yes" in out[1]:
            self._Screen._MsgBox.SetText("TurningOn")
            self._Screen._MsgBox.Draw()
            commands.getstatusoutput("sudo rfkill unblock all")
            self._Screen._TitleBar._InAirPlaneMode = False
        
        else:
            self._Screen._MsgBox.SetText("TurningOff")
            self._Screen._MsgBox.Draw()
            commands.getstatusoutput("sudo rfkill block all")
            self._Screen._TitleBar._InAirPlaneMode = True
    
    def UnBlockAll(self):
        self._Screen._MsgBox.SetText("TurningOn")
        self._Screen._MsgBox.Draw()
        commands.getstatusoutput("sudo rfkill unblock all")
        self._Screen._TitleBar._InAirPlaneMode = False
    
        
    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False
        out = commands.getstatusoutput('sudo rfkill list | grep yes | cut -d " " -f3')
        if "yes" in out[1]:
            self._Screen._TitleBar._InAirPlaneMode = True
            self._airwire_y = 50+43
            self._dialog_index = 1
        else:
            self._airwire_y = 50
            self._dialog_index = 0
            self._Screen._TitleBar._InAirPlaneMode = False
        
        
    def OnReturnBackCb(self):
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        
    def KeyDown(self,event):
        if event.key == CurKeys["A"] or event.key == CurKeys["Menu"]:
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["B"]:
            self.ToggleModeAni()
            """
            self.ToggleMode()
            self._Screen.SwapAndShow()
            
            pygame.time.delay(1000)
            
            self._Screen.Draw()
            self._Screen.SwapAndShow()
            """
        """
        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        """
        
        if event.key == CurKeys["X"]:
            self.UnBlockAll()
            self._Screen.SwapAndShow()
            pygame.time.delay(1000)
            self._Screen.Draw()
            self._Screen.SwapAndShow() 
        
            
    def Draw(self):
        self.ClearCanvas()

        self._Icons["DialogBoxs"].NewCoord(145,23)        
        self._Icons["airwire"].NewCoord(80,self._airwire_y)
        
        self._Icons["DialogBoxs"]._IconIndex = self._dialog_index
        
        self._Icons["DialogBoxs"].DrawTopLeft()
        self._Icons["airwire"].Draw()

        self._Icons["GS"].NewCoord(98,118)
        self._Icons["GS"].Draw()
        
        if self._HWND != None:
            self._HWND.fill((255,255,255))
            
            self._HWND.blit(self._CanvasHWND,(self._PosX,self._PosY,self._Width, self._Height ) )
Пример #5
0
class MusicLibListPage(Page):

    _Icons = {}
    _Selector = None
    _FootMsg = ["Nav", "", "Scan", "Back", "Add to Playlist"]
    _MyList = []
    _SwapMyList = []
    _ListFont = MyLangManager.TrFont("notosanscjk15")
    _MyStack = None

    _Scroller = None

    _BGpng = None
    _BGwidth = 56
    _BGheight = 70

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}
        self._CanvasHWND = None
        self._MyList = []
        self._SwapMyList = []
        self._MyStack = MusicLibStack()

    def SyncList(self, path):
        if myvars.Poller == None:
            return

        alist = myvars.Poller.listfiles(path)
        if alist == False:
            print("listfiles return false")
            return

        self._MyList = []
        self._SwapMyList = []

        start_x = 0
        start_y = 0
        hasparent = 0
        if self._MyStack.Length() > 0:
            hasparent = 1
            li = ListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._MyType = ICON_TYPES["DIR"]
            li._Parent = self
            li.Init("[..]")
            self._MyList.append(li)

        for i, v in enumerate(sorted(alist)):
            li = ListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + (i + hasparent) * ListItem._Height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._MyType = ICON_TYPES["FILE"]
            li._Parent = self

            if "directory" in v:
                li._MyType = ICON_TYPES["DIR"]
                dir_base_name = os.path.basename(v["directory"])
                li.Init(dir_base_name)
                li._Path = v["directory"]
            elif "file" in v:
                bname = os.path.basename(v["file"])
                li.Init(bname)
                li._Path = v["file"]

            else:
                li.Init("NoName")

            self._MyList.append(li)

        for i in self._MyList:
            self._SwapMyList.append(i)

    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList("/")

        icon_for_list = MultiIconItem()
        icon_for_list._ImgSurf = MyIconPool._Icons["sys"]
        icon_for_list._MyType = ICON_TYPES["STAT"]
        icon_for_list._Parent = self

        icon_for_list.Adjust(0, 0, 18, 18, 0)
        self._Icons["sys"] = icon_for_list

        self._BGpng = IconItem()
        self._BGpng._ImgSurf = MyIconPool._Icons["empty"]
        self._BGpng._MyType = ICON_TYPES["STAT"]
        self._BGpng._Parent = self
        self._BGpng.AddLabel(MyLangManager.Tr("Please upload data over Wi-Fi"),
                             MyLangManager.TrFont("varela22"))
        self._BGpng.SetLableColor(MySkinManager.GiveColor('Disabled'))
        self._BGpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()

    def Click(self):
        if len(self._MyList) == 0:
            return

        cur_li = self._MyList[self._PsIndex]

        if cur_li._MyType == ICON_TYPES["DIR"]:
            if cur_li._Path == "[..]":
                self._MyStack.Pop()
                self.SyncList(self._MyStack.Last())
                self._PsIndex = 0
            else:
                self._MyStack.Push(self._MyList[self._PsIndex]._Path)
                self.SyncList(self._MyStack.Last())
                self._PsIndex = 0

        if cur_li._MyType == ICON_TYPES["FILE"]:  ## add to playlist only
            myvars.Poller.addfile(cur_li._Path)
            myvars.PlayListPage.SyncList()
            print("add", cur_li._Path)

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def Rescan(self):
        self.SyncList("/")
        self._PsIndex = 0

    def KeyDown(self, event):

        if IsKeyMenuOrB(event.key) or event.key == CurKeys["Left"]:

            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        """
        if event.key == CurKeys["Right"]:
            self.FScrollDown(Step=5)
            self._Screen.Draw()
            self._Screen.SwapAndShow()
            
        if event.key == CurKeys["Left"]:
            self.FScrollUp(Step=5)
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        """

        if event.key == CurKeys["X"]:
            self.Rescan()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            self.Click()

    def Draw(self):
        self.ClearCanvas()
        """
        start_x = 0
        start_y = 0
        counter = 0
        
        self._MyList = []
        
        for i,v in enumerate(self._SwapMyList):
            if myvars.PlayListPage.InPlayList(v._Path):
                v._Active = True
            else:
                v._Active = False

            if v._Active == False:
                v.NewCoord(start_x, start_y+counter* ListItem._Height)
                counter+=1
                self._MyList.append(v)
        """

        if len(self._MyList) == 0:
            self._BGpng.NewCoord(self._Width / 2, self._Height / 2)
            self._BGpng.Draw()
            return

        else:
            if len(self._MyList) * ListItem._Height > self._Height:
                self._Ps._Width = self._Width - 11

                self._Ps.Draw()
                for i in self._MyList:
                    if myvars.PlayListPage.InPlayList(i._Path):
                        i._Active = True
                    else:
                        i._Active = False

                    if i._PosY > self._Height + self._Height / 2:
                        break

                    if i._PosY < 0:
                        continue

                    i.Draw()

                self._Scroller.UpdateSize(
                    len(self._MyList) * ListItem._Height,
                    self._PsIndex * ListItem._Height)
                self._Scroller.Draw()
            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:
                    if myvars.PlayListPage.InPlayList(i._Path):
                        i._Active = True
                    else:
                        i._Active = False

                    if i._PosY > self._Height + self._Height / 2:
                        break

                    if i._PosY < 0:
                        continue

                    i.Draw()
Пример #6
0
class GameStorePage(Page):
    _FootMsg = ["Nav", "Update", "Up", "Back", "Select"]
    _MyList = []
    _ListFont12 = MyLangManager.TrFont("notosanscjk12")
    _ListFont15 = MyLangManager.TrFont("varela15")

    _AList = {}

    # _Scrolled = 0

    _BGwidth = 320
    _BGheight = 240 - 24 - 20

    _DrawOnce = False
    _Scroller = None
    _InfoPage = None
    _Downloading = None
    _aria2_db = "aria2tasks.db"
    _warehouse_db = "warehouse.db"
    _GobjTimer = -1

    _Scrolled_cnt = 0

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}
        self._MyStack = RPCStack()
        #title file type
        ## Two level url , only github.com

        repos = [{
            "title": "github.com/clockworkpi/warehouse",
            "file":
            "https://raw.githubusercontent.com/clockworkpi/warehouse/master/index.json",
            "type": "source"
        }]
        self._MyStack.Push(repos)

    def GObjectUpdateProcessInterval(self):
        ret = True
        dirty = False
        for x in self._MyList:
            if x._Type == "launcher" or x._Type == "pico8" or x._Type == "tic80":
                percent = config.RPC.getPercent(x._Value["file"])
                if percent is not None:
                    x.SetSmallText(str(percent) + "%")
                    dirty = True
                else:
                    x.SetSmallText("")

        if self._Screen.CurPage() == self and dirty == True:
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        return ret

    def SyncWarehouse(self):
        try:
            conn = sqlite3.connect(self._warehouse_db)
            conn.row_factory = dict_factory
            c = conn.cursor()
            ret = c.execute("SELECT * FROM warehouse").fetchall()
            conn.close()
            return ret
        except Exception as ex:
            print(ex)
            return None
        return None

    def SyncTasks(self):
        try:
            conn = sqlite3.connect(self._aria2_db)
            conn.row_factory = dict_factory
            c = conn.cursor()
            ret = c.execute("SELECT * FROM tasks").fetchall()
            conn.close()
            return ret
        except Exception as ex:
            print(ex)
            return None
        return None

    def SyncList(self):

        self._MyList = []

        start_x = 0
        start_y = 0
        last_height = 0

        repos = []
        stk = self._MyStack.Last()
        stk_lev = self._MyStack.Length()
        repos.extend(stk)
        add_new_house = [{
            "title": "Add new warehouse...",
            "file": "master/index.json",
            "type": "add_house",
            "status": "complete"
        }]

        if stk_lev == 1:  # on top
            ware_menu = self.SyncWarehouse()
            if ware_menu != None and len(ware_menu) > 0:
                #print(ware_menu)
                repos.extend(ware_menu)

            tasks_menu = self.SyncTasks()
            if tasks_menu != None and len(tasks_menu) > 0:
                #print(tasks_menu)
                repos.extend(tasks_menu)

            #print(repos)
            repos.extend(add_new_house)

        for i, u in enumerate(repos):
            #print(i,u)
            li = GameStoreListItem()
            li._CanvasHWND = self._CanvasHWND
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + last_height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont15
            li._Fonts["small"] = self._ListFont12
            li._Active = False
            li._ReadOnly = True
            li._Value = u
            li._Type = u["type"]
            li.Init(u["title"])

            if stk_lev > 1:
                remote_file_url = u["file"]
                menu_file = remote_file_url.split(
                    "raw.githubusercontent.com")[1]
                local_menu_file = "%s/aria2download%s" % (
                    os.path.expanduser('~'), menu_file)

                if FileExists(local_menu_file):
                    li._ReadOnly = False
                else:
                    li._ReadOnly = True
            elif stk_lev == 1:
                if "status" in u:
                    if u["status"] == "complete":
                        li._ReadOnly = False

                if u["type"] == "source":
                    li._ReadOnly = False

            last_height += li._Height

            if li._Type == "launcher" or li._Type == "pico8" or li._Type == "tic80":
                li.SetSmallText("")

            self._MyList.append(li)

        self.RefreshPsIndex()

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface(
                    (self._Screen._Width, self._BGheight))

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        done = IconItem()
        done._ImgSurf = MyIconPool.GiveIconSurface("done")
        done._MyType = ICON_TYPES["STAT"]
        done._Parent = self
        self._Icons["done"] = done

        ps = InfoPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
        self._Scroller.SetCanvasHWND(self._CanvasHWND)

        self._remove_page = YesCancelConfirmPage()
        self._remove_page._Screen = self._Screen
        self._remove_page._StartOrA_Event = self.RemoveGame

        self._remove_page._Name = "Are you sure?"
        self._remove_page.Init()

        self._Keyboard = Keyboard()
        self._Keyboard._Name = "Enter warehouse addr"
        self._Keyboard._FootMsg = ["Nav.", "Add", "ABC", "Backspace", "Enter"]
        self._Keyboard._Screen = self._Screen
        self._Keyboard.Init()
        self._Keyboard.SetPassword("github.com/clockworkpi/warehouse")
        self._Keyboard._Caller = self

        self._PreviewPage = ImageDownloadProcessPage()
        self._PreviewPage._Screen = self._Screen
        self._PreviewPage._Name = "Preview"
        self._PreviewPage.Init()

        self._LoadHousePage = LoadHousePage()
        self._LoadHousePage._Screen = self._Screen
        self._LoadHousePage._Name = "Warehouse"
        self._LoadHousePage._Caller = self
        self._LoadHousePage.Init()

    def ResetHouse(self):
        if self._PsIndex > len(self._MyList) - 1:
            return
        cur_li = self._MyList[self._PsIndex]
        if cur_li._Value["type"] == "source":
            remote_file_url = cur_li._Value["file"]
            menu_file = remote_file_url.split("raw.githubusercontent.com")[
                1]  #assume master branch
            local_menu_file = "%s/aria2download%s" % (os.path.expanduser('~'),
                                                      menu_file)
            local_menu_file_path = os.path.dirname(local_menu_file)
            print(local_menu_file_path)
            local_jsons = glob.glob(local_menu_file_path + "/**/*.json")
            try:
                if os.path.exists(local_menu_file):
                    os.remove(local_menu_file)
                if os.path.exists(local_menu_file + ".aria2"):
                    os.remove(local_menu_file + ".aria2")

                for x in local_jsons:
                    os.remove(x)

            except Exception as ex:
                print(ex)

            self._Screen._MsgBox.SetText("Done")
            self._Screen._MsgBox.Draw()
            self._Screen.SwapAndShow()

    def LoadHouse(self):
        if self._PsIndex > len(self._MyList) - 1:
            return
        cur_li = self._MyList[self._PsIndex]
        if cur_li._Value["type"] == "source" or cur_li._Value["type"] == "dir":

            self._LoadHousePage._URL = cur_li._Value["file"]
            self._Screen.PushPage(self._LoadHousePage)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def PreviewGame(self):
        if self._PsIndex > len(self._MyList) - 1:
            return
        cur_li = self._MyList[self._PsIndex]
        if cur_li._Value["type"] == "launcher" or cur_li._Value[
                "type"] == "pico8" or cur_li._Value["type"] == "tic80":
            if "shots" in cur_li._Value:
                print(cur_li._Value["shots"])
                self._PreviewPage._URL = cur_li._Value["shots"]
                self._Screen.PushPage(self._PreviewPage)
                self._Screen.Draw()
                self._Screen.SwapAndShow()

    def RemoveGame(self):
        if self._PsIndex > len(self._MyList) - 1:
            return

        cur_li = self._MyList[self._PsIndex]
        #if cur_li._Active == True:
        #    return
        print("Remove cur_li._Value", cur_li._Value)

        if cur_li._Value["type"] == "source":
            print("remove a source")
            try:
                conn = sqlite3.connect(self._warehouse_db)
                conn.row_factory = dict_factory
                c = conn.cursor()
                c.execute("DELETE FROM warehouse WHERE file = '%s'" %
                          cur_li._Value["file"])
                conn.commit()
                conn.close()
            except Exception as ex:
                print(ex)
        elif cur_li._Value["type"] == "launcher" or cur_li._Value[
                "type"] == "pico8" or cur_li._Value["type"] == "tic80":
            remote_file_url = cur_li._Value["file"]
            menu_file = remote_file_url.split("raw.githubusercontent.com")[1]
            local_menu_file = "%s/aria2download%s" % (os.path.expanduser('~'),
                                                      menu_file)
            local_menu_file_path = os.path.dirname(local_menu_file)

            gid, ret = config.RPC.urlDownloading(remote_file_url)
            if ret == True:
                config.RPC.remove(gid)

            try:
                if os.path.exists(local_menu_file):
                    os.remove(local_menu_file)
                if os.path.exists(local_menu_file + ".aria2"):
                    os.remove(local_menu_file + ".aria2")
                if os.path.exists(
                        os.path.join(local_menu_file_path,
                                     cur_li._Value["title"])):
                    rmtree(
                        os.path.join(local_menu_file_path,
                                     cur_li._Value["title"]))

            except Exception as ex:
                print(ex)

    def Click(self):
        if self._PsIndex > len(self._MyList) - 1:
            return

        cur_li = self._MyList[self._PsIndex]
        #if cur_li._Active == True:
        #    return

        print("cur_li._Value", cur_li._Value)

        if cur_li._Value["type"] == "source" or cur_li._Value["type"] == "dir":
            remote_file_url = cur_li._Value["file"]
            menu_file = remote_file_url.split("raw.githubusercontent.com")[
                1]  #assume master branch
            local_menu_file = "%s/aria2download%s" % (os.path.expanduser('~'),
                                                      menu_file)
            print(local_menu_file)
            if FileExists(local_menu_file) == False:
                self.LoadHouse()
            else:
                #read the local_menu_file, push into stack,display menu
                self._Downloading = None
                try:
                    with open(local_menu_file) as json_file:
                        local_menu_json = json.load(json_file)
                        print(local_menu_json)
                        self._MyStack.Push(local_menu_json["list"])

                    self.SyncList()
                    self._Screen.Draw()
                    self._Screen.SwapAndShow()
                except Exception as ex:
                    print(ex)
                    self._Screen._MsgBox.SetText("Open house failed ")
                    self._Screen._MsgBox.Draw()
                    self._Screen.SwapAndShow()

        elif cur_li._Value["type"] == "add_house":
            print("show keyboard to add ware house")
            self._Screen.PushCurPage()
            self._Screen.SetCurPage(self._Keyboard)
        else:
            #download the game probably
            remote_file_url = cur_li._Value["file"]
            menu_file = remote_file_url.split("raw.githubusercontent.com")[1]
            local_menu_file = "%s/aria2download%s" % (os.path.expanduser('~'),
                                                      menu_file)

            if FileExists(local_menu_file) == False:
                gid, ret = config.RPC.urlDownloading(remote_file_url)
                if ret == False:
                    gid = config.RPC.addUri(remote_file_url,
                                            options={"out": menu_file})
                    self._Downloading = gid
                    print("stack length ", self._MyStack.Length())
                    """
                    if self._MyStack.Length() > 1:## not on the top list page
                        try:
                            conn = sqlite3.connect(self._aria2_db)
                            c = conn.cursor()
                            c.execute("INSERT INTO tasks(gid,title,file,type,status,fav) VALUES ('"+gid+"','"+cur_li._Value["title"]+"','"+cur_li._Value["file"]+"','"+cur_li._Value["type"]+"','active','0')")

                            conn.commit()
                            conn.close()
                        except Exception as ex:
                            print("SQLITE3 ",ex)
                    """
                else:
                    print(
                        config.RPC.tellStatus(
                            gid, ["status", "totalLength", "completedLength"]))

                    self._Screen._MsgBox.SetText("Getting the game now")
                    self._Screen._MsgBox.Draw()
                    self._Screen.SwapAndShow()

                    pygame.time.delay(800)
                    self._Screen._TitleBar.Redraw()

            else:
                print("file downloaded"
                      )  # maybe check it if is installed,then execute it
                if cur_li._Value[
                        "type"] == "launcher" and cur_li._ReadOnly == False:
                    local_menu_file_path = os.path.dirname(local_menu_file)
                    game_sh = os.path.join(local_menu_file_path,
                                           cur_li._Value["title"],
                                           cur_li._Value["title"] + ".sh")
                    #game_sh = reconstruct_broken_string( game_sh)
                    print("run game: ", game_sh, os.path.exists(game_sh))
                    self._Screen.RunEXE(game_sh)

                if cur_li._Value[
                        "type"] == "pico8" and cur_li._ReadOnly == False:
                    if os.path.exists(
                            "/home/cpi/games/PICO-8/pico-8/pico8") == True:
                        game_sh = "/home/cpi/launcher/Menu/GameShell/50_PICO-8/PICO-8.sh"
                        self._Screen.RunEXE(game_sh)
                    else:
                        self._Screen._MsgBox.SetText("Purchase pico8")
                        self._Screen._MsgBox.Draw()
                        self._Screen.SwapAndShow()
                        pygame.time.delay(800)

                if cur_li._Value[
                        "type"] == "tic80" and cur_li._ReadOnly == False:
                    game_sh = "/home/cpi/apps/Menu/51_TIC-80/TIC-80.sh"
                    self._Screen.RunEXE(game_sh)

    def OnAria2CompleteCb(self, gid):
        print("OnAria2CompleteCb ", gid)
        self.SyncList()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def raw_github_com(self, _url):  #eg: github.com/clockworkpi/warehouse
        if _url.startswith("github.com") == False:
            return False
        parts = _url.split("/")
        if len(parts) != 3:
            return False
        return "/".join([
            "https://raw.githubusercontent.com", parts[1], parts[2],
            "master/index.json"
        ])

    def OnKbdReturnBackCb(self):
        inputed = "".join(self._Keyboard._Textarea._MyWords).strip()
        inputed = inputed.replace("http://", "")
        inputed = inputed.replace("https://", "")

        if inputed.endswith(".git"):
            inputed = inputed[:len(inputed) - 4]
        if inputed.endswith("/"):
            inputed = inputed[:len(inputed) - 1]

        print("last: ", inputed)
        try:
            conn = sqlite3.connect(self._warehouse_db)
            conn.row_factory = dict_factory
            c = conn.cursor()
            ret = c.execute("SELECT * FROM warehouse WHERE title='%s'" %
                            inputed).fetchone()
            if ret != None:
                self._Screen._MsgBox.SetText("Warehouse existed!")
                self._Screen._MsgBox.Draw()
                self._Screen.SwapAndShow()
            else:
                if "github.com/clockworkpi/warehouse" in inputed:
                    self._Screen._MsgBox.SetText("Warehouse existed!")
                    self._Screen._MsgBox.Draw()
                    self._Screen.SwapAndShow()
                else:
                    valid_url = self.raw_github_com(inputed)

                    if valid_url == False:
                        self._Screen._MsgBox.SetText("Warehouse url error!")
                        self._Screen._MsgBox.Draw()
                        self._Screen.SwapAndShow()
                    else:
                        sql_insert = """ INSERT INTO warehouse(title,file,type) VALUES(
                                     '%s',
                                     '%s',
                                     'source');""" % (inputed, valid_url)

                        c.execute(sql_insert)
                        conn.commit()
                        self.SyncList()
                        self._Screen.Draw()
                        self._Screen.SwapAndShow()
            conn.close()
        except Exception as ex:
            print(ex)

    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False
        #sync
        print("OnLoadCb")
        if self._MyStack.Length() == 1:
            self._FootMsg[2] = "Remove"
            self._FootMsg[1] = "Update"
        else:
            self._FootMsg[2] = "Remove"
            self._FootMsg[1] = "Preview"

        self._GobjTimer = gobject.timeout_add(
            500, self.GObjectUpdateProcessInterval)

        self.SyncList()

    def OnReturnBackCb(self):
        if self._MyStack.Length() == 1:
            self._FootMsg[2] = "Remove"
            self._FootMsg[1] = "Update"
        else:
            self._FootMsg[2] = "Remove"
            self._FootMsg[1] = "Preview"

        self.SyncList()
        self.RestoreScrolled()

        self._Screen.Draw()
        self._Screen.SwapAndShow()
        """
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        """

    # def ScrollDown(self):
    # if len(self._MyList) == 0:
    # return
    # self._PsIndex += 1
    # if self._PsIndex >= len(self._MyList):
    # self._PsIndex = len(self._MyList)-1

    # cur_li = self._MyList[self._PsIndex]
    # if cur_li._PosY+cur_li._Height > self._Height:
    # for i in range(0, len(self._MyList)):
    # self._MyList[i]._PosY -= self._MyList[i]._Height

    # self._Scrolled_cnt -= self._MyList[i]._Height

    # def ScrollUp(self):
    # if len(self._MyList) == 0:
    # return
    # self._PsIndex -= 1
    # if self._PsIndex < 0:
    # self._PsIndex = 0
    # cur_li = self._MyList[self._PsIndex]
    # if cur_li._PosY < 0:
    # for i in range(0, len(self._MyList)):
    # self._MyList[i]._PosY += self._MyList[i]._Height

    # self._Scrolled_cnt += self._MyList[i]._Height

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):

            if self._MyStack.Length() > 1:
                self._MyStack.Pop()
                if self._MyStack.Length() == 1:
                    self._FootMsg[2] = "Remove"
                    self._FootMsg[1] = "Update"
                else:
                    self._FootMsg[2] = "Remove"
                    self._FootMsg[1] = "Preview"
                    if self._MyStack.Length() == 2:
                        self._FootMsg[2] = ""
                        self._FootMsg[1] = ""

                self.SyncList()
                self._Screen.Draw()
                self._Screen.SwapAndShow()

            elif self._MyStack.Length() == 1:
                self.ReturnToUpLevelPage()
                self._Screen.Draw()
                self._Screen.SwapAndShow()
                gobject.source_remove(self._GobjTimer)

        if IsKeyStartOrA(event.key):
            self.Click()

            if self._MyStack.Length() == 1:
                self._FootMsg[2] = "Remove"
                self._FootMsg[1] = "Update"
            else:
                self._FootMsg[2] = "Remove"
                self._FootMsg[1] = "Preview"
                if self._MyStack.Length() == 2:
                    self._FootMsg[2] = ""
                    self._FootMsg[1] = ""

            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["X"]:
            #print(self._MyStack.Length() )
            if self._PsIndex <= len(self._MyList) - 1:
                cur_li = self._MyList[self._PsIndex]
                if cur_li._Type != "dir":
                    if self._MyStack.Length() == 1 and self._PsIndex == 0:
                        pass
                        #predefined source
                    else:
                        self._Screen.PushPage(self._remove_page)
                        self._remove_page._StartOrA_Event = self.RemoveGame
                        self._Screen.Draw()
                        self._Screen.SwapAndShow()
                return

            self.SyncList()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Y"]:
            if self._MyStack.Length() == 1:
                self.ResetHouse()
            else:
                self.PreviewGame()

        if event.key == CurKeys["Up"]:
            # self.ScrollUp()
            self.SpeedScroll(event.key)
            self.ScrollUp(self._ScrollStep)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Down"]:
            # self.ScrollDown()
            self.SpeedScroll(event.key)
            self.ScrollDown(self._ScrollStep)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Right"]:  # PageDown
            self.ScrollDown(5)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Left"]:  # PageUp
            self.ScrollUp(5)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def RestoreScrolled(self):
        for i in range(0, len(self._MyList)):
            self._MyList[i]._PosY += self._Scrolled_cnt

    def Draw(self):

        self.ClearCanvas()
        if len(self._MyList) == 0:
            return

        else:
            if len(self._MyList) * self._MyList[0]._Height > self._Height:
                self._Ps._Width = self._Width - 11
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()
                self._Scroller.UpdateSize(
                    len(self._MyList) * self._MyList[0]._Height,
                    self._PsIndex * self._MyList[0]._Height)
                self._Scroller.Draw()

            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()

        if self._HWND != None:
            self._HWND.fill(MySkinManager.GiveColor("White"))

            self._HWND.blit(
                self._CanvasHWND,
                (self._PosX, self._PosY, self._Width, self._Height))
Пример #7
0
class AboutPage(Page):
    _FootMsg =  ["Nav.","","","Back",""]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela13")
    
    _AList = {}

    _Scrolled = 0
    
    _BGwidth = 480
    _BGheight = 272

    _DrawOnce = False
    _Scroller = None
    
    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

    def Uname(self):
        
        out = {}
        out["key"]="uname"
        out["label"]= "Kernel:"
        st = subprocess.check_output(["uname","-srmo"])
        st = st.strip("\n")
        st = st.strip("\t")
        out["value"] = st
        self._AList["uname"] = out

        return
    
    def CpuMhz(self):

        try:
            with open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq") as f:
                content = f.readlines()
            content = [x.strip() for x in content]
            
        except:
            print("open %s failed" % "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq")
            content = ["0"]
        
        mhz = int(content[0]) / 1000.0

        cpuscalemhz = {}
        cpuscalemhz["key"] = "cpuscalemhz"
        cpuscalemhz["label"] = "CPU Mhz:"
        cpuscalemhz["value"] = str(mhz)
        self._AList["cpuscalemhz"] = cpuscalemhz
        
        return 
    
    def CpuInfo(self):
        last_processor = 0
        with open("/proc/cpuinfo") as f:
            for line in f:
                if line.startswith("processor"):
                    parts = line.split(":")
                    cur_processor_number = int( parts[1].strip())
                    if cur_processor_number > last_processor:
                        last_processor = cur_processor_number
                    
                if line.startswith("model name"):
                    parts = line.split(":")
#                    print( parts[1].strip() )
                    processor = {}
                    processor["key"]="processor"
                    processor["label"] = "Processor:"
                    processor["value"] = parts[1].strip()
                    
                    self._AList["processor"] = processor
                    
                if line.startswith("cpu MHz"):
                    parts = line.split(":")
#                    print(parts[1].strip() )
                    cpumhz = {}
                    cpumhz["key"] = "cpumhz"
                    cpumhz["label"] = "CPU MHz:"
                    cpumhz["value"] = parts[1].strip()

                    self._AList["cpumhz"] = cpumhz
                if line.startswith("cpu cores"):
                    parts = line.split(":")
#                    print(parts[1].strip() )
                    cpucores = {}
                    cpucores["key"] = "cpucores"
                    cpucores["label"] = "CPU cores:"
                    cpucores["value"] = parts[1].strip()
                    self._AList["cpucores"] = cpucores
                if line.startswith("Features"):
                    parts = line.split(":")
#                    print(parts[1].strip() )
                    f_ = {}
                    f_["key"] = "features"
                    f_["label"] = "Features:"
                    f_["value"] = parts[1].strip()
                    self._AList["features"] = f_
                    
                if line.startswith("flags"):
                    parts = line.split(":")
#                    print(parts[1].strip() )
                    flags = {}
                    flags["key"] = "flags"
                    flags["label"] = "Flags:"
                    flags["value"] = parts[1].strip()
                    self._AList["flags"] = flags
                    

        if last_processor > 0:
            arm_cores = {}
            arm_cores["key"]= "armcores"
            arm_cores["label"] = "CPU cores:"
            arm_cores["value"] = str(last_processor + 1)
            self._AList["armcores"] = arm_cores
        
    def MemInfo(self):

        with open("/proc/meminfo") as f:
            for line in f:
                if line.startswith("MemTotal"):
                    parts = line.split(":")
                    parts[1] = parts[1].replace("kB","")
                    print(   parts[1].strip() )

                    memory = {}
                    memory["key"] = "memory"
                    memory["label"] = "Memory:"
                    memory["value"] = str( int(parts[1].strip())/1000.0) +" MB"
                    self._AList["memory"] = memory                    
                    break
    def BatteryInfo(self):
        batteryinfo = {}
        batteryinfo["key"] = "batteryinfo"
        batteryinfo["label"] = "Battery:"
        charging_string = "Discharging"
        if BatteryAbstraction.IsCharging():
            charging_string = "Charging"

        batteryinfo["value"] = "{}/{} mAh, {}%, {}".format(
            BatteryAbstraction.CurrentVoltage(),
            BatteryAbstraction.MaxVoltage(),
            BatteryAbstraction.AsPercentage(),
            charging_string
        )
        self._AList["batteryinfo"] = batteryinfo




    def PortInfo1(self):
        portinfo = {}
        portinfo["key"] = "portinfo1"
        portinfo["label"] = "Originally created for ClockworkPi Gameshell."
        portinfo["value"] = ""
        self._AList["portinfo1"] = portinfo

    def PortInfo2(self):
        portinfo = {}
        portinfo["key"] = "portinfo2"
        portinfo["label"] = "Ported to Pocket CHIP by omgmog."
        portinfo["value"] = ""
        self._AList["portinfo2"] = portinfo


    def ThanksTimTam(self):
        thanks = {}
        thanks["key"] = "thankstimtam"
        thanks["label"] = "PocketCHIP Graphic created by TimTam"
        thanks["value"] = ""
        self._AList["thankstimtam"] = thanks


        

    def GenList(self):
        
        self._MyList = []
        
        start_x  = 0
        start_y  = 10
        last_height = 0

        for i,u in enumerate( ["cpuscalemhz","memory","uname", "batteryinfo", "portinfo1","portinfo2","thankstimtam"] ):
            if u not in self._AList:
                continue
            
            v = self._AList[u]
            
            li = InfoPageListItem()
            li._Parent = self
            li._PosX   = start_x
            li._PosY   = start_y + last_height
            li._Width  = Width
            li._Fonts["normal"] = self._ListFontObj
            li._Fonts["small"] = MySkinManager.GiveFont("varela12")
            
            if self._AList[u]["label"] != "":
                li.Init(  self._AList[u]["label"] )
            else:
                # li.Init( self._AList[u]["key"] )
                li.Init("")

            li._Flag = self._AList[u]["key"]

            if self._AList[u]["value"] != "":
                li.SetSmallText( self._AList[u]["value"] )
            else:
                li.SetSmallText("")
            
            last_height += li._Height
            
            self._MyList.append(li)
            
    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface( (self._Screen._Width,self._BGheight) )

        self._PosX = self._Index*self._Screen._Width 
        self._Width = self._Screen._Width ## equal to screen width
        self._Height = self._Screen._Height

        bgpng = IconItem()
        bgpng._ImgSurf = MyIconPool._Icons["about_bg"]
        bgpng._MyType = ICON_TYPES["STAT"]
        bgpng._Parent = self
        bgpng.Adjust(0,0,self._BGwidth,self._BGheight,0)

        self._Icons["bg"] = bgpng
        
        self.CpuInfo()
        self.MemInfo()
        self.CpuMhz()
        self.Uname()
        self.BatteryInfo()
        self.PortInfo1()
        self.PortInfo2()
        self.ThanksTimTam()
        
        self.GenList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
        self._Scroller.SetCanvasHWND(self._HWND)
        
    def ScrollDown(self):
        dis = 10
        if abs(self._Scrolled) <  (self._BGheight - self._Height)/2 + 50:
            self._PosY -= dis
            self._Scrolled -= dis
        
    def ScrollUp(self):
        dis = 10
        if self._PosY < 0:
            self._PosY += dis
            self._Scrolled += dis

        
    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False

    def OnReturnBackCb(self):
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        
    def KeyDown(self,event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        # We don't need this page to be scrolly   

        # if event.key == CurKeys["Up"]:
        #     self.ScrollUp()
        #     self._Screen.Draw()
        #     self._Screen.SwapAndShow()
        # if event.key == CurKeys["Down"]:
        #     self.ScrollDown()
        #     self._Screen.Draw()
        #     self._Screen.SwapAndShow()
        
                                
    def Draw(self):

        if self._DrawOnce == False:
            self.ClearCanvas()
            #self._Ps.Draw()
        
            self._Icons["bg"].NewCoord(self._Width/2,self._Height/2 + (self._BGheight - Height)/2 + self._Screen._TitleBar._Height)
            self._Icons["bg"].Draw()

            for i in self._MyList:
                i.Draw()
                
            self._DrawOnce = True
            
        if self._HWND != None:
            # self._HWND.fill((255,255,255))
            
            self._HWND.blit(self._CanvasHWND,(self._PosX,self._PosY,self._Width, self._Height ) )
Пример #8
0
class ListPage(Page):

    _Icons = {}
    _Selector=None
    
    _FootMsg = ["Nav","","","Back","Enter"]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela15")

    _Scroller = None
    
    def __init__(self):
        Page.__init__(self)
        self._Icons = {}
        self._CanvasHWND = None
        self._MyList = []
        
    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = InfoPageSelector()
        ps._Parent = self
        ps._PosX = 2
        self._Ps = ps
        self._PsIndex = 0
        
        #                ""   pkgname, label
        alist         = [["","Airplane","Airplane Mode"],
                         ["","PowerOptions","Power Options"],
                         ["","Wifi","Wi-Fi"],
                         ["","Bluetooth","Bluetooth"],
                         ["","Sound","Sound Volume"],
                         ["","Brightness","BackLight Brightness"],
                         ["","Storage",""],
                         ["","Time","Timezone"],
                         ["","Languages","Languages"],
                         ["","Notification","Notification"],
                         ["","Update", ""],
                         ["","About",  "About"],
                         ["","PowerOFF","Power OFF"],
                         ["","ButtonsLayout","Buttons Layout"],
                         ["","LauncherGo","Switch to LauncherGo"],
                         ["","Lima","GPU driver switch"],
                         ["","GateWay","Network gateway switch"]]

        start_x  = 0
        start_y  = 0

        
        sys.path.append(myvars.basepath)# add self as import path
        for i,v in enumerate(alist):
            li = ListItem()
            li._Parent = self
            li._PosX   = start_x
            li._PosY   = start_y + i*ListItem._Height
            li._Width  = Width
            li._Fonts["normal"] = self._ListFontObj

            if v[2] != "":
                li.Init(v[2])
            else:
                li.Init(v[1])
            
            #if v[1] == "Wifi" or v[1] == "Sound" or v[1] == "Brightness" or v[1] == "Storage" or v[1] == "Update" or v[1] == "About" or v[1] == "PowerOFF" or v[1] == "HelloWorld":
            if FileExists(myvars.basepath+"/"+ v[1]):
                li._LinkObj = __import__(v[1])
                init_cb   = getattr(li._LinkObj,"Init",None)
                if init_cb != None:
                    if callable(init_cb):
                        li._LinkObj.Init(self._Screen)
                
                self._MyList.append(li)

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()

    def Click(self):
        cur_li = self._MyList[self._PsIndex]
        if cur_li._LinkObj != None:
            api_cb = getattr(cur_li._LinkObj,"API",None)
            if api_cb != None:
                if callable(api_cb):
                    cur_li._LinkObj.API(self._Screen)

        
    def KeyDown(self,event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        
        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        

        if IsKeyStartOrA(event.key):
            self.Click()
            
    def Draw(self):
        self.ClearCanvas()

        if len(self._MyList) * ListItem._Height > self._Height:
            self._Ps._Width = self._Width - 11
            
            self._Ps.Draw()
            
            for i in self._MyList:
                i.Draw()
        
            self._Scroller.UpdateSize( len(self._MyList)*ListItem._Height, self._PsIndex*ListItem._Height)
            self._Scroller.Draw()
        else:
            self._Ps._Width = self._Width
            self._Ps.Draw()
            for i in self._MyList:
                i.Draw()
Пример #9
0
class DevilutionPage(Page):
    _FootMsg = ["Nav", "Check", "Upgrade", "Back", "Play"]

    _GameName = "devilutionX"
    _GamePath = "/home/cpi/games/devilutionX"
    _GameExecutable = _GamePath + "/bin/devilutionx"
    _GameExecutableRevision = _GameExecutable + ".rev"
    _GameBuildScript = _GamePath + "/Packaging/cpi-gamesh/build.sh -t " + pipes.quote(
        os.path.dirname(os.path.abspath(__file__)))
    _GamePNG = _GamePath + "/Packaging/cpi-gamesh/Devilution.png"
    _DevilutionDiabdatmpq = "/home/cpi/.local/share/diasurgical/devilution/diabdat.mpq"
    _DevilutionDiabdatmpqPresent = False
    _GameInstalled = False

    _CiteNewUpdate = "Ahh... fresh meat!"
    _CiteCheckUpdate = "Lets search the books..."
    _CiteWelcome = "Well, what can I do for ya?"
    _CiteCompiling = "Stay awhile and listen."
    _CiteDone = "You must venture through the portal..."
    _CiteFailed = "Game Over. Better luck next time!"

    _GitURL = "https://github.com/diasurgical/devilutionX.git"
    _GitBranch = "master"
    _GitRevision = ""

    _GameIcon = None

    _Process = None
    _Labels = {}
    _Coords = {}

    _ListFontObj = MyLangManager.TrFont("varela13")
    _URLColor = MySkinManager.GiveColor('URL')
    _TextColor = MySkinManager.GiveColor('Text')

    def __init__(self):
        Page.__init__(self)

    def InitLabels(self):

        y = 15
        x = 11
        yInc = 19
        xGitRefLabelWidth = 48

        labels = \
         [["greeting",self._CiteWelcome, self._TextColor, x, y],
          ["status", "", self._URLColor, x, y + 72-yInc],
          ["comment", "", self._TextColor, x, y + 72],
          ["console_out","",self._URLColor, x, y + 72 + yInc],
          ["label_rev","GIT Revisions: ", self._TextColor, x, 132],
          ["label_git_rev","Source: ", self._TextColor, x, 151],
          ["content_git_rev","", self._URLColor, x + xGitRefLabelWidth, 151],
          ["label_bin_rev","Bin: ", self._TextColor, x, 170],
          ["content_bin_rev","", self._URLColor, x + xGitRefLabelWidth, 170]
         ]

        for i in labels:
            l = Label()
            l.SetCanvasHWND(self._CanvasHWND)
            l.Init(i[1], self._ListFontObj)
            l.SetColor(i[2])
            self._Labels[i[0]] = l

            c = SimpleNamespace()
            c.x = i[3]
            c.y = i[4]
            self._Coords[i[0]] = c

    def GitGetRevision(self):
        if not os.path.exists(self._GamePath):
            return "game not installed"
        process = subprocess.Popen("cd " + pipes.quote(self._GamePath) +
                                   "; git rev-parse HEAD",
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.STDOUT,
                                   shell=True)
        self._GitRevision = process.communicate()[0].strip()
        process.wait()
        return self._GitRevision

    def ExectuableGetRevision(self):
        try:
            with open(self._GameExecutableRevision, 'r') as file:
                executableRevsion = file.read().replace('\n', '')
            return executableRevsion
        except:
            return "unknown"

    def InitGameDirectory(self):
        try:
            os.makedirs(self._GamePath)
        except:
            pass
        self.StartShellProcess("cd " + pipes.quote(self._GamePath) +
                               "; git clone --single-branch --branch " +
                               pipes.quote(self._GitBranch) + " " +
                               pipes.quote(self._GitURL) + " .")

    def CheckDevilutionMPQ(self):
        self._DevilutionDiabdatmpqPresent = os.path.isfile(
            self._DevilutionDiabdatmpq)

    def CheckGameInstalled(self):
        self._GameInstalled = os.path.isfile(self._GameExecutable)

    def UpdateFootMsg(self):
        if not self._GameInstalled:
            self._FootMsg = ["Nav", "", "Install", "Back", ""]
            self.UpdateLabel("status", "GIT Upgrade")
            self.UpdateLabel("comment", "Press X to install")
        elif not self._DevilutionDiabdatmpqPresent:
            self._FootMsg = ["Nav", "", "Upgrade", "Back", "Re-check"]
            self.UpdateLabel("status", "Gamefile diabdat.mpq missing")
            self.UpdateLabel("comment", "see readme")
        else:
            self._FootMsg = ["Nav", "", "Upgrade", "Back", "Play"]
            self.UpdateLabel("status", "Ready")
            self.UpdateLabel("comment", self._CiteDone)

    def Init(self):
        Page.Init(self)

        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface(
                    (self._Screen._Width, self._Screen._Height))

        if os.path.isfile(self._GamePNG):
            self._GameIcon = IconItem()
            self._GameIcon._ImageName = self._GamePNG
            self._GameIcon._MyType = ICON_TYPES["STAT"]
            self._GameIcon._Parent = self
            self._GameIcon.Adjust(290, 70, 128, 128, 0)

        self.InitLabels()
        self.CheckDevilutionMPQ()
        self.CheckGameInstalled()
        self.UpdateFootMsg()

        self.UpdateLabel("content_git_rev", self.GitGetRevision(), 24)
        self.UpdateLabel("content_bin_rev", self.ExectuableGetRevision(), 24)

    def UpdateLabel(self, label, msg, maxLen=38):
        print(label + ": " + msg)
        if len(msg) > maxLen:
            m = msg[:maxLen] + "..."
        else:
            m = msg
        self._Labels[label].SetText(m)

    def StartShellProcess(self, cmd):
        print("StartShellProcess " + cmd)
        proc = subprocess.Popen(cmd,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT,
                                shell=True)
        while (True):
            line = proc.stdout.readline()
            if line:
                self.UpdateLabel("console_out", line.strip(), 48)
                self._Screen.Draw()
                self._Screen.SwapAndShow()
            if line == '' and proc.poll() is not None:
                break
        self.UpdateLabel("console_out", "")
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def GitUpgrade(self):
        self.UpdateLabel("status", "GIT Upgrade")
        self.UpdateLabel("comment", self._CiteCheckUpdate)

        curRev = "unset"
        if not os.path.exists(self._GamePath):
            self.InitGameDirectory()
        else:
            curRev = self.GitGetRevision()
            self.StartShellProcess("cd " + pipes.quote(self._GamePath) +
                                   "; git pull")

        self._GitRevision = self.GitGetRevision()
        self.UpdateLabel("content_git_rev", self._GitRevision, 24)

        if curRev != self._GitRevision:
            self.UpdateLabel("comment", self._CiteNewUpdate)
        else:
            self.UpdateLabel("comment", self._CiteDone)

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def GitExectuableIsGitRevision(self):
        return self.GitGetRevision() == self.ExectuableGetRevision()

    def Build(self):
        self.UpdateLabel("status", "Building")
        self.StartShellProcess(self._GameBuildScript)

    def UpgradeAndBuild(self):
        self.GitUpgrade()
        self.UpdateLabel("comment", self._CiteCompiling)
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        if not self.GitExectuableIsGitRevision():
            self.Build()

        self.UpdateLabel("content_git_rev", self.GitGetRevision(), 24)
        self.UpdateLabel("content_bin_rev", self.ExectuableGetRevision(), 24)

        self.UpdateLabel("status", "Done")
        if self.GitExectuableIsGitRevision():
            self.UpdateLabel("comment", self._CiteDone)
        else:
            self.UpdateLabel("comment", self._CiteFailed)

        self.CheckDevilutionMPQ()
        self.CheckGameInstalled()
        self.UpdateFootMsg()

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def KeyDown(self, event):

        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if self._DevilutionDiabdatmpqPresent and self._GameInstalled:
            if IsKeyStartOrA(event.key):
                pygame.event.post(
                    pygame.event.Event(RUNSYS, message=self._GameExecutable))
            if event.key == CurKeys["X"]:
                self.UpgradeAndBuild()
        elif not self._GameInstalled:
            if event.key == CurKeys["X"]:
                self.UpgradeAndBuild()
        elif not self._DevilutionDiabdatmpqPresent:
            if IsKeyStartOrA(event.key):
                self.CheckDevilutionMPQ()
                self.CheckGameInstalled()
                self.UpdateFootMsg()
                self._Screen.Draw()
                self._Screen.SwapAndShow()

    def Draw(self):
        self.ClearCanvas()

        if self._GameIcon != None:
            self._GameIcon.Draw()

        for i in self._Labels:
            if i in self._Coords:
                self._Labels[i].NewCoord(self._Coords[i].x, self._Coords[i].y)
                self._Labels[i].Draw()

        if self._HWND != None:
            self._HWND.fill(MySkinManager.GiveColor('White'))
            self._HWND.blit(
                self._CanvasHWND,
                (self._PosX, self._PosY, self._Width, self._Height))
Пример #10
0
    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        self._BGpng = IconItem()
        self._BGpng._ImgSurf = MyIconPool.GiveIconSurface(self._BG)
        self._BGpng._MyType = ICON_TYPES["STAT"]
        self._BGpng._Parent = self
        #print( MyIconPool.Width(self._BG),MyIconPool.Height(self._BG) )
        self._BGpng.Adjust(0, 0, MyIconPool.Width(self._BG),
                           MyIconPool.Height(self._BG), 0)

        self._Board = Textbulletinboard()

        self._Board._PosX = 4
        self._Board._PosY = 100
        self._Board._Width = self._Width - 4 * 2
        self._Board._Height = 200
        self._Board._CanvasHWND = self._CanvasHWND
        self._Board._Align = "Center"
        self._Board._RowPitch = 28
        self._Board.Init()

        if self._Leader != None and self._Leader._ComPkgInfo != None:
            if "NotFoundMsg" in self._Leader._ComPkgInfo:
                d = []
                for i, v in enumerate(self._Leader._ComPkgInfo["NotFoundMsg"]):
                    Color = None
                    Font = None
                    Bold = False
                    Und = False
                    Txt = ""
                    parts = v.split("|")
                    if len(parts) > 0:
                        Txt = parts[0]

                    if len(parts) == 2:
                        if parts[1] != "None":
                            Color = MySkinManager.GiveColor(parts[1])
                    elif len(parts) == 3:
                        if parts[1] != "None":
                            Color = MySkinManager.GiveColor(parts[1])
                        if parts[2] != "None":
                            Font = MyLangManager.TrFont(parts[2])
                    elif len(parts) == 4:
                        if parts[1] != "None":
                            Color = MySkinManager.GiveColor(parts[1])
                        if parts[2] != "None":
                            Font = MyLangManager.TrFont(parts[2])
                        if parts[3] == "True":
                            Bold = True
                    elif len(parts) == 5:
                        if parts[1] != "None":
                            Color = MySkinManager.GiveColor(parts[1])
                        if parts[2] != "None":
                            Font = MyLangManager.TrFont(parts[2])
                        if parts[3] == "True":
                            Bold = True
                        if parts[4] == "True":
                            Und = True

                    a = Text(Txt, Color, Font, Bold, Und)
                    d = d + a.Words()

                self._Board.SetAndBlitText(d)
Пример #11
0
class LanguagesPage(Page):
    _FootMsg = ["Nav", "", "", "Back", "Select"]
    _MyList = []
    _ListFont = MyLangManager.TrFont("notosanscjk15")

    _AList = {}

    _Scrolled = 0

    _BGwidth = 320
    _BGheight = 240 - 24 - 20

    _DrawOnce = False
    _Scroller = None
    _InfoPage = None

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

    def GenList(self):

        self._MyList = []

        start_x = 0
        start_y = 0
        last_height = 0

        files_path = [
            os.path.basename(x) for x in sorted(glob.glob('langs/*.ini'))
        ]

        for i, u in enumerate(files_path):
            #print(i,u)
            li = PageListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + last_height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._Active = False
            li._Value = u.decode("utf8")
            lang_name = u.split("_")[1]
            lang_name = lang_name.split(".")[0]

            li.Init(lang_name.decode("utf8"))

            last_height += li._Height

            self._MyList.append(li)

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface(
                    (self._Screen._Width, self._BGheight))

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        done = IconItem()
        done._ImgSurf = MyIconPool.GiveIconSurface("done")
        done._MyType = ICON_TYPES["STAT"]
        done._Parent = self
        self._Icons["done"] = done

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.GenList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
        self._Scroller.SetCanvasHWND(self._HWND)

    # def ScrollDown(self):
    # if len(self._MyList) == 0:
    # return
    # self._PsIndex +=1
    # if self._PsIndex >= len(self._MyList):
    # self._PsIndex = len(self._MyList) -1

    # cur_li = self._MyList[self._PsIndex]
    # if cur_li._PosY +cur_li._Height > self._Height:
    # for i in range(0,len(self._MyList)):
    # self._MyList[i]._PosY -= self._MyList[i]._Height

    # def ScrollUp(self):
    # if len(self._MyList) == 0:
    # return
    # self._PsIndex -= 1
    # if self._PsIndex < 0:
    # self._PsIndex = 0
    # cur_li = self._MyList[self._PsIndex]
    # if cur_li._PosY < 0:
    # for i in range(0, len(self._MyList)):
    # self._MyList[i]._PosY += self._MyList[i]._Height

    def Click(self):
        if len(self._MyList) == 0:
            return

        cur_li = self._MyList[self._PsIndex]
        if cur_li._Active == True:
            return

        for i in self._MyList:
            i._Active = False

        cur_li._Active = True
        print(cur_li._Value)
        with open(".lang", "w") as f:
            f.write(cur_li._Value)

        self._Screen._MsgBox.SetText("Applying")
        self._Screen._MsgBox.Draw()
        self._Screen.SwapAndShow()

        MyLangManager.UpdateLang()

        pygame.event.post(pygame.event.Event(RESTARTUI,
                                             message=""))  ##Restart Launcher

        pygame.time.delay(1000)

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False
        with open(".lang", "r") as f:
            thelang = f.read()

        thelang = thelang.strip()

        if thelang == "":
            # thelang = "English"
            thelang = "DEOT"

        for i in self._MyList:
            if thelang in i._Value:
                i._Active = True

    def OnReturnBackCb(self):
        pass
        """
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        """

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            self.Click()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def Draw(self):

        self.ClearCanvas()
        if len(self._MyList) == 0:
            return

        else:
            if len(self._MyList) * PageListItem._Height > self._Height:
                self._Ps._Width = self._Width - 11
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()
                self._Scroller.UpdateSize(
                    len(self._MyList) * PageListItem._Height,
                    self._PsIndex * PageListItem._Height)
                self._Scroller.Draw()

            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()

        if self._HWND != None:
            self._HWND.fill(MySkinManager.GiveColor("White"))

            self._HWND.blit(
                self._CanvasHWND,
                (self._PosX, self._PosY, self._Width, self._Height))
Пример #12
0
class NotificationPage(Page):
    _FootMsg = ["Nav", "", "", "Back", "Toggle"]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela13")

    _AList = {}

    _Scrolled = 0

    _BGwidth = 320
    _BGheight = 240 - 24 - 20

    _DrawOnce = False
    _Scroller = None

    _EasingDur = 30

    _GSNOTIFY_JOBS = "gsnotify/Jobs"
    _GSNOTIFY_SOCKET = "/tmp/gsnotify.sock"
    _Config = None
    _AllowedExts = [".sh", ".lsp", ".lua", ".bin", ".py", ".js"]

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

        if "arm" in platform.machine():
            os.system("git config --global core.filemode false")

    def GenList(self):

        self._MyList = []
        ## map ini to self._AList
        files_path = glob.glob(self._GSNOTIFY_JOBS + "/*")

        start_x = 10
        start_y = 0
        counter = 0
        for i, v in enumerate(files_path):
            filename, file_extension = os.path.splitext(v)
            alias_file = filename + ".alias"

            if file_extension in self._AllowedExts:
                li = NotifyJobListItem()
                li._Parent = self
                li._PosX = start_x
                li._PosY = start_y + counter * InfoPageListItem._Height
                li._Width = Width - 10
                li._Fonts["normal"] = self._ListFontObj
                li._Fonts["small"] = fonts["varela12"]

                if IsExecutable(v):
                    li._ReadOnly = True

                if os.path.isfile(alias_file):
                    fp = open(alias_file, "r")
                    alias = fp.read()
                    alias = alias.strip()
                    label_text = alias.decode("utf8")
                    li.Init(label_text)
                    fp.close()
                else:
                    li.Init(os.path.basename(v))
                li._Flag = v
                ##li.SetSmallText( v )

                self._MyList.append(li)
                counter += 1

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._CanvasHWND = self._Screen._CanvasHWND

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        ps = InfoPageSelector()
        ps._PosX = 11
        ps._Parent = self
        ps._Width = self._Width - 10
        self._Ps = ps
        self._PsIndex = 0

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = 2
        self._Scroller._PosY = 2
        self._Scroller.Init()

    def Click(self):
        if len(self._MyList) == 0:
            return

        cur_li = self._MyList[self._PsIndex]
        #print("Click ",cur_li._Flag)
        if IsExecutable(cur_li._Flag):
            os.system("chmod -x " + cur_li._Flag)
        else:
            os.system("chmod +x " + cur_li._Flag)

        self.GenList()

    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False
        self.GenList()

    def OnReturnBackCb(self):
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def KeyDown(self, event):
        if event.key == CurKeys["A"] or event.key == CurKeys["Menu"]:
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["B"]:

            self._Screen._MsgBox.SetText("Applying")
            self._Screen._MsgBox.Draw()
            self._Screen.SwapAndShow()

            pygame.time.delay(638)

            self.Click()

            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def Draw(self):
        self.ClearCanvas()
        self._Ps.Draw()

        if len(self._MyList) > 0:
            for i in self._MyList:
                i.Draw()

            self._Scroller.UpdateSize(
                len(self._MyList) * InfoPageListItem._Height,
                self._PsIndex * InfoPageListItem._Height)
            self._Scroller.Draw()
Пример #13
0
class TinyCloudPage(Page):
    _FootMsg =  ["Nav","","","Back",""]
    _MyList = []
    
    _ListFontObj = MyLangManager.TrFont("varela13")
    
    _AList = {}
    _Labels = {}

    _Coords = {}
    
    _URLColor  = MySkinManager.GiveColor('URL')
    _TextColor = MySkinManager.GiveColor('Text')
    _Scrolled = 0
    
    _PngSize = {}
    
    _DrawOnce = False
    _Scroller = None
    _Scrolled = 0
    
    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False

    def SetCoords(self):

        self._Coords["forID"] = SimpleNamespace()
        self._Coords["forID"].x = 15
        self._Coords["forID"].y = 11

        self._Coords["forKey"] = SimpleNamespace()
        self._Coords["forKey"].x = 71
        self._Coords["forKey"].y = self._Coords["forID"].y

        self._Coords["key_and_pass"] = SimpleNamespace()
        self._Coords["key_and_pass"].x = 36 # 141
        self._Coords["key_and_pass"].y = self._Coords["forID"].y

        self._Coords["forssh"] = SimpleNamespace()
        self._Coords["forssh"].x = self._Coords["forID"].x
        self._Coords["forssh"].y = 36

        self._Coords["ssh_addr"] = SimpleNamespace()
        self._Coords["ssh_addr"].x = self._Coords["forID"].x
        self._Coords["ssh_addr"].y = 54

        self._Coords["forwin"] = SimpleNamespace()
        self._Coords["forwin"].x = self._Coords["forID"].x
        self._Coords["forwin"].y = 80

        self._Coords["samba_games"] = SimpleNamespace()
        self._Coords["samba_games"].x = self._Coords["forID"].x
        self._Coords["samba_games"].y = 97

        self._Coords["samba_music"] = SimpleNamespace()
        self._Coords["samba_music"].x = self._Coords["samba_games"].x
        self._Coords["samba_music"].y = 115

        self._Coords["for_airplay"] = SimpleNamespace()
        self._Coords["for_airplay"].x = self._Coords["forID"].x
        self._Coords["for_airplay"].y = 140

        self._Coords["airplay_name"] = SimpleNamespace()
        self._Coords["airplay_name"].x = 68
        self._Coords["airplay_name"].y = self._Coords["for_airplay"].y
        
        self._Coords["for-usb-eth"] = SimpleNamespace()
        self._Coords["for-usb-eth"].x = self._Coords["forID"].x
        self._Coords["for-usb-eth"].y = 163
        
        self._Coords["usb-eth-addr"] = SimpleNamespace()
        self._Coords["usb-eth-addr"].x = 112
        self._Coords["usb-eth-addr"].y = self._Coords["for-usb-eth"].y

        self._Coords["bg"]          = SimpleNamespace()
        self._Coords["bg"].x        = self._Width/2
        self._Coords["bg"].y        = self._Height/2

        self._Coords["online"]          = SimpleNamespace()
        self._Coords["online"].x        = 266
        self._Coords["online"].y        = 99

    def SetLabels(self):
        if is_wifi_connected_now():
            self._IP = get_wifi_ip()
            print("TinyCould : %s" % self._IP)
            try:
                if validators.ip_address.ipv4(self._IP) == False:
                    self._IP = "xxx.xxx.xxx.xxx"
            except:
                print("ip error %s " % self._IP)
                self._IP = "xxx.xxx.xxx.xxx"
            
        else:
            self._IP = "xxx.xxx.xxx.xxx"
        
        labels = \
        [["forssh","For ssh and scp:",self._ListFontObj,self._TextColor],
         ["ssh_addr","ssh cpi@%s" % self._IP, self._ListFontObj,self._URLColor],
         ["forwin", "For Windows network:",    self._ListFontObj, self._TextColor],
         ["samba_games", "\\\\%s\games" % self._IP, self._ListFontObj,self._URLColor],
         ["samba_music", "\\\\%s\music" % self._IP, self._ListFontObj,self._URLColor],
         ["forID",      "ID:",                     self._ListFontObj, self._TextColor],
         ["forKey",     "Key:",                    self._ListFontObj, self._TextColor],
         ["key_and_pass", "cpi",                   self._ListFontObj, self._URLColor],
         ["for_airplay", "Airplay:",               self._ListFontObj, self._TextColor],
         ["airplay_name","clockworkpi",            self._ListFontObj, self._URLColor],
         ["for-usb-eth","USB-Ethernet:",            self._ListFontObj, self._TextColor],
         ["usb-eth-addr","192.168.10.1",            self._ListFontObj, self._URLColor]]

        for i in labels:
            l = Label()
            l.SetCanvasHWND(self._CanvasHWND)
            l.Init(i[1],i[2])
            l.SetColor(i[3])
            self._Labels[ i[0] ] = l

        self.SetCoords() ##
        
    def Init(self):

        
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface( (self._Screen._Width,self._Screen._Height) )
        
        self._PosX = self._Index*self._Screen._Width 
        self._Width = self._Screen._Width ## equal to screen width
        self._Height = self._Screen._Height

        self._PngSize["bg"] = (253,114)
        self._PngSize["online"] = (75,122)
        
        bgpng = IconItem()
        bgpng._ImgSurf = MyIconPool.GiveIconSurface("needwifi_bg")
        bgpng._MyType = ICON_TYPES["STAT"]
        bgpng._Parent = self
        bgpng.Adjust(0,0,self._PngSize["bg"][0],self._PngSize["bg"][1],0)

        self._Icons["bg"] = bgpng
        
        onlinepng = IconItem()
        onlinepng._ImgSurf = MyIconPool.GiveIconSurface("online")
        onlinepng._MyType = ICON_TYPES["STAT"]
        onlinepng._Parent = self
        onlinepng.Adjust(0,0,self._PngSize["online"][0], self._PngSize["online"][1],0)

        self._Icons["online"] = onlinepng

        self.SetLabels()

    def KeyDown(self,event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        
    def Draw(self):
        if self._DrawOnce == False:
            self.ClearCanvas()

            if is_wifi_connected_now():
                
                self._Icons["online"].NewCoord(self._Coords["online"].x, self._Coords["online"].y)
                self._Icons["online"].Draw()

                self.SetLabels()
                
                for i in self._Labels:
                    if i in self._Coords:
                        self._Labels[i].NewCoord( self._Coords[i].x, self._Coords[i].y)
                        self._Labels[i].Draw()

                self._Labels["key_and_pass"].NewCoord( 103,self._Coords["key_and_pass"].y)
                self._Labels["key_and_pass"].Draw()

            else:
                self._Labels["for-usb-eth"].NewCoord(self._Coords["for-usb-eth"].x+55, self._Coords["for-usb-eth"].y)
                self._Labels["for-usb-eth"].Draw()
                
                self._Labels["usb-eth-addr"].NewCoord(self._Coords["usb-eth-addr"].x+55, self._Coords["usb-eth-addr"].y)
                self._Labels["usb-eth-addr"].Draw()                
                
                self._Icons["bg"].NewCoord(self._Coords["bg"].x, self._Coords["bg"].y)
                self._Icons["bg"].Draw()

                
            self._DrawOnce = True
            
        if self._HWND != None:
            self._HWND.fill(MySkinManager.GiveColor('White'))
            self._HWND.blit(self._CanvasHWND,(self._PosX,self._PosY,self._Width, self._Height ) )
class RomSoConfirmPage(ConfirmPage):
    _ListFont = MyLangManager.TrFont("Eurostile15")

    _ConfirmText = MyLangManager.Tr("SetupGameEngineAutoQ")

    _MyDownloadPage = None

    def CheckBattery(self):
        try:
            f = open(config.Battery)
        except IOError:
            print("RomSoConfirmPage open %s failed" % config.Battery)
            return 6
        else:
            with f:
                bat_uevent = {}
                content = f.readlines()
                content = [x.strip() for x in content]
                for i in content:
                    pis = i.split("=")
                    if len(pis) > 1:
                        bat_uevent[pis[0]] = pis[1]

                if "POWER_SUPPLY_CAPACITY" in bat_uevent:
                    cur_cap = int(bat_uevent["POWER_SUPPLY_CAPACITY"])
                else:
                    cur_cap = 0

                return cur_cap

        return 0

    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        li = MultiLabel()
        li.SetCanvasHWND(self._CanvasHWND)
        li._Width = 160
        li.Init(self._ConfirmText, self._ListFont)

        li._PosX = (self._Width - li._Width) / 2
        li._PosY = (self._Height - li._Height) / 2

        self._BGPosX = li._PosX - 20
        self._BGPosY = li._PosY - 20
        self._BGWidth = li._Width + 40
        self._BGHeight = li._Height + 40

        self._MyList.append(li)

    def SnapMsg(self, msg):
        self._MyList[0].SetText(msg)
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        self._MyList[0].SetText(self._ConfirmText)

    def OnReturnBackCb(self):
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            if self.CheckBattery() < 5:
                self.SnapMsg(MyLangManager.Tr("BATOver5Pct"))
            else:
                if self._MyDownloadPage == None:
                    self._MyDownloadPage = DownloadProcessPage()
                    self._MyDownloadPage._Screen = self._Screen
                    self._MyDownloadPage._Name = "Downloading"
                    self._MyDownloadPage.Init()

                self._Screen.PushPage(self._MyDownloadPage)
                self._Screen.Draw()
                self._Screen.SwapAndShow()

                if config.CurKeySet == "PC":
                    so_url = self._Parent._Emulator[
                        "SO_URL"]  ## [rom/fav]_list_page is _Parent
                    so_url = so_url.replace("armhf", "x86_64")
                    print(so_url)
                    self._MyDownloadPage.StartDownload(
                        so_url,
                        os.path.dirname(self._Parent._Emulator["ROM_SO"]))
                else:
                    self._MyDownloadPage.StartDownload(
                        self._Parent._Emulator["SO_URL"],
                        os.path.dirname(self._Parent._Emulator["ROM_SO"]))

    def Draw(self):
        self.ClearCanvas()
        self.DrawBG()
        for i in self._MyList:
            i.Draw()
Пример #15
0
class CoresPage(Page):
    _FootMsg =  ["Nav","Del","Scan","Back",""]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela13")
    
    _AList = {}

    _Scrolled = 0
    
    _BGwidth = 320
    _BGheight = 240-24-20

    _DrawOnce = False
    _Scroller = None

    _EasingDur = 30
    
    _CORES_PATH = "%s/apps/emulators" % os.path.expanduser('~') 

    _Config =None
    _AllowedExts = [".so",".bin"]
    _HiddenSos   = ["chailove_libretro.so","nxengine_libretro.so"]
    
    def __init__(self):
        Page.__init__(self)
        self._Icons = {}
        
        if "arm" in platform.machine():
            pass
        
    def GenList(self):

        self._MyList = []
        ## map ini to self._AList
        files_path = glob.glob(self._CORES_PATH+"/*")
        
        start_x  = 10
        start_y  = 0
        counter = 0 
        for i,v in enumerate( files_path):
            if os.path.basename(v) in self._HiddenSos:
                continue
            
            filename, file_extension = os.path.splitext(v)

            alias_file = filename+file_extension + ".alias"
            
            if file_extension in self._AllowedExts:
                li = InfoPageListItem()
                li._Parent = self
                li._PosX   = start_x
                li._PosY   = start_y + counter*InfoPageListItem._Height
                li._Width  = Width-10
                li._Fonts["normal"] = self._ListFontObj
                li._Fonts["small"] = MySkinManager.GiveFont("varela12")
                li._ReadOnly = True
                
                if os.path.isfile(alias_file):
                    fp = open(alias_file, "r")
                    alias = fp.read()
                    alias = alias.strip()
                    label_text = alias.decode("utf8")
                    li.Init( label_text )
                    fp.close()
                else:
                    li.Init( os.path.basename(v) )
                li._Flag = v
                ##li.SetSmallText( v )
                
                self._MyList.append(li)
                counter += 1
    
    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._CanvasHWND = self._Screen._CanvasHWND

        self._PosX = self._Index*self._Screen._Width 
        self._Width = self._Screen._Width ## equal to screen width
        self._Height = self._Screen._Height

        ps = InfoPageSelector()
        ps._PosX = 11
        ps._Parent = self
        ps._Width = self._Width-10
        self._Ps = ps
        self._PsIndex = 0

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = 2
        self._Scroller._PosY = 2
        self._Scroller.Init()
        
        self._ConfirmBox = DeleteCoreConfirmPage()
        self._ConfirmBox._Screen = self._Screen
        self._ConfirmBox._Name = "Confirm to Delete?"
        self._ConfirmBox._Parent = self
        self._ConfirmBox.Init()
        
    def ReScan(self):
        self.GenList()
        self.RefreshPsIndex()
      
    def ConfirmBoxCallbackA(self):
        if len(self._MyList) == 0:
            return
            
        cur_li = self._MyList[self._PsIndex]
        
        os.system("rm %s" % CmdClean(cur_li._Flag))
        self.GenList()
        self.RefreshPsIndex()
        
    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False    
        self.GenList()
    
    def OnReturnBackCb(self):
        pass
        
    def KeyDown(self,event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        
        if event.key == CurKeys["X"]: #Scan current
           self.ReScan() 
           self._Screen.Draw()
           self._Screen.SwapAndShow()
                       
        if event.key == CurKeys["Y"]: #del
            if len(self._MyList) == 0:
                return
            
            self._ConfirmBox.CallbackA = self.ConfirmBoxCallbackA
            
            self._Screen.PushPage(self._ConfirmBox)
            self._Screen.Draw()
            self._Screen.SwapAndShow()
            
        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

 

    def Draw(self):
        self.ClearCanvas()

        if len(self._MyList) > 0:
            self._Ps.Draw()
            for i in self._MyList:
                i.Draw()
        
            self._Scroller.UpdateSize( len(self._MyList)*InfoPageListItem._Height,
                                   self._PsIndex*InfoPageListItem._Height) 
            self._Scroller.Draw()
Пример #16
0
class FavListPage(Page):

    _Icons = {}
    _Selector = None
    _FootMsg = ["Nav", "Remove", "Scan", "", "Run"]
    _MyList = []
    _ListFont = MyLangManager.TrFont("notosanscjk15")
    _MyStack = None
    _Emulator = None
    _Parent = None
    _Scroller = None
    _Scrolled = 0
    _BGwidth = 75
    _BGheight = 73
    _RomSoConfirmDownloadPage = None

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}
        self._CanvasHWND = None
        self._MyList = []
        self._MyStack = FavStack()
        self._Emulator = {}

    def GeneratePathList(self, path):
        if os.path.isdir(path) == False:
            return False

        files_path = glob.glob(path + "/*")

        ret = []

        for i, v in enumerate(files_path):
            dirmap = {}
            if os.path.isdir(
                    v) and self._Emulator["FILETYPE"] == "dir":  ## like DOSBOX
                gameshell_bat = self._Emulator["EXT"][0]
                if FileExists(v + "/" + gameshell_bat):
                    stats = os.stat(v)
                    if stats.st_gid != self._Parent._FavGID:  ## only favs
                        continue
                    try:
                        dirmap["gamedir"] = v.decode("utf8", "ignore")
                    except:
                        dirmap["gamedir"] = v.decode("ascii", "ignore")

                    ret.append(dirmap)
            if os.path.isfile(v) and self._Emulator["FILETYPE"] == "file":
                stats = os.stat(v)
                if stats.st_gid != self._Parent._FavGID:  ## only favs
                    continue
                bname = os.path.basename(v)  ### filter extension
                if len(bname) > 1:
                    pieces = bname.split(".")
                    if len(pieces) > 1:
                        if pieces[len(pieces) -
                                  1].lower() in self._Emulator["EXT"]:
                            try:
                                dirmap["file"] = v.decode("utf8", "ignore")
                            except:
                                dirmap["file"] = v.decode("ascii", "ignore")

                            ret.append(dirmap)

#            else:
#                print("not file or dir")

        return ret

    def SyncList(self, path):

        alist = self.GeneratePathList(path)

        if alist == False:
            print("listfiles return false")
            return
#        print("fav list alist: ")
#        print(alist)

        self._MyList = []
        start_x = 0
        start_y = 0
        hasparent = 0
        if self._MyStack.Length() > 0:
            hasparent = 1
            li = ListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._MyType = ICON_TYPES["DIR"]
            li._Parent = self
            li.Init("[..]")
            self._MyList.append(li)

        for i, v in enumerate(sorted(alist)):
            li = ListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + (i + hasparent) * ListItem._Height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._MyType = ICON_TYPES["FILE"]
            li._Parent = self
            if "directory" in v:
                li._MyType = ICON_TYPES["DIR"]
                li.Init(v["directory"])
            elif "file" in v:
                li.Init(v["file"])

            elif "gamedir" in v:
                li.Init(v["gamedir"])
            else:
                li.Init("NoName")

            self._MyList.append(li)

    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList(self._Emulator["ROM"])

        self._MyStack._Emulator = self._Emulator

        icon_for_list = MultiIconItem()
        icon_for_list._ImgSurf = self._Parent._Icons["sys"]
        icon_for_list._MyType = ICON_TYPES["STAT"]
        icon_for_list._Parent = self
        icon_for_list.Adjust(0, 0, 18, 18, 0)

        self._Icons["sys"] = icon_for_list

        bgpng = IconItem()
        bgpng._ImgSurf = MyIconPool._Icons["star"]
        bgpng._MyType = ICON_TYPES["STAT"]
        bgpng._Parent = self
        bgpng.AddLabel(MyLangManager.Tr("MyFavGames"),
                       MyLangManager.TrFont("varela18"))
        bgpng.SetLableColor(MySkinManager.GiveColor('Disabled'))
        bgpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Icons["bg"] = bgpng

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()

        rom_so_confirm_page = RomSoConfirmPage()
        rom_so_confirm_page._Screen = self._Screen
        rom_so_confirm_page._Name = "Download Confirm"
        rom_so_confirm_page._Parent = self
        rom_so_confirm_page.Init()

        self._RomSoConfirmDownloadPage = rom_so_confirm_page

    def ScrollUp(self):
        if len(self._MyList) == 0:
            return

        tmp = self._PsIndex
        self._PsIndex -= self._ScrollStep

        if self._PsIndex < 0:
            self._PsIndex = 0
        dy = tmp - self._PsIndex
        cur_li = self._MyList[self._PsIndex]
        if cur_li._PosY < 0:
            for i in range(0, len(self._MyList)):
                self._MyList[i]._PosY += self._MyList[i]._Height * dy
            self._Scrolled += dy

    def ScrollDown(self):
        if len(self._MyList) == 0:
            return
        tmp = self._PsIndex
        self._PsIndex += self._ScrollStep
        if self._PsIndex >= len(self._MyList):
            self._PsIndex = len(self._MyList) - 1

        dy = self._PsIndex - tmp
        cur_li = self._MyList[self._PsIndex]
        if cur_li._PosY + cur_li._Height > self._Height:
            for i in range(0, len(self._MyList)):
                self._MyList[i]._PosY -= self._MyList[i]._Height * dy
            self._Scrolled -= dy

    def SyncScroll(self):
        ##
        if self._Scrolled == 0:
            return

        if self._PsIndex < len(self._MyList):
            cur_li = self._MyList[self._PsIndex]
            if self._Scrolled > 0:
                if cur_li._PosY < 0:
                    for i in range(0, len(self._MyList)):
                        self._MyList[i]._PosY += self._Scrolled * self._MyList[
                            i]._Height
            elif self._Scrolled < 0:
                if cur_li._PosY + cur_li._Height > self._Height:
                    for i in range(0, len(self._MyList)):
                        self._MyList[i]._PosY += self._Scrolled * self._MyList[
                            i]._Height

    def Click(self):

        if len(self._MyList) == 0:
            return

        if self._PsIndex > len(self._MyList) - 1:
            return

        cur_li = self._MyList[self._PsIndex]

        if cur_li._MyType == ICON_TYPES["DIR"]:
            return

        if cur_li._MyType == ICON_TYPES["FILE"]:
            self._Screen._MsgBox.SetText("Launching")
            self._Screen._MsgBox.Draw()
            self._Screen.SwapAndShow()
            if self._Emulator["FILETYPE"] == "dir":
                path = cur_li._Path + "/" + self._Emulator["EXT"][0]
            else:
                path = cur_li._Path

            print("Run ", path)

            if self._Emulator["FILETYPE"] == "dir":
                escaped_path = CmdClean(path)
            else:
                escaped_path = CmdClean(path)

            custom_config = ""
            if self._Emulator["RETRO_CONFIG"] != "" and len(
                    self._Emulator["RETRO_CONFIG"]) > 5:
                custom_config = " -c " + self._Emulator["RETRO_CONFIG"]

            cmdpath = " ".join(
                (self._Emulator["LAUNCHER"], self._Emulator["ROM_SO"],
                 custom_config, escaped_path))

            if self._Emulator[
                    "ROM_SO"] == "":  #empty means No needs for rom so
                pygame.event.post(pygame.event.Event(RUNEVT, message=cmdpath))
            else:
                if FileExists(self._Emulator["ROM_SO"]):
                    pygame.event.post(
                        pygame.event.Event(RUNEVT, message=cmdpath))
                else:
                    self._Screen.PushPage(self._RomSoConfirmDownloadPage)
                    self._Screen.Draw()
                    self._Screen.SwapAndShow()

            return

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def ReScan(self):
        if self._MyStack.Length() == 0:
            self.SyncList(self._Emulator["ROM"])
        else:
            self.SyncList(self._MyStack.Last())

        idx = self._PsIndex
        if idx > (len(self._MyList) - 1):
            idx = len(self._MyList)
            if idx > 0:
                idx -= 1
            elif idx == 0:  ##nothing in _MyList
                pass

        self._PsIndex = idx  ## sync PsIndex

        self.SyncScroll()

    def OnReturnBackCb(self):
        self.ReScan()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def OnLoadCb(self):
        self.ReScan()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def SpeedScroll(self, thekey):
        if self._Screen._LastKey == thekey:
            self._ScrollStep += 1
            if self._ScrollStep >= 5:
                self._ScrollStep = 5
        else:
            self._ScrollStep = 1

        cur_time = time.time()

        if cur_time - self._Screen._LastKeyDown > 0.3:
            self._ScrollStep = 1

    def KeyDown(self, event):

        if IsKeyMenuOrB(event.key) or event.key == CurKeys["Left"]:
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Up"]:
            self.SpeedScroll(event.key)
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.SpeedScroll(event.key)
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            self.Click()

        if event.key == CurKeys["X"]:  #Scan current
            self.ReScan()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Y"]:  #del
            if len(self._MyList) == 0:
                return

            cur_li = self._MyList[self._PsIndex]
            if cur_li.IsFile():
                """
                #self._Parent.FavDeleteConfirmPage.SetFileName(cur_li._Path)
                #self._Parent.FavDeleteConfirmPage.SetTrashDir(self._Emulator["ROM"])## Fav delete,return to ROM dir,not .Trash
                #self._Screen.PushCurPage()
                #self._Screen.SetCurPage(self._Parent.FavDeleteConfirmPage)
                #self._Screen.Draw()
                #self._Screen.SwapAndShow()
                """

                #delete directly without confirm dialog
                stats = os.stat(cur_li._Path)
                os.chown(
                    cur_li._Path, stats.st_uid,
                    stats.st_uid)  ## normally uid and gid should be the same
                self._Screen._MsgBox.SetText("Deleting")
                self._Screen._MsgBox.Draw()
                self._Screen.SwapAndShow()
                pygame.time.delay(600)
                self.ReScan()
                self._Screen.Draw()
                self._Screen.SwapAndShow()

    def Draw(self):
        self.ClearCanvas()

        if len(self._MyList) == 0:
            self._Icons["bg"].NewCoord(self._Width / 2, self._Height / 2)
            self._Icons["bg"].Draw()
        else:
            if len(self._MyList) * ListItem._Height > self._Height:
                self._Ps._Width = self._Width - 10
                self._Ps.Draw()

                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break

                    if i._PosY < 0:
                        continue

                    i.Draw()

                self._Scroller.UpdateSize(
                    len(self._MyList) * ListItem._Height,
                    self._PsIndex * ListItem._Height)
                self._Scroller.Draw()

            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:
                    i.Draw()
Пример #17
0
class PlayListPage(Page):

    _Icons = {}
    _Selector = None
    _FootMsg = ["Nav", "Remove", "RTA", "Back", "Play/Pause"]
    _MyList = []
    _ListFont = MyLangManager.TrFont("notosanscjk15")

    _Scroller = None
    _CurSongTime = "0:0"

    _BGpng = None
    _BGwidth = 75
    _BGheight = 70

    _Scrolled = 0

    _CurSongName = ""

    def __init__(self):
        self._Icons = {}
        Page.__init__(self)
        self._CanvasHWND = None
        self._MyList = []

    def SyncList(self):
        self._MyList = []
        start_x = 0
        start_y = 0
        if myvars.Poller == None:
            return

        play_list = myvars.Poller.playlist()
        for i, v in enumerate(play_list):
            li = ListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + i * ListItem._Height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont

            if "title" in v:
                if isinstance(v["title"], (list, )):
                    li.Init(" | ".join(v["title"]))
                else:
                    li.Init(v["title"])

                if "file" in v:
                    li._Path = v["file"]

            elif "file" in v:
                li.Init(os.path.basename(v["file"]))
                li._Path = v["file"]
            else:
                li.Init("NoName")

            li._Labels["Text"]._PosX = 7
            self._MyList.append(li)

        self.SyncPlaying()

    def GObjectInterval(self):  ## 250 ms
        self.SyncPlaying()

        if self._Screen.CurPage() == self:
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        return True

    def SyncPlaying(self):
        if myvars.Poller == None:
            return

        current_song = myvars.Poller.poll()

        for i, v in enumerate(self._MyList):
            self._MyList[i]._Playing = False
            self._MyList[i]._PlayingProcess = 0

        if current_song != None:
            if "song" in current_song:
                posid = int(current_song["song"])
                if posid < len(self._MyList):  # out of index
                    self._CurSongName = self._MyList[posid]._Text

                    if "state" in current_song:
                        if current_song["state"] == "stop":
                            self._MyList[posid]._Playing = False
                        else:
                            self._MyList[posid]._Playing = True
                    if "time" in current_song:
                        self._CurSongTime = current_song["time"]
                        times_ = current_song["time"].split(":")
                        if len(times_) > 1:
                            cur = float(times_[0])
                            end = float(times_[1])
                            pros = int((cur / end) * 100.0)
                            self._MyList[posid]._PlayingProcess = pros

    def InPlayList(self, path):
        for i, v in enumerate(self._MyList):
            if v._Path == path:
                return True

    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList()
        gobject.timeout_add(850, self.GObjectInterval)

        self._BGpng = IconItem()
        self._BGpng._ImgSurf = MyIconPool._Icons["heart"]
        self._BGpng._MyType = ICON_TYPES["STAT"]
        self._BGpng._Parent = self
        self._BGpng.AddLabel(MyLangManager.Tr("my favorite music"),
                             MyLangManager.TrFont("varela18"))
        self._BGpng.SetLableColor(MySkinManager.GiveColor('Disabled'))
        self._BGpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()

    def ScrollUp(self):
        if len(self._MyList) == 0:
            return
        self._PsIndex -= 1
        if self._PsIndex < 0:
            self._PsIndex = 0
        cur_li = self._MyList[self._PsIndex]
        if cur_li._PosY < 0:
            for i in range(0, len(self._MyList)):
                self._MyList[i]._PosY += self._MyList[i]._Height
            self._Scrolled += 1

    def ScrollDown(self):
        if len(self._MyList) == 0:
            return
        self._PsIndex += 1
        if self._PsIndex >= len(self._MyList):
            self._PsIndex = len(self._MyList) - 1

        cur_li = self._MyList[self._PsIndex]
        if cur_li._PosY + cur_li._Height > self._Height:
            for i in range(0, len(self._MyList)):
                self._MyList[i]._PosY -= self._MyList[i]._Height
            self._Scrolled -= 1

    def SyncScroll(self):  # show where it left
        if self._Scrolled == 0:
            return

        if self._PsIndex < len(self._MyList):
            cur_li = self._MyList[self._PsIndex]
            if self._Scrolled > 0:
                if cur_li._PosY < 0:
                    for i in range(0, len(self._MyList)):
                        self._MyList[i]._PosY += self._Scrolled * self._MyList[
                            i]._Height
            elif self._Scrolled < 0:
                if cur_li._PosY + cur_li._Height > self._Height:
                    for i in range(0, len(self._MyList)):
                        self._MyList[i]._PosY += self._Scrolled * self._MyList[
                            i]._Height

    def Click(self):
        if len(self._MyList) == 0:
            return

        cur_li = self._MyList[self._PsIndex]
        play_pos_id = myvars.Poller.play(self._PsIndex)

        self.SyncPlaying()

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def OnReturnBackCb(self):  # return from music_lib_list_page
        self.SyncList()
        self.SyncScroll()

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            if myvars.Poller != None:
                myvars.Poller.stop()
                self._CurSongTime = ""
                self._CurSongName = ""

            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Right"]:  #add
            self._Screen.PushCurPage()
            self._Screen.SetCurPage(myvars.MusicLibListPage)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Y"]:  # del selected songs
            myvars.Poller.delete(self._PsIndex)
            self.SyncList()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            self.Click()

        if event.key == CurKeys["X"]:  # start spectrum
            myvars.SpectrumPage._Neighbor = self
            self._Screen.PushPage(myvars.SpectrumPage)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def Draw(self):
        self.ClearCanvas()

        if len(self._MyList) == 0:
            self._BGpng.NewCoord(self._Width / 2, self._Height / 2)
            self._BGpng.Draw()
            return
        else:
            if len(self._MyList) * ListItem._Height > self._Height:
                self._Ps._Width = self._Width - 11
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break

                    if i._PosY < 0:
                        continue

                    i.Draw()
                self._Scroller.UpdateSize(
                    len(self._MyList) * ListItem._Height,
                    self._PsIndex * ListItem._Height)
                self._Scroller.Draw()
            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:

                    if i._PosY > self._Height + self._Height / 2:
                        break

                    if i._PosY < 0:
                        continue

                    i.Draw()
Пример #18
0
class PowerOptionsPage(Page):
    _FootMsg = ["Nav", "Detail", "", "Back", "Select"]
    _MyList = []
    _ListFont = MyLangManager.TrFont("notosanscjk15")

    _AList = {}

    _Scrolled = 0

    _BGwidth = 320
    _BGheight = 240 - 24 - 20

    _DrawOnce = False
    _Scroller = None
    _InfoPage = None

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

    def GenList(self):

        self._MyList = []

        start_x = 0
        start_y = 0
        last_height = 0

        supersaving = {}
        supersaving["key"] = "super"
        supersaving["label"] = "Power saving"
        supersaving["value"] = "supersaving"

        powersaving = {}
        powersaving["key"] = "saving"
        powersaving["label"] = "Balanced"
        powersaving["value"] = "powersaving"

        balance_saving = {}
        balance_saving["key"] = "balance"
        balance_saving["label"] = "Performance"
        balance_saving["value"] = "balance_saving"

        server_saving = {}
        server_saving["key"] = "server"
        server_saving["label"] = "Server"
        server_saving["value"] = "server"

        self._AList["supersaving"] = supersaving
        self._AList["powersaving"] = powersaving
        self._AList["server"] = server_saving
        self._AList["balance_saving"] = balance_saving

        for i, u in enumerate(
            ["supersaving", "powersaving", "server", "balance_saving"]):
            if u not in self._AList:
                continue

            v = self._AList[u]

            li = PageListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + last_height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._Active = False
            li._Value = self._AList[u]["value"]

            if self._AList[u]["label"] != "":
                li.Init(self._AList[u]["label"])
            else:
                li.Init(self._AList[u]["key"])

            last_height += li._Height

            self._MyList.append(li)

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface(
                    (self._Screen._Width, self._BGheight))

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        done = IconItem()
        done._ImgSurf = MyIconPool.GiveIconSurface("done")
        done._MyType = ICON_TYPES["STAT"]
        done._Parent = self
        self._Icons["done"] = done

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.GenList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
        self._Scroller.SetCanvasHWND(self._HWND)

        self._InfoPage = InfoPage()
        self._InfoPage._Screen = self._Screen
        self._InfoPage._Name = "Power option detail"
        self._InfoPage.Init()

    def Click(self):
        if len(self._MyList) == 0:
            return

        cur_li = self._MyList[self._PsIndex]
        if cur_li._Active == True:
            return

        for i in self._MyList:
            i._Active = False

        cur_li._Active = True
        print(cur_li._Value)
        with open(".powerlevel", "w") as f:
            f.write(cur_li._Value)

        config.PowerLevel = cur_li._Value

        if config.PowerLevel != "supersaving":
            os.system("sudo iw wlan0 set power_save off > /dev/null")
        else:
            os.system("sudo iw wlan0 set power_save on > /dev/null")

        self._Screen._MsgBox.SetText("Applying")
        self._Screen._MsgBox.Draw()
        self._Screen.SwapAndShow()

        pygame.event.post(pygame.event.Event(POWEROPT, message=""))

        pygame.time.delay(1000)

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False
        with open(".powerlevel", "r") as f:
            powerlevel = f.read()

        powerlevel = powerlevel.strip()

        if powerlevel == "":
            powerlevel = "balance_saving"

        for i in self._MyList:
            if i._Value == powerlevel:
                i._Active = True

    def OnReturnBackCb(self):
        pass
        """
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        """

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            self.Click()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Y"]:
            cur_li = self._MyList[self._PsIndex]
            time1 = config.PowerLevels[cur_li._Value][0]
            time2 = config.PowerLevels[cur_li._Value][1]
            time3 = config.PowerLevels[cur_li._Value][2]

            self._InfoPage._Time1 = time1
            self._InfoPage._Time2 = time2
            self._InfoPage._Time3 = time3

            self._Screen.PushPage(self._InfoPage)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def Draw(self):

        self.ClearCanvas()
        if len(self._MyList) == 0:
            return

        else:
            if len(self._MyList) * PageListItem._Height > self._Height:
                self._Ps._Width = self._Width - 11
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()
                self._Scroller.UpdateSize(
                    len(self._MyList) * PageListItem._Height,
                    self._PsIndex * PageListItem._Height)
                self._Scroller.Draw()

            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()

        if self._HWND != None:
            self._HWND.fill(MySkinManager.GiveColor("White"))

            self._HWND.blit(
                self._CanvasHWND,
                (self._PosX, self._PosY, self._Width, self._Height))
Пример #19
0
 def Init(self):
     self._FontObj = MyLangManager.TrFont("veramono24")
Пример #20
0
class BluetoothPage(Page):
    _MyList = []
    #Wicd dbus part
    _Adapter = None
    _Dbus = None
    _Devices = None

    _BlePassword = ""
    _Connecting = False
    _Scanning = False

    _PrevState = None
    _Selector = None

    _ShowingMessageBox = False
    _MsgBox = None
    _ConnectTry = 0
    _BlockCb = None

    _LastStatusMsg = ""
    _FootMsg = ["Nav", "Info", "Scan", "Back", "TryConnect"]
    _Scroller = None
    _ListFontObj = MyLangManager.TrFont("notosanscjk15")

    _InfoPage = None

    _ADAPTER_DEV = "hci0"

    _Offline = False

    _Leader = None

    def __init__(self):
        Page.__init__(self)
        self._MyList = []
        self._CanvasHWND = None

    def ShowBox(self, msg):

        self._MsgBox._Text = msg
        self._ShowingMessageBox = True
        self._Screen.Draw()
        self._MsgBox.Draw()
        self._Screen.SwapAndShow()

    def HideBox(self):
        self.Draw()
        self._ShowingMessageBox = False
        self._Screen.SwapAndShow()

    def Init(self):

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        #self._CanvasHWND = pygame.Surface((self._Width,self._Height))
        self._CanvasHWND = self._Screen._CanvasHWND

        ps = BleListSelector()
        ps._Parent = self
        ps._Width = Width - 12

        self._Ps = ps
        self._PsIndex = 0

        msgbox = BleListMessageBox()
        msgbox._CanvasHWND = self._CanvasHWND
        msgbox.Init(" ", MyLangManager.TrFont("veramono15"))
        msgbox._Parent = self

        self._MsgBox = msgbox

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = 2
        self._Scroller._PosY = 2
        self._Scroller.Init()

        self.GenNetworkList()

        self._InfoPage = BleInfoPage()
        self._InfoPage._Screen = self._Screen
        self._InfoPage._Name = "BluetoothInfo"
        self._InfoPage.Init()

    def print_normal(self, address, properties):
        print("[ " + address + " ]")

        for key in properties.keys():
            value = properties[key]
            if type(value) is dbus.String:
                value = unicode(value).encode('ascii', 'replace')
            if (key == "Class"):
                print("    %s = 0x%06x" % (key, value))
            else:
                print("    %s = %s" % (key, value))

        print()

        properties["Logged"] = True

    def skip_dev(self, old_dev, new_dev):
        if not "Logged" in old_dev:
            return False
        if "Name" in old_dev:
            return True
        if not "Name" in new_dev:
            return True
        return False

    def DbusPropertiesChanged(self, interface, changed, invalidated, path):
        global devices
        print("DbusPropertiesChanged")
        if interface != "org.bluez.Device1":
            return

        if path in devices:
            dev = devices[path]

            if self.skip_dev(dev, changed):
                return
            devices[path] = dict(devices[path].items() + changed.items())
        else:
            devices[path] = changed

        if "Address" in devices[path]:
            address = devices[path]["Address"]
        else:
            address = "<unknown>"

        self._Devices = devices
        self.print_normal(address, devices[path])

        self.RefreshDevices()
        self.GenNetworkList()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def ShutDownConnecting(self):
        print("Bluetooth Shutdown connecting...")

    def AbortedAndReturnToUpLevel(self):
        self.HideBox()
        self._Screen._FootBar.ResetNavText()
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def CheckIfBluetoothConnecting(self):
        return True

    def TryConnect(self):
        global bus

        if self._PsIndex >= len(self._MyList):
            return

        cur_li = self._MyList[self._PsIndex]
        print(cur_li._Path)

        if "Connected" in cur_li._Atts:
            if cur_li._Atts["Connected"] == 1:
                return

        proxy_obj = bus.get_object("org.bluez", cur_li._Path)
        dev = dbus.Interface(proxy_obj, "org.bluez.Device1")

        self._Screen._FootBar.UpdateNavText("Connecting")
        self.ShowBox(MyLangManager.Tr("Connecting"))

        self._Leader._MyAgent.device_obj = dev
        self._Leader._MyAgent.dev_path = cur_li._Path

        try:
            dev.Pair(reply_handler=self._Leader._MyAgent.pair_reply,
                     error_handler=self._Leader._MyAgent.pair_error,
                     timeout=60000)
        except Exception, e:
            print(str(e))
Пример #21
0
class InfoPage(Page):
    _FootMsg = ["Nav", "", "", "Back", ""]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela15")
    _AList = {}

    _Time1 = 40
    _Time2 = 120
    _Time3 = 300

    def ConvertSecToMin(self, secs):
        sec_str = ""
        min_str = ""
        if secs > 60:
            m = int(secs / 60)
            s = secs % 60
            if m > 1:
                min_str = ("%d " + MyLangManager.Tr("minutes") + " ") % m
            else:
                min_str = ("%d " + MyLangManager.Tr("minute") + " ") % m

            if s == 1:
                sec_str = ("%d " + MyLangManager.Tr("second")) % s
            elif s > 1:
                sec_str = ("%d " + MyLangManager.Tr("seconds")) % s
        elif secs > 0:
            if secs > 1:
                sec_str = ("%d " + MyLangManager.Tr("seconds")) % secs
            else:
                sec_str = ("%d " + MyLangManager.Tr("second")) % secs

        elif secs == 0:
            sec_str = MyLangManager.Tr("Never")

        return min_str + sec_str

    def RefreshList(self):
        ## after GenList ,reuse
        self._AList["time1"]["value"] = self.ConvertSecToMin(self._Time1)
        self._AList["time2"]["value"] = self.ConvertSecToMin(self._Time2)
        self._AList["time3"]["value"] = self.ConvertSecToMin(self._Time3)

        for i, v in enumerate(self._AList):
            self._MyList[i].SetSmallText(self._AList[v]["value"])

    def GenList(self):

        time1 = {}
        time1["key"] = "time1"
        if self._Time1 == 0:
            time1["value"] = MyLangManager.Tr("Never")
        else:
            time1["value"] = "%d secs" % self._Time1
        time1["label"] = "Screen dimming"

        time2 = {}
        time2["key"] = "time2"
        if self._Time2 == 0:
            time2["value"] = MyLangManager.Tr("Never")
        else:
            time2["value"] = "%d secs" % self._Time2

        time2["label"] = "Screen OFF"

        time3 = {}
        time3["key"] = "time3"

        if self._Time3 == 0:
            time3["value"] = MyLangManager.Tr("Never")
        else:
            time3["value"] = "%d secs" % self._Time3
        time3["label"] = "Power OFF"

        self._AList["time1"] = time1
        self._AList["time2"] = time2
        self._AList["time3"] = time3

        self._MyList = []

        start_x = 0
        start_y = 0

        for i, v in enumerate(self._AList):
            #print(v)
            li = PageListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + i * PageListItem._Height
            li._Width = Width
            li._Fonts["normal"] = self._ListFontObj
            li._Fonts["small"] = MyLangManager.TrFont("varela12")

            if self._AList[v]["label"] != "":
                li.Init(self._AList[v]["label"])
            else:
                li.Init(self._AList[v]["key"])

            li._Flag = self._AList[v]["key"]

            li.SetSmallText(self._AList[v]["value"])

            self._MyList.append(li)

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._CanvasHWND = self._Screen._CanvasHWND

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.GenList()

    def ScrollUp(self):
        if len(self._MyList) == 0:
            return
        self._PsIndex -= 1
        if self._PsIndex < 0:
            self._PsIndex = 0
        cur_li = self._MyList[self._PsIndex]
        if cur_li._PosY < 0:
            for i in range(0, len(self._MyList)):
                self._MyList[i]._PosY += self._MyList[i]._Height

    def ScrollDown(self):
        if len(self._MyList) == 0:
            return
        self._PsIndex += 1
        if self._PsIndex >= len(self._MyList):
            self._PsIndex = len(self._MyList) - 1

        cur_li = self._MyList[self._PsIndex]
        if cur_li._PosY + cur_li._Height > self._Height:
            for i in range(0, len(self._MyList)):
                self._MyList[i]._PosY -= self._MyList[i]._Height

    def Click(self):
        cur_li = self._MyList[self._PsIndex]
        print(cur_li._Flag)

    def OnLoadCb(self):
        self.RefreshList()

    def OnReturnBackCb(self):
        pass
        """
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        """

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def Draw(self):
        self.ClearCanvas()
        self._Ps.Draw()

        for i in self._MyList:
            i.Draw()
Пример #22
0
class LoadHousePage(Page):
    _FootMsg = ["Nav.", "", "", "Back", "Cancel"]
    _Value = 0
    _URL = None
    _ListFontObj = MyLangManager.TrFont("varela18")
    _URLColor = MySkinManager.GiveColor('URL')
    _TextColor = MySkinManager.GiveColor('Text')
    _Caller = None
    _img = None
    _Downloader = None
    _DownloaderTimer = -1

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}
        self._CanvasHWND = None

    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND
        self._LoadingLabel = Label()
        self._LoadingLabel.SetCanvasHWND(self._CanvasHWND)
        self._LoadingLabel.Init("Loading", self._ListFontObj)
        self._LoadingLabel.SetColor(self._TextColor)

    def OnLoadCb(self):
        if self._URL is None:
            return
        self._img = None
        self.ClearCanvas()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

        filename = self._URL.split("/")[-1].strip()
        local_dir = self._URL.split("raw.githubusercontent.com")

        if len(local_dir) > 1:
            menu_file = local_dir[1]
            local_menu_file = "%s/aria2download%s" % (os.path.expanduser('~'),
                                                      menu_file)

            if FileExists(local_menu_file):
                #load json
                with open(local_menu_file) as json_file:
                    try:
                        local_menu_json = json.load(json_file)
                        self._Caller._MyStack.Push(local_menu_json["list"])
                    except:
                        pass

                    self.Leave()

            else:
                self._Downloader = Download(self._URL, "/tmp", None)
                self._Downloader.start()
                self._DownloaderTimer = gobject.timeout_add(
                    400, self.GObjectUpdateProcessInterval)

    def GObjectUpdateProcessInterval(self):
        ret = True
        if self._Screen.CurPage() == self:
            if self._Downloader._stop == True:
                ret = False

            dst_filename = self._Downloader.get_dest()
            if self._Downloader.isFinished():
                if self._Downloader.isSuccessful():
                    filename = self._URL.split("/")[-1].strip()
                    local_dir = self._URL.split("raw.githubusercontent.com")
                    menu_file = local_dir[1]
                    local_menu_file = "%s/aria2download%s" % (
                        os.path.expanduser('~'), menu_file)

                    dl_file = os.path.join("/tmp", filename)
                    if not os.path.exists(os.path.dirname(local_menu_file)):
                        os.makedirs(os.path.dirname(local_menu_file))

                    copyfile(dl_file, local_menu_file)
                    with open(local_menu_file) as json_file:
                        try:
                            local_menu_json = json.load(json_file)
                            self._Caller._MyStack.Push(local_menu_json["list"])
                        except:
                            pass

                    ret = False

                    self.Leave()
                else:
                    self._Screen._MsgBox.SetText("Fetch house failed")
                    self._Screen._MsgBox.Draw()
                    self._Screen.SwapAndShow()
                    ret = False
            return ret
        else:
            return False

    def Leave(self):
        if self._DownloaderTimer != -1:
            gobject.source_remove(self._DownloaderTimer)
        self._DownloaderTimer = -1

        if self._Downloader != None:
            try:
                self._Downloader.stop()
            except:
                print("user canceled ")

        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        self._URL = None

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            self.Leave()

    def Draw(self):
        self.ClearCanvas()
        self._LoadingLabel.NewCoord((Width - self._LoadingLabel._Width) / 2,
                                    (Height - 44) / 2)
        self._LoadingLabel.Draw()

        if self._img is not None:
            self._CanvasHWND.blit(
                self._img,
                midRect(Width / 2, (Height - 44) / 2,
                        pygame.Surface.get_width(self._img),
                        pygame.Surface.get_height(self._img), Width,
                        Height - 44))
Пример #23
0
class AboutPage(Page):
    _FootMsg = ["Nav.", "", "", "Back", ""]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela13")

    _AList = {}

    _Scrolled = 0

    _BGwidth = 320
    _BGheight = 300

    _DrawOnce = False
    _Scroller = None

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

    def Uname(self):

        out = {}
        out["key"] = "uname"
        out["label"] = "Kernel:"
        st = subprocess.check_output(["uname", "-srmo"])
        st = st.strip("\n")
        st = st.strip("\t")
        out["value"] = st
        self._AList["uname"] = out

        return

    def CpuMhz(self):

        try:
            with open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"
                      ) as f:
                content = f.readlines()
            content = [x.strip() for x in content]

        except:
            print("open %s failed" %
                  "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq")
            content = ["0"]

        mhz = int(content[0]) / 1000.0

        cpuscalemhz = {}
        cpuscalemhz["key"] = "cpuscalemhz"
        cpuscalemhz["label"] = "CPU Mhz:"
        cpuscalemhz["value"] = str(mhz)
        self._AList["cpuscalemhz"] = cpuscalemhz

        return

    def CpuInfo(self):
        last_processor = 0
        with open("/proc/cpuinfo") as f:
            for line in f:
                if line.startswith("processor"):
                    parts = line.split(":")
                    cur_processor_number = int(parts[1].strip())
                    if cur_processor_number > last_processor:
                        last_processor = cur_processor_number

                if line.startswith("model name"):
                    parts = line.split(":")
                    #                    print( parts[1].strip() )
                    processor = {}
                    processor["key"] = "processor"
                    processor["label"] = "Processor:"
                    processor["value"] = parts[1].strip()

                    self._AList["processor"] = processor

                if line.startswith("cpu MHz"):
                    parts = line.split(":")
                    #                    print(parts[1].strip() )
                    cpumhz = {}
                    cpumhz["key"] = "cpumhz"
                    cpumhz["label"] = "CPU MHz:"
                    cpumhz["value"] = parts[1].strip()

                    self._AList["cpumhz"] = cpumhz
                if line.startswith("cpu cores"):
                    parts = line.split(":")
                    #                    print(parts[1].strip() )
                    cpucores = {}
                    cpucores["key"] = "cpucores"
                    cpucores["label"] = "CPU cores:"
                    cpucores["value"] = parts[1].strip()
                    self._AList["cpucores"] = cpucores
                if line.startswith("Features"):
                    parts = line.split(":")
                    #                    print(parts[1].strip() )
                    f_ = {}
                    f_["key"] = "features"
                    f_["label"] = "Features:"
                    f_["value"] = parts[1].strip()
                    self._AList["features"] = f_

                if line.startswith("flags"):
                    parts = line.split(":")
                    #                    print(parts[1].strip() )
                    flags = {}
                    flags["key"] = "flags"
                    flags["label"] = "Flags:"
                    flags["value"] = parts[1].strip()
                    self._AList["flags"] = flags

        if last_processor > 0:
            arm_cores = {}
            arm_cores["key"] = "armcores"
            arm_cores["label"] = "CPU cores:"
            arm_cores["value"] = str(last_processor + 1)
            self._AList["armcores"] = arm_cores

    def MemInfo(self):

        with open("/proc/meminfo") as f:
            for line in f:
                if line.startswith("MemTotal"):
                    parts = line.split(":")
                    parts[1] = parts[1].replace("kB", "")
                    print(parts[1].strip())

                    memory = {}
                    memory["key"] = "memory"
                    memory["label"] = "Memory:"
                    memory["value"] = str(
                        int(parts[1].strip()) / 1000.0) + " MB"
                    self._AList["memory"] = memory
                    break

    def LauncherVersion(self):
        launcher_version = {}
        launcher_version["key"] = "launcher_ver"
        launcher_version["label"] = "Launcher:"
        launcher_version["value"] = VERSION
        self._AList["launcher_ver"] = launcher_version

    def OsImageVersion(self):
        if FileExists("/etc/clockworkpi_os_image_version"):
            try:
                with open("/etc/clockworkpi_os_image_version") as f:
                    content = f.readlines()
                content = [x.strip() for x in content]

            except:
                print("open %s failed" % "/etc/clockworkpi_os_image_version")
                content = None

            if content != None and len(content) > 0:
                os_image_ver = {}
                os_image_ver["key"] = "os_image_ver"
                os_image_ver["label"] = "OS Image:"
                os_image_ver["value"] = content[0][:12]
                self._AList["os_image_ver"] = os_image_ver

    def GenList(self):

        self._MyList = []

        start_x = 0
        start_y = 10
        last_height = 0

        for i, u in enumerate([
                "processor", "armcores", "cpuscalemhz", "features", "memory",
                "uname", "launcher_ver", "os_image_ver"
        ]):
            #for i,u in enumerate( ["processor","cpucores","cpumhz","flags","memory","uname"] ):
            if u not in self._AList:
                continue

            v = self._AList[u]

            li = InfoPageListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + last_height
            li._Width = Width
            li._Fonts["normal"] = self._ListFontObj
            li._Fonts["small"] = MySkinManager.GiveFont("varela12")

            if self._AList[u]["label"] != "":
                li.Init(self._AList[u]["label"])
            else:
                li.Init(self._AList[u]["key"])

            li._Flag = self._AList[u]["key"]

            li.SetSmallText(self._AList[u]["value"])

            last_height += li._Height

            self._MyList.append(li)

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface(
                    (self._Screen._Width, self._BGheight + 50))

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        bgpng = MultiIconItem()
        bgpng._ImgSurf = MyIconPool.GiveIconSurface("about_bg")
        bgpng._MyType = ICON_TYPES["STAT"]
        bgpng._Parent = self
        bgpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Icons["bg"] = bgpng

        self.CpuInfo()
        self.MemInfo()
        self.CpuMhz()
        self.Uname()

        self.LauncherVersion()
        self.OsImageVersion()

        self.GenList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
        self._Scroller.SetCanvasHWND(self._HWND)

    def ScrollDown(self):
        dis = 10
        if abs(self._Scrolled) < (self._BGheight - self._Height) / 2 + 100:
            self._PosY -= dis
            self._Scrolled -= dis

    def ScrollUp(self):
        dis = 10
        if self._PosY < 0:
            self._PosY += dis
            self._Scrolled += dis

    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False

    def OnReturnBackCb(self):
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def Draw(self):

        if self._DrawOnce == False:
            self.ClearCanvas()
            #self._Ps.Draw()

            for i in self._MyList:
                i.Draw()

            self._DrawOnce = True

            self._Icons["bg"].DrawRect((230, 0, 82, 184), (228, 0, 82, 184))

            y = self._MyList[len(self._MyList) - 1]._PosY + 30

            self._Icons["bg"].DrawRect(((self._Width - 191) / 2, y, 191, 68),
                                       (65, 232, 191, 68))

        if self._HWND != None:
            self._HWND.fill(MySkinManager.GiveColor("White"))

            self._HWND.blit(
                self._CanvasHWND,
                (self._PosX, self._PosY, self._Width, self._Height))

            self._Scroller.UpdateSize(self._BGheight, abs(self._Scrolled) * 3)
            self._Scroller.Draw()
class TimezoneListPage(Page):

    _Icons = {}
    _Selector = None
    _FootMsg = ["Nav", "", "", "Back", "Select"]
    _MyList = []
    _SwapMyList = []
    _ListFont = MyLangManager.TrFont("notosanscjk15")
    _MyStack = None

    _Scroller = None

    _BGpng = None
    _BGwidth = 56
    _BGheight = 70

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}
        self._CanvasHWND = None
        self._MyList = []
        self._SwapMyList = []
        self._MyStack = TimeLibStack()

    def buildDirectoryList(self, path):
        elements = [{
            'name': f,
            'file_path': os.path.join(path, f),
            'is_file': os.path.isfile(os.path.join(path, f))
        } for f in os.listdir(path)]
        return elements

    def SyncList(self, path):

        alist = self.buildDirectoryList(path)
        if not alist:
            print("buildDirectoryList empty")
            return

        self._MyList = []
        self._SwapMyList = []

        start_x = 0
        start_y = 0
        hasparent = 0
        if self._MyStack.Length() > 0:
            hasparent = 1
            li = ListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._MyType = ICON_TYPES["DIR"]
            li.Init("[..]")
            self._MyList.append(li)

        for i, v in enumerate(sorted(alist)):
            li = ListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + (i + hasparent) * ListItem._Height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._MyType = ICON_TYPES["FILE"]

            if not v['is_file']:
                li._MyType = ICON_TYPES["DIR"]
            else:
                li._MyType = ICON_TYPES["FILE"]

            li.Init(v['name'])
            li._Path = v["file_path"]

            self._MyList.append(li)

        for i in self._MyList:
            self._SwapMyList.append(i)

    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList("/usr/share/zoneinfo/posix")

        icon_for_list = MultiIconItem()
        icon_for_list._ImgSurf = MyIconPool.GiveIconSurface("sys")
        icon_for_list._MyType = ICON_TYPES["STAT"]
        icon_for_list._Parent = self

        icon_for_list.Adjust(0, 0, 18, 18, 0)
        self._Icons["sys"] = icon_for_list

        self._BGpng = IconItem()
        self._BGpng._ImgSurf = MyIconPool.GiveIconSurface("empty")
        self._BGpng._MyType = ICON_TYPES["STAT"]
        self._BGpng._Parent = self
        self._BGpng.AddLabel("No timezones found on system!",
                             MyLangManager.TrFont("varela22"))
        self._BGpng.SetLableColor(MySkinManager.GiveColor('Disabled'))
        self._BGpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()

    def Click(self):
        if len(self._MyList) == 0:
            return

        cur_li = self._MyList[self._PsIndex]

        if cur_li._MyType == ICON_TYPES["DIR"]:
            if cur_li._Path == "[..]":
                self._MyStack.Pop()
                self.SyncList(self._MyStack.Last())
                self._PsIndex = 0
            else:
                self._MyStack.Push(self._MyList[self._PsIndex]._Path)
                self.SyncList(self._MyStack.Last())
                self._PsIndex = 0

        if cur_li._MyType == ICON_TYPES["FILE"]:  ## set the current timezone
            subprocess.call(['sudo', 'cp', cur_li._Path, '/etc/localtime'])
            #copyfile(cur_li._Path, '/etc/localtime')
            print("add", cur_li._Path)

        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def Rescan(self):
        self.SyncList("/usr/share/zoneinfo/posix")
        self._PsIndex = 0

    def KeyDown(self, event):

        if IsKeyMenuOrB(event.key):

            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Right"]:
            self.FScrollDown(Step=5)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if event.key == CurKeys["Left"]:
            self.FScrollUp(Step=5)
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            self.Click()

    def Draw(self):
        self.ClearCanvas()

        if len(self._MyList) == 0:
            self._BGpng.NewCoord(self._Width / 2, self._Height / 2)
            self._BGpng.Draw()
            return

        else:
            if len(self._MyList) * ListItem._Height > self._Height:
                self._Ps._Width = self._Width - 11

                self._Ps.Draw()
                for i in self._MyList:
                    if False:
                        i._Active = True
                    else:
                        i._Active = False

                    if i._PosY > self._Height + self._Height / 2:
                        break

                    if i._PosY < 0:
                        continue

                    i.Draw()

                self._Scroller.UpdateSize(
                    len(self._MyList) * ListItem._Height,
                    self._PsIndex * ListItem._Height)
                self._Scroller.Draw()
            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:
                    if False:
                        i._Active = True
                    else:
                        i._Active = False

                    if i._PosY > self._Height + self._Height / 2:
                        break

                    if i._PosY < 0:
                        continue

                    i.Draw()
Пример #25
0
class BleInfoPage(Page):
    _FootMsg = ["Nav", "Forget", "Disconnect", "Back", ""]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela15")
    _ListSmFontObj = MySkinManager.GiveFont("varela12")  # small font
    _ListSm2FontObj = MySkinManager.GiveFont("varela11")

    _AList = {}
    _Path = ""

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._CanvasHWND = self._Screen._CanvasHWND

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        ps = BleInfoPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        #_AList is an object
        self.GenList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = 2
        self._Scroller._PosY = 2
        self._Scroller.Init()

        self._ConfirmPage1 = BleForgetConfirmPage()
        self._ConfirmPage1._Screen = self._Screen
        self._ConfirmPage1._Name = "ConfirmForget"
        self._ConfirmPage1._Parent = self
        self._ConfirmPage1.Init()

    def GenList(self):
        if self._AList == None:
            return
        self._MyList = []
        self._PsIndex = 0
        start_x = 0
        start_y = 0

        for i, v in enumerate(self._AList):
            #print(i,v) # (0, dbus.String(u'AddressType'))

            li = InfoPageListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + i * InfoPageListItem._Height
            li._Width = Width
            li._Fonts["normal"] = self._ListFontObj

            if v == "UUIDs":
                li._Fonts["small"] = self._ListSm2FontObj
            else:
                li._Fonts["small"] = self._ListSmFontObj

            li.Init(str(v))
            li._Flag = v

            if v == "UUIDs":
                if len(self._AList[v]) > 1:
                    pp(self._AList[v][0])
                    sm_text = str(self._AList[v][0])
                else:
                    sm_text = "<empty>"
            else:
                sm_text = str(self._AList[v])

            if sm_text == "0":
                sm_text = "No"
            elif sm_text == "1":
                sm_text = "Yes"

            sm_text = sm_text[:20]
            li.SetSmallText(sm_text)

            li._PosX = 2
            self._MyList.append(li)

    def TryToForget(self):
        global adapter
        proxy_obj = bus.get_object("org.bluez", self._Path)
        dev = dbus.Interface(proxy_obj, "org.bluez.Device1")

        self._Screen._MsgBox.SetText("Forgeting")
        self._Screen._MsgBox.Draw()
        self._Screen.SwapAndShow()

        try:
            adapter.RemoveDevice(dev)
        except Exception, e:
            err_name = e.get_dbus_name()
            if err_name == "org.freedesktop.DBus.Error.NoReply":
                self._Screen._MsgBox.SetText("DBus noreply")
            else:
                self._Screen._MsgBox.SetText("Forget failed")

            self._Screen._MsgBox.Draw()
            self._Screen.SwapAndShow()

        pygame.time.delay(500)

        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
Пример #26
0
class WifiList(Page):
    _MyList = []
    #Wicd dbus part
    _Wireless = None
    _Daemon   = None
    _Dbus     = None
    _WifiPassword = ""
    _Connecting = False
    _Scanning   = False 
    
    _PrevWicdState = None
    
    _Selector = None
    
    _ShowingMessageBox = False 
    _MsgBox            = None
    _ConnectTry        = 0
    _BlockingUI        = False
    _BlockCb           = None
    
    _LastStatusMsg     = ""
    _FootMsg           = ["Nav","Info","Scan","Back","Enter"]
    _EncMethods        = None
    _Scroller          = None
    _ListFontObj       = MyLangManager.TrFont("notosanscjk15")

    _InfoPage          = None
    _CurBssid          = ""
    
    def __init__(self):
        Page.__init__(self)
        self._MyList = []
        self._CanvasHWND = None
    
    def ShowBox(self,msg):
        
        self._MsgBox._Text = msg
        self._ShowingMessageBox = True
        self._Screen.Draw()
        self._MsgBox.Draw()
        self._Screen.SwapAndShow()
    
    def HideBox(self):
        self.Draw()
        self._ShowingMessageBox = False
        self._Screen.SwapAndShow()

    def GenNetworkList(self):
        self._MyList = []
        start_x = 0
        start_y = 0

        for network_id in range(0,self._Wireless.GetNumberOfNetworks()):
            is_active = \
                self._Wireless.GetCurrentSignalStrength("") != 0 and \
                self._Wireless.GetCurrentNetworkID(self._Wireless.GetIwconfig()) == network_id \
                and self._Wireless.GetWirelessIP('') is not None

            ni = NetItem()
            ni._Parent = self
            ni._PosX = start_x
            ni._PosY = start_y + network_id* NetItem._Height
            ni._Width = Width
            ni._FontObj = self._ListFontObj
            #ni._Bssid   = self._Wireless.GetWirelessProperty(network_id,"bssid")
            
            ni.Init(network_id,is_active)
            self._MyList.append(ni)

        self._PsIndex = 0
        
    def Disconnect(self):
        self._Connecting= False
        self._Daemon.Disconnect()
    ## force to disconnect
    def ShutDownConnecting(self):
        print("Shutdownconnecting...",self._ConnectTry)
        self._Daemon.CancelConnect()
        self._Daemon.SetForcedDisconnect(True)
        self._Connecting = False

    def Rescan(self,sync=False):
        print("start Rescan")
        if self._Wireless != None:
            self._Wireless.Scan(sync)

## dbus signal functions
    def DbusScanFinishedSig(self):

        if self._Screen._CurrentPage != self:
            return
        self.ResetPageSelector()
        
        self.UpdateNetList(force_check=True)

        self._Scanning = False
        self.HideBox()
        self._BlockingUI = False
        print("dbus says scan finished")

    def DbusScanStarted(self):
        if self._Screen._CurrentPage !=self:
            return
        
        self._Scanning = True
        self.ShowBox(MyLangManager.Tr("Wifi scanning"))
        self._BlockingUI = True
        print("dbus says start scan...")


    def UpdateNetList(self,state=None,info=None,force_check=False,firstrun=False):

        if self._Daemon == None:
            return
        
        if not state:
            state,trash = self._Daemon.GetConnectionStatus()
            print("state")
            pp(state)
            print("Trash: ")
            pp(trash)

        if force_check or self._PrevWicdState != state:
            self.GenNetworkList() ## refresh the network list 
        
        if info != None:
            if len(info) > 3:
                _id  = int(info[3])
                if _id < len(self._MyList):
                    self._MyList[_id].UpdateStrenLabel( str(info[2]))

        self._PrevWicdState = state
        
    def SetConnectingStatus(self,fast):
        
        wireless_connecting = self._Wireless.CheckIfWirelessConnecting()

        """
        if self._ConnectTry > 5000:
            #wicd itself will take a very long time to try to connect ,will not block forever,just make it faster to dropout
            self.ShutDownConnecting()
            self._ConnectTry = 0
            self._BlockingUI = False
            return False
        """
        
        if wireless_connecting:
            
            if not fast:
                iwconfig = self._Wireless.GetIwconfig()
            else:
                iwconfig = ''
            essid = self._Wireless.GetCurrentNetwork(iwconfig)
            stat = self._Wireless.CheckWirelessConnectingMessage()
            if self._LastStatusMsg != "%s: %s"%(essid,stat):
                print("%s: %s" %(essid,stat))
                self._LastStatusMsg = "%s: %s"%(essid,stat)
                self.ShowBox(self._LastStatusMsg)
                
                self._Screen._FootBar.UpdateNavText(self._LastStatusMsg)
                SwapAndShow()
            #self._ConnectTry+=1

            return True
        else:
            self._Connecting = False
            return self._Connecting

    def UpdateStatus(self):
        print("UpdateStatus")
        wireless_connecting = self._Wireless.CheckIfWirelessConnecting()
        fast = not self._Daemon.NeedsExternalCalls()
        
        self._Connecting = wireless_connecting
        
        if self._Connecting:
            gobject.timeout_add(250,self.SetConnectingStatus,fast)
        else:
            if not fast:
                iwconfig = self._Wireless.GetIwconfig()
            else:
                iwconfig = ''

            if self.CheckForWireless(iwconfig,self._Wireless.GetWirelessIP(''),None):
                return True
            else:
                print("Not Connected")
                return True

    def DbusDaemonStatusChangedSig(self,state=None,info=None):
        if self._Screen._CurrentPage != self:
            return

        print("in DbusDaemonStatusChangedSig")
        """
        dbus.UInt32(2L)
        ['192.168.31.141', 'TP-LINK4G', '88', '0', '72.2 Mb/s']
        """
#        pp(info)
        self.UpdateNetList(state,info)
        if info != None:
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        

    def DbusConnectResultsSent(self,result):
        print(" in DbusConnectResultsSent")
        """
         in DbusConnectResultsSent
        'dhcp_failed'
        dbus says start scan...

        """
        if result != None:
            print(result)
            
        self._Connecting = False
        self._BlockingUI = False
        if self._BlockCb != None:
            self._BlockCb()
            self._BlockCb = None

        self._Screen._FootBar.ResetNavText()
    
    def CheckForWireless(self,iwconfig,wireless_ip,set_status):
        if not wireless_ip:
            return False
        network = self._Wireless.GetCurrentNetwork(iwconfig)
        if not network:
            return False
        network = misc.to_unicode(network)
        if daemon.GetSignalDisplayType() == 0:
            strength = self._Wireless.GetCurrentSignalStrength(iwconfig)
        else:
            strength = self._Wireless.GetCurrentDBMStrength(iwconfig)

        if strength is None:
            return False
        strength = misc.to_unicode(self._Daemon.FormatSignalForPrinting(strength))
        ip = misc.to_unicode(wireless_ip)

        print(_('Connected to $A at $B (IP: $C)').replace
                    ('$A', network).replace
                    ('$B', strength).replace
                    ('$C', ip))
        
        return True

    def ConfigWireless(self,password):
        
        netid = self._PsIndex
        
        for i,v in enumerate(self._MyList):
            if v._Bssid == self._CurBssid:
                netid = i
                break
        
        print(netid," ", password)
        """
        self._Wireless.SetWirelessProperty(netid,"dhcphostname","GameShell")
        self._Wireless.SetWirelessProperty(netid,"ip","None")
        self._Wireless.SetWirelessProperty(netid,"dns_domain","None")
        self._Wireless.SetWirelessProperty(netid,"gateway","None")
        self._Wireless.SetWirelessProperty(netid,"use_global_dns",0)
        self._Wireless.SetWirelessProperty(netid,"netmask","None")
        self._Wireless.SetWirelessProperty(netid,"usedhcphostname",0) ## set 1 to use hostname above
        self._Wireless.SetWirelessProperty(netid,"bitrate","auto")
        self._Wireless.SetWirelessProperty(netid,"allow_lower_bitrates",0)
        self._Wireless.SetWirelessProperty(netid,"dns3","None")
        self._Wireless.SetWirelessProperty(netid,"dns2","None")
        self._Wireless.SetWirelessProperty(netid,"dns1","None")
        self._Wireless.SetWirelessProperty(netid,"use_settings_globally",0)
        self._Wireless.SetWirelessProperty(netid,"use_static_dns",0)
        self._Wireless.SetWirelessProperty(netid,"search_domain","None")
        """
        self._Wireless.SetWirelessProperty(netid,"enctype","wpa-psk")
        self._Wireless.SetWirelessProperty(netid,"apsk",password)
        self._Wireless.SetWirelessProperty(netid,"automatic",1)

        self.ShowBox(MyLangManager.Tr("Connecting"))
        
        self._MyList[netid].Connect()
        print("after Connect")
        self.UpdateStatus()

    def GetWirelessEncrypt(self,network_id):
        results = []
        activeID = -1
        for x,enc_type in enumerate(self._EncMethods):
            if enc_type["type"] == self._Wireless.GetWirelessProperty(network_id,"enctype"):
                activeID = x
                break

        if activeID == -1:
            return results
        
        for type_ in ['required','optional']:
            fields = self._EncMethods[activeID][type_]
            for field in fields:
                try:
                    text = field[1].lower().replace(' ','_')
                except KeyError:
                    text = field[1].replace(' ','_')
                
                value = self._Wireless.GetWirelessProperty(network_id, field[0])
                results.append({text:value})
        """
        [{'preshared_key': 'blah blah blah',},]

        or nothing 
        [{'identity': None,},{'password': None,},]

        """
        return results

    def AbortedAndReturnToUpLevel(self):
        self.HideBox()
        self._Screen._FootBar.ResetNavText()
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()

    def OnKbdReturnBackCb(self):
        password_inputed = "".join(myvars.PasswordPage._Textarea._MyWords)
        if is_wifi_connected_now() == False:
            self.ConfigWireless(password_inputed)
        else:
            for i in range(0,10):
                if is_wifi_connected_now() == True:
                    self.ShowBox(MyLangManager.Tr("Launching"))
                    self._Daemon.Disconnect()
                    self._Daemon.SetForcedDisconnect(True)
                    self._Connecting = False
                else:
                    break
                
                pygame.time.delay(100)
                
            if is_wifi_connected_now() == False:
                self.ConfigWireless(password_inputed)
            else:
                self.ShowBox(MyLangManager.Tr("Disconnect first"))
        
    def OnReturnBackCb(self):
        pass
        
        
    def KeyDown(self,event):

#        if self._BlockingUI == True:
#            print("UI blocking ...")
#            return
        
        if IsKeyMenuOrB(event.key):
            if self._Wireless != None:
                wireless_connecting = self._Wireless.CheckIfWirelessConnecting()
                if wireless_connecting:
                    self.ShutDownConnecting()
                    self.ShowBox(MyLangManager.Tr("ShutDownConnecting"))
                    self._BlockingUI=True
                    self._BlockCb = self.AbortedAndReturnToUpLevel
                else:
                    self.AbortedAndReturnToUpLevel()
            else:
                self.HideBox()
                self.ReturnToUpLevelPage()
                self._Screen.Draw()
                self._Screen.SwapAndShow()
    
        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
            
        if IsKeyStartOrA(event.key): ## enter to set password,enter is B on GM
            if len(self._MyList) == 0:
                return
            
            self._CurBssid = self._MyList[self._PsIndex]._Bssid
            
            wicd_wirelss_encrypt_pwd = self.GetWirelessEncrypt(self._PsIndex)
            if self._MyList[self._PsIndex]._IsActive:
                self.ShowBox( self._Wireless.GetWirelessIP('')    )
            else:
                self._Screen.PushCurPage()
                self._Screen.SetCurPage( myvars.PasswordPage )
                
                thepass = ""
                for i in wicd_wirelss_encrypt_pwd:
                    if "preshared_key" in i:
                        if i["preshared_key"] != None:
                            if len(str(i["preshared_key"])) > 0:
                                thepass = str(i["preshared_key"])
                                break
                
                myvars.PasswordPage.SetPassword(thepass)
                self._Screen.Draw()
                self._Screen.SwapAndShow()
                
                """
                try:
                    self._Screen.Draw()
                    self._Screen.SwapAndShow()
                except Exception as e: 
                    print(e)
                    exit(-1)
                """
        if event.key == CurKeys["X"]:
            self.Rescan(False)
            
        if event.key == CurKeys["Y"]:
            if len(self._MyList) == 0:
                return

            self._InfoPage._NetworkId = self._PsIndex
            self._InfoPage._Wireless  = self._Wireless
            self._InfoPage._Daemon    = self._Daemon
            
            self._Screen.PushPage(self._InfoPage)
            self._Screen.Draw()
            self._Screen.SwapAndShow()
            

    def Init(self):
        
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        #self._CanvasHWND = pygame.Surface((self._Width,self._Height))
        self._CanvasHWND = self._Screen._CanvasHWND

        ps = WifiListSelector()
        ps._Parent = self
        ps._Width = Width - 12
        
        self._Ps = ps
        self._PsIndex = 0
        
        msgbox = WifiListMessageBox()
        msgbox._CanvasHWND = self._CanvasHWND
        msgbox.Init(" ",MyLangManager.TrFont("veramono12"))
        msgbox._Parent = self
        
        self._MsgBox = msgbox 

        self._EncMethods = misc.LoadEncryptionMethods() # load predefined templates from /etc/wicd/...

        """
  {
    'fields': [],
    'name': 'WPA 1/2 (Passphrase)',
    'optional': [],
    'protected': [
      ['apsk', 'Preshared_Key'],
    ],
    'required': [
      ['apsk', 'Preshared_Key'],
    ],
    'type': 'wpa-psk',
  },
        """
        
        self.UpdateNetList(force_check=True,firstrun=True)

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = 2
        self._Scroller._PosY = 2
        self._Scroller.Init()


        self._InfoPage = WifiInfoPage()
        self._InfoPage._Screen = self._Screen
        self._InfoPage._Name   = MyLangManager.Tr("Wifi info")
        self._InfoPage.Init()
        
    def Draw(self):
        self.ClearCanvas()

        if len(self._MyList) == 0:
            return
        
        self._Ps.Draw()
        for i in self._MyList:
            i.Draw()

        
        self._Scroller.UpdateSize( len(self._MyList)*NetItem._Height, self._PsIndex*NetItem._Height)
        self._Scroller.Draw()
Пример #27
0
class GPUDriverPage(Page):
    _FootMsg = ["Nav", "", "", "Back", "Select"]
    _MyList = []
    _ListFont = MyLangManager.TrFont("notosanscjk12")

    _AList = {}

    _Scrolled = 0

    _BGwidth = 320
    _BGheight = 240 - 24 - 20

    _DrawOnce = False
    _Scroller = None
    _InfoPage = None

    def __init__(self):
        Page.__init__(self)
        self._Icons = {}

    def GenList(self):

        self._MyList = []

        start_x = 0
        start_y = 0
        last_height = 0

        drivers = [["fbturbo", "FBTURBO driver (Software Rendering)"],
                   [
                       "modesetting",
                       "LIMA driver (Experimental Hardware Rendering)"
                   ]]

        for i, u in enumerate(drivers):
            #print(i,u)
            li = PageListItem()
            li._Parent = self
            li._PosX = start_x
            li._PosY = start_y + last_height
            li._Width = Width
            li._Fonts["normal"] = self._ListFont
            li._Active = False
            li._Value = u[0]
            li.Init(u[1])

            last_height += li._Height

            self._MyList.append(li)

    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._HWND = self._Screen._CanvasHWND
                self._CanvasHWND = pygame.Surface(
                    (self._Screen._Width, self._BGheight))

        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width  ## equal to screen width
        self._Height = self._Screen._Height

        done = IconItem()
        done._ImgSurf = MyIconPool.GiveIconSurface("done")
        done._MyType = ICON_TYPES["STAT"]
        done._Parent = self
        self._Icons["done"] = done

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.GenList()

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()
        self._Scroller.SetCanvasHWND(self._HWND)

    def Click(self):
        if len(self._MyList) == 0:
            return

        cur_li = self._MyList[self._PsIndex]
        if cur_li._Active == True:
            return

        print(cur_li._Value)

        if "arm" in platform.machine():
            for i in self._MyList:
                i._Active = False

            cur_li._Active = True
            self._Screen._MsgBox.SetText("Applying")
            self._Screen._MsgBox.Draw()
            self._Screen.SwapAndShow()

            if "modesetting" in cur_li._Value:  ## enable lima
                os.system("touch %s/.lima" % os.path.expanduser('~'))
                ArmSystem(
                    "sudo mv /usr/lib/xorg/modules/drivers/modesetting_drv.so.lima  /usr/lib/xorg/modules/drivers/modesetting_drv.so"
                )
                ArmSystem(
                    "sudo sed -i '/^#.*lima/s/^#//' /etc/ld.so.conf.d/00-arm-linux-gnueabihf.conf"
                )
                ArmSystem("sudo ldconfig")
            else:  #disable lima
                os.system("rm %s/.lima" % os.path.expanduser('~'))
                ArmSystem(
                    "sudo mv /usr/lib/xorg/modules/drivers/modesetting_drv.so /usr/lib/xorg/modules/drivers/modesetting_drv.so.lima"
                )
                ArmSystem(
                    "sudo sed -i 's/^[^#]*lima/#&/' /etc/ld.so.conf.d/00-arm-linux-gnueabihf.conf"
                )
                ArmSystem("sudo ldconfig")

            pygame.time.delay(800)
            os.system("sudo reboot")

        else:
            self._Screen._MsgBox.SetText("Do it in GameShell")
            self._Screen._MsgBox.Draw()
            self._Screen.SwapAndShow()

    def OnLoadCb(self):
        self._Scrolled = 0
        self._PosY = 0
        self._DrawOnce = False

        ## grep Driver /etc/xorg.conf | tr -s " " | cut -d " " -f3
        ## "fbturbo"
        ## "modesetting"
        thedrv = ""

        if "arm" in platform.machine():
            if FileExists("%s/.lima" % os.path.expanduser('~')):
                thedrv = "modesetting"
            else:
                thedrv = "fbturbo"

        if thedrv == "":
            thedrv = "fbturbo"

        for i in self._MyList:
            i._Active = False

        for i in self._MyList:
            if thedrv in i._Value:
                i._Active = True

    def OnReturnBackCb(self):
        pass
        """
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        """

    def KeyDown(self, event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

        if IsKeyStartOrA(event.key):
            self.Click()

        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()

    def Draw(self):

        self.ClearCanvas()
        if len(self._MyList) == 0:
            return

        else:
            if len(self._MyList) * PageListItem._Height > self._Height:
                self._Ps._Width = self._Width - 11
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()
                self._Scroller.UpdateSize(
                    len(self._MyList) * PageListItem._Height,
                    self._PsIndex * PageListItem._Height)
                self._Scroller.Draw()

            else:
                self._Ps._Width = self._Width
                self._Ps.Draw()
                for i in self._MyList:
                    if i._PosY > self._Height + self._Height / 2:
                        break
                    if i._PosY < 0:
                        continue
                    i.Draw()

        if self._HWND != None:
            self._HWND.fill(MySkinManager.GiveColor("White"))

            self._HWND.blit(
                self._CanvasHWND,
                (self._PosX, self._PosY, self._Width, self._Height))
Пример #28
0
class WifiInfoPage(Page):
    _FootMsg =  ["Nav","","","Back",""]
    _MyList = []
    _ListFontObj = MyLangManager.TrFont("varela15")

    _Wireless = None
    _Daemon   = None
    
    _AList = {}
    _NetworkId = -1
    
    def GenList(self):
        
        self._MyList = []
        if self._NetworkId != -1:
            self._AList["ip"]["value"] = "Not Connected"
            
            if self._Wireless.GetCurrentNetworkID(self._Wireless.GetIwconfig()) == self._NetworkId:
                ip = self._Wireless.GetWirelessIP('')
            
                if ip is not None:
                    self._AList["ip"]["value"] = ip
            
            self._AList["bssid"]["value"] = self._Wireless.GetWirelessProperty(self._NetworkId,"bssid")
        
        start_x  = 0
        start_y  = 0
        
        for i,v in enumerate( self._AList):
            li = InfoPageListItem()
            li._Parent = self
            li._PosX   = start_x
            li._PosY   = start_y + i*InfoPageListItem._Height
            li._Width  = Width
            li._Fonts["normal"] = self._ListFontObj
            li._Fonts["small"] = MyLangManager.TrFont("varela12")
            
            if self._AList[v]["label"] != "":
                li.Init(  self._AList[v]["label"] )
            else:
                li.Init( self._AList[v]["key"] )

            li._Flag = self._AList[v]["key"]

            li.SetSmallText( self._AList[v]["value"] )
            
            self._MyList.append(li)
            
    def Init(self):
        if self._Screen != None:
            if self._Screen._CanvasHWND != None and self._CanvasHWND == None:
                self._CanvasHWND = self._Screen._CanvasHWND

        self._PosX = self._Index*self._Screen._Width 
        self._Width = self._Screen._Width ## equal to screen width
        self._Height = self._Screen._Height

        ps = InfoPageSelector()
        ps._Parent = self
        ps._PosX = 2
        self._Ps = ps
        self._PsIndex = 0

        ip = {}
        ip["key"] = "ip"
        ip["label"] = "IP"
        ip["value"] = "Not Connected"
        
        bssid = {}
        bssid["key"] = "bssid"
        bssid["label"] = "BSSID"
        bssid["value"] = ""
        
        self._AList["ip"] = ip
        self._AList["bssid"] = bssid
        
        self.GenList()

        self._DisconnectConfirmPage = WifiDisconnectConfirmPage()
        self._DisconnectConfirmPage._Screen = self._Screen
        self._DisconnectConfirmPage._Name   = "Confirm Disconnect"
        self._DisconnectConfirmPage._Parent = self
        self._DisconnectConfirmPage.Init()

    def Click(self):
        cur_li = self._MyList[self._PsIndex]
        print(cur_li._Flag)        

    def TryDisconnect(self):
        if self._Wireless.GetCurrentNetworkID(self._Wireless.GetIwconfig()) == self._NetworkId \
           and self._Wireless.GetWirelessIP('') is not None:
            self._Screen.PushPage(self._DisconnectConfirmPage)
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        else:
            return
        
    def OnLoadCb(self):
        if self._Wireless.GetCurrentNetworkID(self._Wireless.GetIwconfig()) == self._NetworkId \
           and self._Wireless.GetWirelessIP('') is not None:
            self._FootMsg[2] = "Disconnect"
        else:
            self._FootMsg[2] =  ""

        self.GenList()

    def OnReturnBackCb(self):
        self.ReturnToUpLevelPage()
        self._Screen.Draw()
        self._Screen.SwapAndShow()
        
    def KeyDown(self,event):
        if IsKeyMenuOrB(event.key):
            self.ReturnToUpLevelPage()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        
        if event.key == CurKeys["Up"]:
            self.ScrollUp()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        if event.key == CurKeys["Down"]:
            self.ScrollDown()
            self._Screen.Draw()
            self._Screen.SwapAndShow()
        

        if IsKeyStartOrA(event.key):
            self.Click()

        if event.key == CurKeys["X"]:
            self.TryDisconnect()
                                
    def Draw(self):
        self.ClearCanvas()
        self._Ps.Draw()

        for i in self._MyList:
            i.Draw()
Пример #29
0
    def Init(self):
        self._PosX = self._Index * self._Screen._Width
        self._Width = self._Screen._Width
        self._Height = self._Screen._Height

        self._CanvasHWND = self._Screen._CanvasHWND

        ps = ListPageSelector()
        ps._Parent = self
        self._Ps = ps
        self._PsIndex = 0

        self.SyncList(self._Emulator["ROM"])

        ### will also mkdir of the ***ROM self
        try:
            os.makedirs(self._Emulator["ROM"] + "/.Trash")
        except OSError:
            if not os.path.isdir(self._Emulator["ROM"] + "/.Trash"):
                raise

        try:
            os.makedirs(self._Emulator["ROM"] + "/.Fav")
        except OSError:
            if not os.path.isdir(self._Emulator["ROM"] + "/.Fav"):
                raise

        self._MyStack._Emulator = self._Emulator

        icon_for_list = MultiIconItem()
        icon_for_list._ImgSurf = self._Parent._Icons["sys"]
        icon_for_list._MyType = ICON_TYPES["STAT"]
        icon_for_list._Parent = self

        icon_for_list.Adjust(0, 0, 18, 18, 0)

        self._Icons["sys"] = icon_for_list

        bgpng = IconItem()
        bgpng._ImgSurf = MyIconPool._Icons["empty"]
        bgpng._MyType = ICON_TYPES["STAT"]
        bgpng._Parent = self
        bgpng.AddLabel(MyLangManager.Tr("Please upload data over Wi-Fi"),
                       MyLangManager.TrFont("varela22"))
        bgpng.SetLableColor(MySkinManager.GiveColor('Disabled'))
        bgpng.Adjust(0, 0, self._BGwidth, self._BGheight, 0)

        self._Icons["bg"] = bgpng

        self._Scroller = ListScroller()
        self._Scroller._Parent = self
        self._Scroller._PosX = self._Width - 10
        self._Scroller._PosY = 2
        self._Scroller.Init()

        rom_so_confirm_page = RomSoConfirmPage()
        rom_so_confirm_page._Screen = self._Screen
        rom_so_confirm_page._Name = "Download Confirm"
        rom_so_confirm_page._Parent = self
        rom_so_confirm_page.Init()

        self._RomSoConfirmDownloadPage = rom_so_confirm_page
Пример #30
0
class UpdatePage(Page):
    _Icons = {}
    _FootMsg = ["Nav","","Check Update","Back",""]

    _ListFontObj = MyLangManager.TrFont("varela15")    
    _ConfirmPage = None
    _AList    = {}
    _MyList   = []
    def __init__(self):
        Page.__init__(self)
        self._Icons = {}    

    def GenList(self):
        
        start_x  = 0
        start_y  = 0
        
        for i,v in enumerate( self._AList):
            li = InfoPageListItem()
            li._Parent = self
            li._PosX   = start_x
            li._PosY   = start_y + i*InfoPageListItem._Height
            li._Width  = Width
            li._Fonts["normal"] = self._ListFontObj
            li._Fonts["small"] = MySkinManager.GiveFont("varela12")
            
            if self._AList[v]["label"] != "":
                li.Init(  self._AList[v]["label"] )
            else:
                li.Init( self._AList[v]["key"] )

            li._Flag = self._AList[v]["key"]

            li.SetSmallText( self._AList[v]["value"] )
            
            self._MyList.append(li)
        
    def Init(self):
        self._CanvasHWND = self._Screen._CanvasHWND
        self._Width =  self._Screen._Width
        self._Height = self._Screen._Height

        self._ConfirmPage = UpdateConfirmPage()
        self._ConfirmPage._Screen = self._Screen
        self._ConfirmPage._Name  = "Update Confirm"
        self._ConfirmPage._Parent = self
        self._ConfirmPage.Init()

        it = {}
        it["key"] = "version"
        it["label"] = "Version"
        it["value"] = config.VERSION
        self._AList["version"] = it
        
        self.GenList()
        
    def CheckUpdate(self):
        global LauncherLoc
        self._Screen._MsgBox.SetText("CheckingUpdate")
        self._Screen._MsgBox.Draw()
        self._Screen.SwapAndShow()

        try:
            r = requests.get(config.UPDATE_URL, verify=False, timeout=8)
        except:
            print("requests get error")
            return
        else:
            if r.status_code == requests.codes.ok:
                try:
                    json_ = r.json()

                    if "version" in json_ and "updatepath" in json_ and "md5sum" in json_:
                        if config.VERSION != json_["version"]:
                            
                            self._ConfirmPage._URL = json_["updatepath"]
                            self._ConfirmPage._MD5 = json_["md5sum"]
                            self._ConfirmPage._GIT = False
                            
                            self._Screen.PushPage(self._ConfirmPage)
                            
                            self._Screen.Draw()
                            self._ConfirmPage.SnapMsg(MyLangManager.Tr("ConfirmUpdateToFQ") % json_["version"] )
                            self._Screen.SwapAndShow()
                            
                    elif "gitversion" in json_: ### just use git to  run update
                        cur_dir = os.getcwd()
                        os.chdir(LauncherLoc)
                        current_git_version = get_git_revision_short_hash()
                        current_git_version = current_git_version.strip("\n")
                        current_git_version = current_git_version.strip("\t")
                        os.chdir(cur_dir)
                        if current_git_version != json_["gitversion"]:
                            self._ConfirmPage._URL = None
                            self._ConfirmPage._MD5 = None
                            self._ConfirmPage._GIT = True
                            self._ConfirmPage._Version = json_["gitversion"]
                            
                            self._Screen.PushPage(self._ConfirmPage)
                            
                            self._Screen.Draw()
                            self._ConfirmPage.SnapMsg(MyLangManager.Tr("UpdateToFQ") % json_["gitversion"] )
                            self._Screen.SwapAndShow()
                        else:
                            self._Screen.Draw()
                            self._Screen._MsgBox.SetText("LauncherIsUpToDate")
                            self._Screen._MsgBox.Draw()
                            self._Screen.SwapAndShow()
                            pygame.time.delay(765)
                            
                    return True
                except Exception, e:
                    print("r.json() error %s" % str(e))
                
            else: