main_screen.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. # -*- coding: utf-8 -*-
  2. import pygame
  3. from pygame.locals import *
  4. from sys import exit
  5. import os
  6. import sys
  7. from libs import easing
  8. from datetime import datetime
  9. import base64
  10. from beeprint import pp
  11. ## local package import
  12. from constants import ICON_TYPES,icon_ext,icon_width,icon_height,RUNEVT
  13. from icon_item import IconItem
  14. from page import Page,PageStack
  15. from title_bar import TitleBar
  16. from foot_bar import FootBar
  17. from constants import Width,Height,bg_color
  18. from util_funcs import midRect,FileExists,ReplaceSuffix,ReadTheFileContent,CmdClean,MakeExecutable,SkinMap
  19. from fonts import fonts
  20. from keys_def import CurKeys
  21. from label import Label
  22. from untitled_icon import UntitledIcon
  23. from Emulator import MyEmulator
  24. class MessageBox(Label):
  25. _Parent = None
  26. def __init__(self):
  27. pass
  28. def Init(self,text,font_obj,color=pygame.Color(83,83,83)):
  29. self._Color = color
  30. self._FontObj = font_obj
  31. self._Text = text
  32. self._Width = 0
  33. self._Height = 0
  34. self._CanvasHWND = pygame.Surface( ( int(self._Parent._Width),int(self._Parent._Height)))
  35. self._HWND = self._Parent._CanvasHWND
  36. def SetText(self,text):
  37. self._Text = text
  38. def Draw(self):
  39. self._Width = 0
  40. self._Height = 0
  41. self._CanvasHWND.fill( (255,255,255))
  42. words = self._Text.split(' ')
  43. space = self._FontObj.size(' ')[0]
  44. max_width = self._Parent._Width-40
  45. x ,y = (0,0)
  46. row_total_width = 0
  47. lines = 0
  48. for word in words:
  49. word_surface = self._FontObj.render(word, True, self._Color)
  50. word_width = word_surface.get_width()
  51. word_height = word_surface.get_height()
  52. row_total_width += word_width
  53. if lines == 0:
  54. lines += word_height
  55. if row_total_width+space >= max_width:
  56. x = 0 # Reset the x.
  57. y += word_height # Start on new row.
  58. row_total_width = word_width
  59. lines += word_height
  60. self._CanvasHWND.blit(word_surface, (x, y))
  61. if len(words) == 1: # single line
  62. x += word_width
  63. else:
  64. x += word_width + space
  65. if x > self._Width:
  66. self._Width = x
  67. if lines >= (self._Parent._Height - 40):
  68. break
  69. self._Height = lines
  70. padding = 5
  71. x = (self._Parent._Width - self._Width)/2
  72. y = (self._Parent._Height - self._Height)/2
  73. # print("x %d y %d w %d h %d" %(x,y,self._Width,self._Height ))
  74. pygame.draw.rect(self._HWND,(255,255,255),(x-padding,y-padding, self._Width+padding*2,self._Height+padding*2))
  75. if self._HWND != None:
  76. rect = midRect(self._Parent._Width/2,self._Parent._Height/2,self._Width,self._Height,Width,Height)
  77. self._HWND.blit(self._CanvasHWND,rect,(0,0,self._Width,self._Height))
  78. #self._HWND.blit(self._CanvasHWND,rect)
  79. pygame.draw.rect(self._HWND,(0,0,0),(x-padding,y-padding, self._Width+padding*2,self._Height+padding*2),1)
  80. python_package_flag = "__init__.py"
  81. emulator_flag = "action.config"
  82. ##Abstract object for manage Pages ,not the pygame's physic screen
  83. class MainScreen(object):
  84. _Pages = []
  85. _PageMax = 0
  86. _PageIndex = 0
  87. _PosX = 0
  88. _PosY = TitleBar._BarHeight+1
  89. _Width = Width
  90. _Height = Height -FootBar._BarHeight -TitleBar._BarHeight-1
  91. _MyPageStack = None
  92. _CurrentPage = None # pointer to the current displaying Page Class
  93. _CanvasHWND = None
  94. _HWND = None
  95. _TitleBar = None
  96. _FootBar = None
  97. _MsgBox = None
  98. _MsgBoxFont = fonts["veramono20"]
  99. _IconFont = fonts["varela15"]
  100. def __init__(self):
  101. self._Pages = []
  102. self._MyPageStack = PageStack()
  103. def Init(self):
  104. self._CanvasHWND = pygame.Surface((self._Width,self._Height))
  105. self._MsgBox= MessageBox()
  106. self._MsgBox._Parent= self
  107. self._MsgBox.Init(" ", self._MsgBoxFont)
  108. def FartherPages(self):
  109. self._PageMax = len(self._Pages)
  110. for i in range(0,self._PageMax):
  111. self._Pages[i]._Index = i
  112. self._Pages[i]._CanvasHWND = self._CanvasHWND
  113. self._Pages[i]._IconNumbers = len(self._Pages[i]._Icons)
  114. self._Pages[i]._Screen = self
  115. self._Pages[i].Adjust()
  116. if self._Pages[i]._IconNumbers > 1:
  117. self._Pages[i]._PsIndex = 1
  118. self._Pages[i]._IconIndex = self._Pages[i]._PsIndex
  119. self._CurrentPage = self._Pages[self._PageIndex]
  120. self._CurrentPage._OnShow = True
  121. def GetMyRightSidePage(self):
  122. ret = self._PageIndex +1
  123. if ret > (self._PageMax -1):
  124. ret = self._PageMax -1
  125. return ret
  126. def PageMoveLeft(self):
  127. self._Pages[self._PageIndex]._OnShow = False
  128. if self._PageIndex < (self._PageMax - 1):
  129. my_right_side_page = self.GetMyRightSidePage()
  130. for i in range(0,self._PageMax):
  131. if i!= self._PageIndex and i != my_right_side_page:
  132. self._Pages[i].MoveLeft(Width)
  133. self._Pages[self._PageIndex].EasingLeft(Width)
  134. if self._PageIndex != my_right_side_page:
  135. self._Pages[my_right_side_page].EasingLeft(Width)
  136. self._Pages[self._PageIndex].ResetPageSelector()
  137. self._PageIndex+=1
  138. if self._PageIndex > (self._PageMax -1):
  139. self._PageIndex = (self._PageMax -1)
  140. self._Pages[self._PageIndex]._OnShow = True
  141. self._CurrentPage = self._Pages[self._PageIndex]
  142. def GetMyLeftSidePage(self):
  143. ret = self._PageIndex -1
  144. if ret < 0:
  145. ret = 0
  146. return ret
  147. def PageMoveRight(self):
  148. self._Pages[self._PageIndex]._OnShow = False
  149. if self._PageIndex > 0:
  150. my_left_side_page = self.GetMyLeftSidePage()
  151. for i in range(0,self._PageMax):
  152. if i!= self._PageIndex and i!= my_left_side_page:
  153. pass
  154. #self._Pages[i].MoveRight(Width)
  155. self._Pages[self._PageIndex].EasingRight(Width)
  156. if self._PageIndex != my_left_side_page:
  157. self._Pages[my_left_side_page].EasingRight(Width)
  158. self._Pages[self._PageIndex].ResetPageSelector()
  159. self._PageIndex-=1
  160. if self._PageIndex < 0:
  161. self._PageIndex = 0
  162. self._Pages[self._PageIndex]._OnShow = True
  163. self._CurrentPage = self._Pages[self._PageIndex]
  164. def EasingAllPageLeft(self):
  165. current_time = 0.0
  166. start_posx = 0.0
  167. current_posx = start_posx
  168. final_posx = float(Width)
  169. posx_init = 0
  170. dur = 30
  171. last_posx = 0.0
  172. all_last_posx = []
  173. if self._PageIndex >= (self._PageMax - 1):
  174. return
  175. for i in range(0,Width*dur):
  176. current_posx = easing.SineIn(current_time,start_posx,final_posx-start_posx,float(dur))
  177. if current_posx >= final_posx:
  178. current_posx = final_posx
  179. dx = current_posx - last_posx
  180. all_last_posx.append(int(dx))
  181. current_time+=1
  182. last_posx = current_posx
  183. if current_posx >= final_posx:
  184. break
  185. c = 0
  186. for i in all_last_posx:
  187. c+=i
  188. if c < final_posx - start_posx:
  189. all_last_posx.append( final_posx - c )
  190. for i in all_last_posx:
  191. self.ClearCanvas()
  192. for j in self._Pages:
  193. j._PosX -= i
  194. j.DrawIcons()
  195. j._Screen.SwapAndShow()
  196. self._Pages[self._PageIndex]._OnShow = False
  197. self._PageIndex+=1
  198. if self._PageIndex > (self._PageMax -1):
  199. self._PageIndex = (self._PageMax -1)
  200. self._Pages[self._PageIndex]._OnShow = True
  201. self._CurrentPage = self._Pages[self._PageIndex]
  202. def EasingAllPageRight(self):
  203. current_time = 0.0
  204. start_posx = 0.0
  205. current_posx = start_posx
  206. final_posx = float(Width)
  207. posx_init = 0
  208. dur = 30
  209. last_posx = 0.0
  210. all_last_posx = []
  211. if self._PageIndex <= 0:
  212. return
  213. for i in range(0,Width*dur):
  214. current_posx = easing.SineIn(current_time,start_posx,final_posx-start_posx,float(dur))
  215. if current_posx >= final_posx:
  216. current_posx = final_posx
  217. dx = current_posx - last_posx
  218. all_last_posx.append(int(dx))
  219. current_time+=1
  220. last_posx = current_posx
  221. if current_posx >= final_posx:
  222. break
  223. c = 0
  224. for i in all_last_posx:
  225. c+=i
  226. if c < final_posx - start_posx:
  227. all_last_posx.append( final_posx - c )
  228. for i in all_last_posx:
  229. self.ClearCanvas()
  230. for j in reversed(self._Pages):
  231. j._PosX += i
  232. j.DrawIcons()
  233. j._Screen.SwapAndShow()
  234. self._Pages[self._PageIndex]._OnShow = False
  235. self._PageIndex-=1
  236. if self._PageIndex < 0:
  237. self._PageIndex = 0
  238. self._Pages[self._PageIndex]._OnShow = True
  239. self._CurrentPage = self._Pages[self._PageIndex]
  240. def CurPage(self):
  241. return self._CurrentPage
  242. def PushCurPage(self):
  243. self._MyPageStack.Push(self._CurrentPage)
  244. def SetCurPage(self,page):
  245. self._CurrentPage = page
  246. on_load_cb = getattr(self._CurrentPage,"OnLoadCb",None)
  247. if on_load_cb != None:
  248. if callable( on_load_cb ):
  249. self._CurrentPage.OnLoadCb()
  250. def PushPage(self,page):
  251. self.PushCurPage()
  252. self.SetCurPage(page)
  253. def AppendPage(self,Page):
  254. self._Pages.append(Page)
  255. def ClearCanvas(self):
  256. self._CanvasHWND.fill((255,255,255))
  257. def SwapAndShow(self):
  258. if self._HWND != None:
  259. self._HWND.blit(self._CanvasHWND,(self._PosX,self._PosY,self._Width,self._Height))
  260. pygame.display.update()
  261. def ExtraName(self,name):
  262. ## extra name like 1_xxx to be => xxx,
  263. parts = name.split("_")
  264. if len(parts) > 1:
  265. return parts[1]
  266. elif len(parts) == 1:
  267. return parts[0]
  268. else:
  269. return name
  270. def IsEmulatorPackage(self,dirname):
  271. files = os.listdir(dirname)
  272. for i in sorted(files):
  273. if i.endswith(emulator_flag):
  274. return True
  275. return False
  276. def IsPythonPackage(self,dirname):
  277. files = os.listdir(dirname)
  278. for i in sorted(files):
  279. if i.endswith(python_package_flag):
  280. return True
  281. return False
  282. def ReadTheDirIntoPages(self,_dir,pglevel,cur_page):
  283. if FileExists(_dir) == False and os.path.isdir(_dir) == False:
  284. return
  285. files = os.listdir(_dir)
  286. for i in sorted(files):
  287. if os.path.isdir(_dir+"/"+i): # TOPLEVEL only is dir
  288. if pglevel == 0:
  289. page = Page()
  290. page._Name = self.ExtraName(i)
  291. page._Icons = []
  292. self._Pages.append(page)
  293. self.ReadTheDirIntoPages(_dir+"/"+i, pglevel+1 ,self._Pages[ len(self._Pages) -1])
  294. else: ## On CurPage now
  295. i2 = self.ExtraName(i)
  296. iconitem = IconItem()
  297. iconitem._CmdPath = ""
  298. iconitem.AddLabel(i2,self._IconFont)
  299. if FileExists( SkinMap(_dir+"/"+i2+".png") ):
  300. iconitem._ImageName = SkinMap(_dir+"/"+i2+".png")
  301. else:
  302. untitled = UntitledIcon()
  303. untitled.Init()
  304. if len(i2) > 1:
  305. untitled.SetWords(i2[:2])
  306. elif len(i2) == 1:
  307. untitled.SetWords([i2[0],i2[0]])
  308. else:
  309. untitled.SetWords(["G","s"])
  310. iconitem._ImgSurf = untitled.Surface()
  311. iconitem._ImageName = ""
  312. if self.IsPythonPackage(_dir+"/"+i):
  313. iconitem._MyType = ICON_TYPES["FUNC"]
  314. sys.path.append(_dir)
  315. iconitem._CmdPath = __import__(i)
  316. init_cb = getattr(iconitem._CmdPath,"Init",None)
  317. if init_cb != None:
  318. if callable(init_cb):
  319. iconitem._CmdPath.Init(self)
  320. cur_page._Icons.append(iconitem)
  321. elif self.IsEmulatorPackage(_dir+"/"+i):
  322. obj = {}
  323. obj["ROM"] = ""
  324. obj["ROM_SO"] =""
  325. obj["EXT"] = []
  326. obj["LAUNCHER"] = ""
  327. obj["TITLE"] = "Game"
  328. obj["SO_URL"] = ""
  329. try:
  330. f = open(_dir+"/"+i+"/"+emulator_flag)
  331. except IOError:
  332. print("action config open failed")
  333. return
  334. else:
  335. with f:
  336. content = f.readlines()
  337. content = [x.strip() for x in content]
  338. for i in content:
  339. pis = i.split("=")
  340. if len(pis) > 1:
  341. if "EXT" in pis[0]:
  342. obj[pis[0]] = pis[1].split(",")
  343. else:
  344. obj[pis[0]] = pis[1]
  345. em = MyEmulator()
  346. em._Emulator = obj
  347. em.Init(self)
  348. iconitem._CmdPath = em
  349. iconitem._MyType = ICON_TYPES["Emulator"]
  350. cur_page._Icons.append(iconitem)
  351. else:
  352. iconitem._MyType = ICON_TYPES["DIR"]
  353. iconitem._LinkPage = Page()
  354. iconitem._LinkPage._Name = i2
  355. cur_page._Icons.append(iconitem)
  356. self.ReadTheDirIntoPages(_dir+"/"+i,pglevel+1,iconitem._LinkPage)
  357. elif os.path.isfile(_dir+"/"+i) and pglevel > 0:
  358. if i.lower().endswith(icon_ext):
  359. i2 = self.ExtraName(i)
  360. #cmd = ReadTheFileContent(_dir+"/"+i)
  361. iconitem = IconItem()
  362. iconitem._CmdPath = _dir+"/"+i
  363. MakeExecutable(iconitem._CmdPath)
  364. iconitem._MyType = ICON_TYPES["EXE"]
  365. if FileExists( SkinMap( _dir+"/"+ReplaceSuffix(i2,"png"))):
  366. iconitem._ImageName = SkinMap(_dir+"/"+ReplaceSuffix(i2,"png"))
  367. else:
  368. untitled = UntitledIcon()
  369. untitled.Init()
  370. if len(i2) > 1:
  371. untitled.SetWords(i2[:2])
  372. elif len(i2) == 1:
  373. untitled.SetWords([i2[0],i2[0]])
  374. else:
  375. untitled.SetWords(["G","s"])
  376. iconitem._ImgSurf = untitled.Surface()
  377. iconitem._ImageName = ""
  378. iconitem.AddLabel(i2.split(".")[0],self._IconFont)
  379. iconitem._LinkPage = None
  380. cur_page._Icons.append(iconitem)
  381. def RunEXE(self,cmdpath):
  382. self.DrawRun()
  383. self.SwapAndShow()
  384. pygame.time.delay(1000)
  385. cmdpath = cmdpath.strip()
  386. cmdpath = CmdClean(cmdpath)
  387. pygame.event.post( pygame.event.Event(RUNEVT, message=cmdpath))
  388. def OnExitCb(self,event):
  389. ## leave rest to Pages
  390. on_exit_cb = getattr(self._CurrentPage,"OnExitCb",None)
  391. if on_exit_cb != None:
  392. if callable( on_exit_cb ):
  393. self._CurrentPage.OnExitCb(event)
  394. return
  395. def KeyDown(self,event):
  396. """
  397. if event.key == pygame.K_PAGEUP:
  398. self.EasingAllPageLeft()
  399. #self.SwapAndShow()
  400. if event.key == pygame.K_PAGEDOWN:
  401. self.EasingAllPageRight()
  402. #self.SwapAndShow()
  403. """
  404. if event.key == pygame.K_t:
  405. self.DrawRun()
  406. self.SwapAndShow()
  407. if event.key == CurKeys["Space"]:
  408. self.Draw()
  409. self.SwapAndShow()
  410. ## leave rest to Pages
  411. current_page_key_down_cb = getattr(self._CurrentPage,"KeyDown",None)
  412. if current_page_key_down_cb != None:
  413. if callable( current_page_key_down_cb ):
  414. self._CurrentPage.KeyDown(event)
  415. def DrawRun(self):
  416. self._MsgBox.SetText("Launching....")
  417. self._MsgBox.Draw()
  418. def Draw(self):
  419. self._CurrentPage.Draw()
  420. #if self._HWND != None:
  421. # self._HWND.blit(self._CanvasHWND,(self._PosX,self._PosY,self._Width,self._Height))
  422. if self._TitleBar != None:
  423. self._TitleBar.Draw(self._CurrentPage._Name)
  424. if self._FootBar != None:
  425. if hasattr(self._CurrentPage,"_FootMsg"):
  426. self._FootBar.SetLabelTexts(self._CurrentPage._FootMsg)
  427. self._FootBar.Draw()