main_screen.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. from beeprint import pp
  10. ## local package import
  11. from constants import ICON_TYPES,icon_ext,icon_width,icon_height,RUNEVT
  12. from icon_item import IconItem
  13. from page import Page,PageStack
  14. from title_bar import TitleBar
  15. from foot_bar import FootBar
  16. from constants import Width,Height,bg_color
  17. from util_funcs import midRect,FileExists,ReplaceSuffix,ReadTheFileContent,CmdClean,MakeExecutable,SkinMap
  18. from fonts import fonts
  19. from keys_def import CurKeys
  20. from label import Label
  21. from untitled_icon import UntitledIcon
  22. from Emulator import MyEmulator
  23. from skin_manager import SkinManager
  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. _SkinManager = None
  101. def __init__(self):
  102. self._Pages = []
  103. self._MyPageStack = PageStack()
  104. def Init(self):
  105. self._CanvasHWND = pygame.Surface((self._Width,self._Height))
  106. self._MsgBox= MessageBox()
  107. self._MsgBox._Parent= self
  108. self._MsgBox.Init(" ", self._MsgBoxFont)
  109. self._SkinManager = SkinManager()
  110. self._SkinManager.Init()
  111. def FartherPages(self):
  112. self._PageMax = len(self._Pages)
  113. for i in range(0,self._PageMax):
  114. self._Pages[i]._Index = i
  115. self._Pages[i]._CanvasHWND = self._CanvasHWND
  116. self._Pages[i]._IconNumbers = len(self._Pages[i]._Icons)
  117. self._Pages[i]._Screen = self
  118. self._Pages[i].Adjust()
  119. if self._Pages[i]._IconNumbers > 1:
  120. self._Pages[i]._PsIndex = 1
  121. self._Pages[i]._IconIndex = self._Pages[i]._PsIndex
  122. self._CurrentPage = self._Pages[self._PageIndex]
  123. self._CurrentPage._OnShow = True
  124. def GetMyRightSidePage(self):
  125. ret = self._PageIndex +1
  126. if ret > (self._PageMax -1):
  127. ret = self._PageMax -1
  128. return ret
  129. def PageMoveLeft(self):
  130. self._Pages[self._PageIndex]._OnShow = False
  131. if self._PageIndex < (self._PageMax - 1):
  132. my_right_side_page = self.GetMyRightSidePage()
  133. for i in range(0,self._PageMax):
  134. if i!= self._PageIndex and i != my_right_side_page:
  135. self._Pages[i].MoveLeft(Width)
  136. self._Pages[self._PageIndex].EasingLeft(Width)
  137. if self._PageIndex != my_right_side_page:
  138. self._Pages[my_right_side_page].EasingLeft(Width)
  139. self._Pages[self._PageIndex].ResetPageSelector()
  140. self._PageIndex+=1
  141. if self._PageIndex > (self._PageMax -1):
  142. self._PageIndex = (self._PageMax -1)
  143. self._Pages[self._PageIndex]._OnShow = True
  144. self._CurrentPage = self._Pages[self._PageIndex]
  145. def GetMyLeftSidePage(self):
  146. ret = self._PageIndex -1
  147. if ret < 0:
  148. ret = 0
  149. return ret
  150. def PageMoveRight(self):
  151. self._Pages[self._PageIndex]._OnShow = False
  152. if self._PageIndex > 0:
  153. my_left_side_page = self.GetMyLeftSidePage()
  154. for i in range(0,self._PageMax):
  155. if i!= self._PageIndex and i!= my_left_side_page:
  156. pass
  157. #self._Pages[i].MoveRight(Width)
  158. self._Pages[self._PageIndex].EasingRight(Width)
  159. if self._PageIndex != my_left_side_page:
  160. self._Pages[my_left_side_page].EasingRight(Width)
  161. self._Pages[self._PageIndex].ResetPageSelector()
  162. self._PageIndex-=1
  163. if self._PageIndex < 0:
  164. self._PageIndex = 0
  165. self._Pages[self._PageIndex]._OnShow = True
  166. self._CurrentPage = self._Pages[self._PageIndex]
  167. def EasingAllPageLeft(self):
  168. current_time = 0.0
  169. start_posx = 0.0
  170. current_posx = start_posx
  171. final_posx = float(Width)
  172. posx_init = 0
  173. dur = 30
  174. last_posx = 0.0
  175. all_last_posx = []
  176. if self._PageIndex >= (self._PageMax - 1):
  177. return
  178. for i in range(0,Width*dur):
  179. current_posx = easing.SineIn(current_time,start_posx,final_posx-start_posx,float(dur))
  180. if current_posx >= final_posx:
  181. current_posx = final_posx
  182. dx = current_posx - last_posx
  183. all_last_posx.append(int(dx))
  184. current_time+=1
  185. last_posx = current_posx
  186. if current_posx >= final_posx:
  187. break
  188. c = 0
  189. for i in all_last_posx:
  190. c+=i
  191. if c < final_posx - start_posx:
  192. all_last_posx.append( final_posx - c )
  193. for i in all_last_posx:
  194. self.ClearCanvas()
  195. for j in self._Pages:
  196. j._PosX -= i
  197. j.DrawIcons()
  198. j._Screen.SwapAndShow()
  199. self._Pages[self._PageIndex]._OnShow = False
  200. self._PageIndex+=1
  201. if self._PageIndex > (self._PageMax -1):
  202. self._PageIndex = (self._PageMax -1)
  203. self._Pages[self._PageIndex]._OnShow = True
  204. self._CurrentPage = self._Pages[self._PageIndex]
  205. def EasingAllPageRight(self):
  206. current_time = 0.0
  207. start_posx = 0.0
  208. current_posx = start_posx
  209. final_posx = float(Width)
  210. posx_init = 0
  211. dur = 30
  212. last_posx = 0.0
  213. all_last_posx = []
  214. if self._PageIndex <= 0:
  215. return
  216. for i in range(0,Width*dur):
  217. current_posx = easing.SineIn(current_time,start_posx,final_posx-start_posx,float(dur))
  218. if current_posx >= final_posx:
  219. current_posx = final_posx
  220. dx = current_posx - last_posx
  221. all_last_posx.append(int(dx))
  222. current_time+=1
  223. last_posx = current_posx
  224. if current_posx >= final_posx:
  225. break
  226. c = 0
  227. for i in all_last_posx:
  228. c+=i
  229. if c < final_posx - start_posx:
  230. all_last_posx.append( final_posx - c )
  231. for i in all_last_posx:
  232. self.ClearCanvas()
  233. for j in reversed(self._Pages):
  234. j._PosX += i
  235. j.DrawIcons()
  236. j._Screen.SwapAndShow()
  237. self._Pages[self._PageIndex]._OnShow = False
  238. self._PageIndex-=1
  239. if self._PageIndex < 0:
  240. self._PageIndex = 0
  241. self._Pages[self._PageIndex]._OnShow = True
  242. self._CurrentPage = self._Pages[self._PageIndex]
  243. def CurPage(self):
  244. return self._CurrentPage
  245. def PushCurPage(self):
  246. self._MyPageStack.Push(self._CurrentPage)
  247. def SetCurPage(self,page):
  248. self._CurrentPage = page
  249. on_load_cb = getattr(self._CurrentPage,"OnLoadCb",None)
  250. if on_load_cb != None:
  251. if callable( on_load_cb ):
  252. self._CurrentPage.OnLoadCb()
  253. def PushPage(self,page):
  254. self.PushCurPage()
  255. self.SetCurPage(page)
  256. def AppendPage(self,Page):
  257. self._Pages.append(Page)
  258. def ClearCanvas(self):
  259. self._CanvasHWND.fill((255,255,255))
  260. def SwapAndShow(self):
  261. if self._HWND != None:
  262. self._HWND.blit(self._CanvasHWND,(self._PosX,self._PosY,self._Width,self._Height))
  263. pygame.display.update()
  264. def ExtraName(self,name):
  265. ## extra name like 1_xxx to be => xxx,
  266. parts = name.split("_")
  267. if len(parts) > 1:
  268. return parts[1]
  269. elif len(parts) == 1:
  270. return parts[0]
  271. else:
  272. return name
  273. def IsEmulatorPackage(self,dirname):
  274. files = os.listdir(dirname)
  275. for i in sorted(files):
  276. if i.endswith(emulator_flag):
  277. return True
  278. return False
  279. def IsPythonPackage(self,dirname):
  280. files = os.listdir(dirname)
  281. for i in sorted(files):
  282. if i.endswith(python_package_flag):
  283. return True
  284. return False
  285. def ReadTheDirIntoPages(self,_dir,pglevel,cur_page):
  286. if FileExists(_dir) == False and os.path.isdir(_dir) == False:
  287. return
  288. files = os.listdir(_dir)
  289. for i in sorted(files):
  290. if os.path.isdir(_dir+"/"+i): # TOPLEVEL only is dir
  291. if pglevel == 0:
  292. page = Page()
  293. page._Name = self.ExtraName(i)
  294. page._Icons = []
  295. self._Pages.append(page)
  296. self.ReadTheDirIntoPages(_dir+"/"+i, pglevel+1 ,self._Pages[ len(self._Pages) -1])
  297. else: ## On CurPage now
  298. i2 = self.ExtraName(i)
  299. iconitem = IconItem()
  300. iconitem._CmdPath = ""
  301. iconitem.AddLabel(i2,self._IconFont)
  302. if FileExists( SkinMap(_dir+"/"+i2+".png") ):
  303. iconitem._ImageName = SkinMap(_dir+"/"+i2+".png")
  304. else:
  305. untitled = UntitledIcon()
  306. untitled.Init()
  307. if len(i2) > 1:
  308. untitled.SetWords(i2[:2])
  309. elif len(i2) == 1:
  310. untitled.SetWords([i2[0],i2[0]])
  311. else:
  312. untitled.SetWords(["G","s"])
  313. iconitem._ImgSurf = untitled.Surface()
  314. iconitem._ImageName = ""
  315. if self.IsPythonPackage(_dir+"/"+i):
  316. iconitem._MyType = ICON_TYPES["FUNC"]
  317. sys.path.append(_dir)
  318. iconitem._CmdPath = __import__(i)
  319. init_cb = getattr(iconitem._CmdPath,"Init",None)
  320. if init_cb != None:
  321. if callable(init_cb):
  322. iconitem._CmdPath.Init(self)
  323. cur_page._Icons.append(iconitem)
  324. elif self.IsEmulatorPackage(_dir+"/"+i):
  325. obj = {}
  326. obj["ROM"] = ""
  327. obj["ROM_SO"] =""
  328. obj["EXT"] = []
  329. obj["LAUNCHER"] = ""
  330. obj["TITLE"] = "Game"
  331. obj["SO_URL"] = ""
  332. obj["RETRO_CONFIG"] = "" ##
  333. try:
  334. f = open(_dir+"/"+i+"/"+emulator_flag)
  335. except IOError:
  336. print("action config open failed")
  337. return
  338. else:
  339. with f:
  340. content = f.readlines()
  341. content = [x.strip() for x in content]
  342. for i in content:
  343. pis = i.split("=")
  344. if len(pis) > 1:
  345. if "EXT" in pis[0]:
  346. obj[pis[0]] = pis[1].split(",")
  347. else:
  348. obj[pis[0]] = pis[1]
  349. em = MyEmulator()
  350. em._Emulator = obj
  351. em.Init(self)
  352. iconitem._CmdPath = em
  353. iconitem._MyType = ICON_TYPES["Emulator"]
  354. cur_page._Icons.append(iconitem)
  355. else:
  356. iconitem._MyType = ICON_TYPES["DIR"]
  357. iconitem._LinkPage = Page()
  358. iconitem._LinkPage._Name = i2
  359. cur_page._Icons.append(iconitem)
  360. self.ReadTheDirIntoPages(_dir+"/"+i,pglevel+1,iconitem._LinkPage)
  361. elif os.path.isfile(_dir+"/"+i) and pglevel > 0:
  362. if i.lower().endswith(icon_ext):
  363. i2 = self.ExtraName(i)
  364. #cmd = ReadTheFileContent(_dir+"/"+i)
  365. iconitem = IconItem()
  366. iconitem._CmdPath = _dir+"/"+i
  367. MakeExecutable(iconitem._CmdPath)
  368. iconitem._MyType = ICON_TYPES["EXE"]
  369. if FileExists( SkinMap( _dir+"/"+ReplaceSuffix(i2,"png"))):
  370. iconitem._ImageName = SkinMap(_dir+"/"+ReplaceSuffix(i2,"png"))
  371. else:
  372. untitled = UntitledIcon()
  373. untitled.Init()
  374. if len(i2) > 1:
  375. untitled.SetWords(i2[:2])
  376. elif len(i2) == 1:
  377. untitled.SetWords([i2[0],i2[0]])
  378. else:
  379. untitled.SetWords(["G","s"])
  380. iconitem._ImgSurf = untitled.Surface()
  381. iconitem._ImageName = ""
  382. iconitem.AddLabel(i2.split(".")[0],self._IconFont)
  383. iconitem._LinkPage = None
  384. cur_page._Icons.append(iconitem)
  385. def RunEXE(self,cmdpath):
  386. self.DrawRun()
  387. self.SwapAndShow()
  388. pygame.time.delay(1000)
  389. cmdpath = cmdpath.strip()
  390. cmdpath = CmdClean(cmdpath)
  391. pygame.event.post( pygame.event.Event(RUNEVT, message=cmdpath))
  392. def OnExitCb(self,event):
  393. ## leave rest to Pages
  394. on_exit_cb = getattr(self._CurrentPage,"OnExitCb",None)
  395. if on_exit_cb != None:
  396. if callable( on_exit_cb ):
  397. self._CurrentPage.OnExitCb(event)
  398. return
  399. def KeyDown(self,event):
  400. """
  401. if event.key == pygame.K_PAGEUP:
  402. self.EasingAllPageLeft()
  403. #self.SwapAndShow()
  404. if event.key == pygame.K_PAGEDOWN:
  405. self.EasingAllPageRight()
  406. #self.SwapAndShow()
  407. """
  408. if event.key == pygame.K_t:
  409. self.DrawRun()
  410. self.SwapAndShow()
  411. if event.key == CurKeys["Space"]:
  412. self.Draw()
  413. self.SwapAndShow()
  414. ## leave rest to Pages
  415. current_page_key_down_cb = getattr(self._CurrentPage,"KeyDown",None)
  416. if current_page_key_down_cb != None:
  417. if callable( current_page_key_down_cb ):
  418. self._CurrentPage.KeyDown(event)
  419. def DrawRun(self):
  420. self._MsgBox.SetText("Launching....")
  421. self._MsgBox.Draw()
  422. def Draw(self):
  423. self._CurrentPage.Draw()
  424. #if self._HWND != None:
  425. # self._HWND.blit(self._CanvasHWND,(self._PosX,self._PosY,self._Width,self._Height))
  426. if self._TitleBar != None:
  427. self._TitleBar.Draw(self._CurrentPage._Name)
  428. if self._FootBar != None:
  429. if hasattr(self._CurrentPage,"_FootMsg"):
  430. self._FootBar.SetLabelTexts(self._CurrentPage._FootMsg)
  431. self._FootBar.Draw()