def get(self, s, autoComplete, defaultText, **kwargs): if self.waitForInput: print "\nTerminal: Getting input in an existing input-request is forbidden." print "Terminal: Probably you attempted to do an input-request in an autocomplete callback." return "" elif terminalTools.keyGrabber.active: print "\nTerminal: Getting input whilest grabbing keys is forbidden." print "Terminal: Call 'terminalTools.keyGrabber.pause()' before doing any input-request." print "Terminal: Afterwards, call 'terminalTools.keyGrabber.resume()' to continue grabbing keys." return "" e32.ao_yield() self.updateData = s, kwargs prompt.enterKey = self.set prompt.setAutoComplete(autoComplete) terminalTools.print_special(s, doNL = False, **kwargs) prompt.setPosToEnd(True) prompt.add(defaultText) self.waitForInput = True while True: if wantExit or not self.waitForInput: prompt.enterKey = None prompt.setAutoComplete(False) print self.waitForInput = False checkForExit() return self.inputBuffer else: e32.ao_yield()
def draw_welcome(): wel_col = 1 while not start: img.text((fitx(cn(TITLE), (0, W)), H / 4 + 1), cn(TITLE), fill=SHADOW, font=FONT) img.text((fitx(cn(TITLE), (0, W)) + 1, H / 4), cn(TITLE), fill=MAINFONT_CLR, font=FONT) fsym = img.measure_text(cn(TIP), font='symbol') fsym2 = img.measure_text(cn(COPYRIGHT)) img.text(((W / 2 - fsym[1] / 2), H * 4 / 5), cn(TIP), fill=(0, 100 * wel_col, 0), font='symbol') img.text(((W / 2 - fsym2[1] / 2), H * 19 / 20), cn(COPYRIGHT), fill=SHADOW) paint(()) wel_col += 1 if wel_col == 3: wel_col = 1 e32.ao_yield() e32.ao_sleep(0.1) while 1: e32.ao_yield()
def cb_select(): ''' Callback for listbox item selection event ''' ### keypress handler trick, to allow Enter/Select work global g_time my_timer.cancel() # Ignore first and non-timer trickered events if (not g_time) or (time.clock() - g_time < 0.1): g_time = time.clock() # Should be more than start keyrepeat rate my_timer.after(0.15, cb_select) return g_time = 0 ### keypress handler trick, done # Current listbox selection index = lb3.current() # Change selected item icon: on <-> off if e3[index][1] == icon_on: new_icon = icon_off else: new_icon = icon_on e3[index] = (e3[index][0], new_icon) # Show new list, same item selected lb3.set_list(e3, index) appuifw.app.body = lb3 # Make it visible e32.ao_yield()
def rank(): appuifw.app.exit_key_handler = menu try: db = e32dbm.open("c:\\ranklist.e32dbm", "r") tdb = db.items() db.close() except: appuifw.note(chn("暂无排行榜"), "error") for i in range(len(tdb) - 1): for j in range(len(tdb) - i - 1): if int(tdb[j][1]) < int(tdb[j + 1][1]): t = tdb[j] tdb[j] = tdb[j + 1] tdb[j + 1] = t while 1: img.clear(0) img.rectangle( (0, 0, 176, 208), outline=color_box[random.randint(0, 3)][random.randint(0, 3)]) img.text((20, 20), chn("排---------行-------榜"), 0xff0000, font=ziti) img.text((20, 190), chn("排--------行---------榜"), 0xff0000, font=ziti) for i in range(8): img.text((30, 30 + i * 20), chn(tdb[i][0]), 0x0000ff) img.text((140, 30 + i * 20), chn(tdb[i][1]), 0x00ff00) handle_redraw(()) e32.ao_sleep(0.2) e32.ao_yield()
def decl(path): try: try: os.rmdir(en(path)) pt(cn('删除') + path) except: sa = os.listdir(en(path)) for i in sa: pt(cn(('删除%s%s' % (en(path), i)))) try: os.remove((en(path) + '\\' + i)) except: try: os.rmdir((en(path) + '\\' + i)) except: decl(((path + cn(i)) + '\\')) decl(path) except: pt(path + cn("不存在<或只读文件>")) app_lock = e32.Ao_lock() if A.query(path + cn("无法删除,跳过删除其它文件?"), "query"): app_lock.signal() else: pt(cn("\n删完完毕,剩下只读文件!")) app_lock.wait() e32.ao_yield() A.app.title = old
def show(self, goto, full, text=u'Loading...', shadow=1, stop=1): if goto > full or \ not self.focusflag or \ not full or \ goto < 0: return if isinstance(text, (tuple, list)): text, text2 = text else: text2 = None text, xx = self.x_text(text, 'annotation', self.scr[0] - 26) xx -=5 try: self.window.remove_image(self.img) except ValueError: pass self.img.rectangle((0, 0, self.img.size[0], self.__sizeY), 0xcccccc, self.color_background) x = abs((self.img.size[0] - 12) * goto / full) self.img1.clear(self.color_background2) a, b = self.img1.size self.img2.blit(self.img_gradient) if text2: text2, xx2 = self.x_text(text2, 'dense', self.scr[0] - 37) xx2 -= 11 self.img1.text((xx2, b - 3 - self.__dislocation_text2), text2, self.color_text2, 'dense') self.img2.text((xx2, b - 4 - self.__dislocation_text2), text2, 0, 'dense') self.img1.blit(self.img2, source = (0, 0, x, self.__sizeW), target = (0, 1)) self.img1.rectangle((0, 0, a, b), 0xcccccc) self.img.blit(self.img1, target = (6, self.__sizeY - self.__sizeW - 6)) self.img.text((xx, self.__sizeY - self.__sizeW - 6 - self.__h_text / 2 - self.__dislocation_text), text, self.color_text, 'annotation') self.window.add_image(self.img, (0, 0)) if shadow and not self.top_shadow.visible: self.top_shadow.show() self.window.show() e32.ao_yield() if goto == full and stop: e32.ao_sleep(0.1, self.stop)
def cb_select(): """ Callback for listbox item selection event """ ### keypress handler trick, to allow Enter/Select work global g_time my_timer.cancel() # Ignore first and non-timer trickered events if (not g_time) or (time.clock() - g_time < 0.1): g_time = time.clock() # Should be more than start keyrepeat rate my_timer.after(0.15, cb_select) return g_time = 0 ### keypress handler trick, done # Current listbox selection index = lb3.current() # Change selected item icon: on <-> off if e3[index][1] == icon_on: new_icon = icon_off else: new_icon = icon_on e3[index] = (e3[index][0], new_icon) # Show new list, same item selected lb3.set_list(e3, index) appuifw.app.body = lb3 # Make it visible e32.ao_yield()
def videocamera(): global keyboard i=len(os.listdir("E:\\Videos\\")) video_savepath=u"E:\\Videos\\vid%d.mp4" % i canvas=appuifw.Canvas(event_callback=keyboard.handle_event, redraw_callback=None) appuifw.app.body=canvas camera.stop_finder() camera.start_finder(vf, size=(240,196)) recording=False running=True while running: if keyboard.pressed(EScancodeSelect): if not recording: vid=camera.start_record(video_savepath, video_callback) #Start recording the video recording=True else: camera.stop_record() #Stop recording videocamera() #Restart the camera in video mode if keyboard.pressed(EScancodeRightSoftkey) and recording: camera.stop_record() quit() appuifw.app.menu=[(u"Exit", quit)] e32.ao_yield()
def videocamera(): global keyboard i = len(os.listdir("E:\\Videos\\")) video_savepath = u"E:\\Videos\\vid%d.mp4" % i canvas = appuifw.Canvas(event_callback=keyboard.handle_event, redraw_callback=None) appuifw.app.body = canvas camera.stop_finder() camera.start_finder(vf, size=(240, 196)) recording = False running = True while running: if keyboard.pressed(EScancodeSelect): if not recording: vid = camera.start_record( video_savepath, video_callback) #Start recording the video recording = True else: camera.stop_record() #Stop recording videocamera() #Restart the camera in video mode if keyboard.pressed(EScancodeRightSoftkey) and recording: camera.stop_record() quit() appuifw.app.menu = [(u"Exit", quit)] e32.ao_yield()
def play(self): ui.start_anew(self.health) while not self.game_over: # Stop the screensaver coming on (if we have the misty module present) if globals().__contains__('misty'): misty.reset_inactivity_time() self.eventlock.wait() if self.event == INCOMING_HORIZONTAL_ATTACK_EVENT: self.defend(self.event) elif self.event == INCOMING_VERTICAL_ATTACK_EVENT: self.defend(self.event) elif self.event == OUTGOING_HORIZONTAL_ATTACK_EVENT: self.attack(self.event) elif self.event == OUTGOING_VERTICAL_ATTACK_EVENT: self.attack(self.event) elif self.event == VICTORY_EVENT: self.victory() self.event = None e32.ao_yield() #? self.__timer.cancel() axyz.disconnect() self.rotation_sensor.disconnect() ui.won_or_dead(self.won) return (self.won, self.quitting)
def preview(self): if not self.running: movie = [ os.path.join(self.dir,f) for f in os.listdir(self.dir) ] movie.reverse() if movie: app.screen = "full" self.body_canvas = Canvas(redraw_callback=self.handle_redraw) app.body = self.body_canvas self.img = graphics.Image.new(self.body_canvas.size) for frame in movie: self.img.clear(0x000000) snap = graphics.Image.open(frame) snap = snap.resize(self.body_canvas.size) self.img.blit(snap) self.handle_redraw(()) e32.ao_yield() note(u"Video ended.","info") app.screen = "normal" app.body = self.body_text self.img = None self.body_canvas = None else: self.body_text.add(u"No files found." + self.NL) else: self.body_text.add(u"Stop the recording first." + self.NL)
def AskUser(self, path=None, path_item=None, type="file", exts=[]): self.type = type.lower() self.exts = map(str.lower, exts) if self.type not in ("file", "folder"): self.type = "file" ui.app.screen = "normal" ui.app.exit_key_handler = self.exit e32.ao_yield() ui.app.menu = [ (u"Select", self.ret), (u"Open", self.rightArrow), (u"Back", self.leftArrow), (u"Edit Filter", ((u"Filter", lambda: self.editFilter("f")), (u"Show All", self.editFilter))), (u"Quit", self.exit), ] ui.app.title = u"Choose " + self.type e32.ao_yield() self._run(path, path_item) ui.app.title = self.old_title ui.app.body = self.old_body ui.app.menu = self.old_menu ui.app.exit_key_handler = self.old_exit ui.app.screen = self.old_screen ui.app.focus = None if self.CH: return self.cur else: return None
def open_offline(self, filename): stall() e32.ao_yield() import pychmlib try: chm_file = pychmlib.chm.chm(filename) except: appuifw.note(ERR_READING, "error") self.refresh() return try: hhc_file = chm_file.get_hhc() if hhc_file: import hhc hhc_obj = hhc.parse(hhc_file.get_content()) viewer = HHCViewer(filename, hhc_obj, chm_file.encoding) viewer.set_as_offline(chm_file) viewer.show() self.quit() else: appuifw.note(ERR_NO_HHC, "error") self.refresh() return finally: chm_file.close()
def AsyncLoad(self): lastprecent = 0 nowprecent = itnet.loadingPrecent while (1): nowprecent = itnet.loadingPrecent if (lastprecent == nowprecent and lastprecent < 100 and nowprecent < 100): sleep(0.1) e32.ao_yield() continue itnet.resizePic(itnet.nowUrl[0], itnet.nowUrl[1]) self.drawAsyncLoad(nowprecent) if (nowprecent >= 100): self.loading = 0 self.RunningForm = self.allForm.main self.lastRunningForm = self.RunningForm self.lastX = self.selectedIndex - 1 self.redraw() self.slideChangeThread.after(3, self.slideChange) break lastprecent = nowprecent sleep(0.1) e32.ao_yield()
def main(self, game_obj): self.game_obj = game_obj # Run the game initializer and # pass in a reference to to the game world here. game_obj.initialize(self) # Start the game loop assert hasattr(game_obj, 'run'), "Game object needs a run method." if not self.is_running: self.is_running = 1 if not hasattr(game_obj, 'handle_timers'): game_obj.handle_timers = 0 handle_timers = game_obj.handle_timers run_fn = game_obj.run while self.is_running: ao_yield() run_fn() if handle_timers: continue else: ao_sleep(self.fps) # Run any termination/cleanup sequence here if any. if hasattr(game_obj, 'terminate'): game_obj.terminate()
def compress(): global run ( obw, per, run, ) = (len(sp), 0, 0) z = zipfile.ZipFile((zdir + name), 'w', com) if (aktiv[1] == 'srz'): try: z.write('e:/system/apps/zippy/info.txt', 'info/info.txt') except: None img.rectangle((20, 120, 156, 140), 7829488, width=20) img.text((50, 122), ru('Ar\xc5\x9fivleniyor . . .'), font=u'apl') while (obw > per): img.rectangle((18, 132, (18 + ((140 * per) / obw)), 137), 255, width=10) try: if (aktiv[1] == 'zip'): z.write(sp[per], usp[per]) elif (sdir == ''): z.write(sp[per], (sp[per][0] + sp[per][2:])) else: z.write(sp[per], (sdir + sp[per][2:])) per += 1 except: per += 1 redraw(()) e32.ao_yield() z.close() run = 1 main()
def restoreFolder(self, folder, data, txt): items = os.listdir(folder) for item in items: e32.ao_yield() if self.abort: return False path = folder + "\\" + item if os.path.isdir(path): if not self.restoreFolder(path, data, txt): return False elif os.path.isfile(path): filesize = os.path.getsize(path) path2 = path[len(self.backupdir) + 1:] path2 = path2[0] + ":" + path2[1:] txt.add(unicode(path2 + "\n")) if not self.copyfile(path, path2): txt.add(self.S_ERROR_FAILED_TO_COPY_FILE % (unicode(path), unicode(path2))) return False if not self.delfile(path): txt.add(self.S_ERROR_FAILED_TO_DELETE_FILE % (unicode(path))) return False data[0] += 1 data[1] += filesize return True
def rank(): canvas.bind(EKeySelect, lambda: None) img = graphics.Image.new(canvas.size) appuifw.app.exit_key_handler = menu try: db = e32dbm.open("e:\\System\\Apps\\Puzzle\\picrank.e32dbm", "r") tdb = db.items() db.close() except: appuifw.note(chn("暂无排行"), "error") for i in range(len(tdb) - 1): for j in range(len(tdb) - i - 1): if int(tdb[j][1]) > int(tdb[j + 1][1]): t = tdb[j] tdb[j] = tdb[j + 1] tdb[j + 1] = t while 1: img.clear(0) for i in range(30, 1, -1): img.ellipse((105 - 5 * i / 2, 15 - i / 3, 105 + 3 * i / 2, 15 + i), fill=(0, 265 - 8 * i, 265 - 8 * i)) img.text((70, 30), chn("排行榜"), 0x0000ff, font=ziti) for i in range(8): img.text((30, 55 + i * 20), chn(tdb[i][0]), 0x00ff00, font=ziti) img.text((100, 55 + i * 20), chn(": " + tdb[i][1]), 0xff0000, font=ziti) canvas.blit(img) e32.ao_sleep(0.2) e32.ao_yield()
def run(params): filename = params[1] appuifw.app.title = unicode(os.path.split(filename)[1]) ext = os.path.splitext(filename)[1].lower() if ext in PYTHON_EXTS: source_path = os.path.splitdrive(filename)[1].lower() # It's safe to exit if we have been started from the Messaging # app, but not if we have been started from e.g. the web # browser, since then the whole browser would exit. The # default is to not exit the app, since that's safer. should_exit = source_path.startswith('\\system\\mail') if ext in PYTHON_LIB_EXTS: actions = [lambda: lib_install(filename)] menu = [u"Python lib module"] else: actions = [ lambda: script_install(filename), lambda: standalone_install(filename), lambda: lib_install(filename) ] menu = [u"Python script", u"py2app", u"Python lib module"] index = appuifw.popup_menu(menu, u"Install as") try: if not index == None: appuifw.app.exit_key_handler = exit_wait e32.ao_yield() actions[index]() appuifw.note(u"Installation complete", "info") finally: appuifw.app.exit_key_handler = None if should_exit: appuifw.app.set_exit()
def backup(): qu=ui.popup_menu([u'Phone', u'Memory Card'], u'Select Location') loc=['c:\\', 'e:\\'] try: dir=loc[qu]+'ADIKStools\\mySMSbackup\\'+time.strftime('%Y%m%d')+'\\' except: return if not os.path.exists(dir): os.makedirs(dir) ui.note(u'Folder Successfully Created', 'conf') n=dir+time.strftime('%H.%M.%S')+'.txt' gui.global_note(u'backing up\nplease wait', 'info') fl=open(n, 'a') fl.write(u'ADIKSonline SMS Backup\n\n%s\n' %q) b=t.sms_messages() if len(b)==0: ui.note(u'you have no message in your inbox'.upper()) fl.write(u'No message in Inbox ! ! !\n\n%s\n' %u) fl.close() return y=0 for i in b: try: fl.write(u'MESSAGE ID: %d\nSENDER: %s\nTIME: %s\nCONTENTS: %s\n\n%s\n\n' %(i, str(t.address(i)), time.ctime(t.time(i)), t.content(i), u)) e32.ao_yield() except: y+=1 gui.global_note(u'an error occured', 'error') fl.write(u'get more, contact:\[email protected]\n+2347035536245') fl.close() gui.global_note(str(len(b)-y)+u' successful'+u'\n'+str(y)+u' errors', 'confirm') e32.ao_sleep(1.5) if len(b)-y and msgquery.infopopup(u'View Backup Now?', u'View Backup', msgquery.OKRBack): view(n)
def switch_in(self): appuifw.app.body = self.canvas appuifw.app.menu = [(u"Save Image", self.save_picture)] appuifw.app.title = u'Image' self.screen_picture = camera.take_photo(size=(640, 480)) self.running = 1 while self.running: if self.save_picture_flag: self.running = 0 try: self.screen_picture = camera.take_photo(size=(1280, 960)) self.filename = self.filename_prefix + str(int( time.time())) + u'.jpg' self.screen_picture.save(self.filename) appuifw.note(u"Picture saved to " + self.filename, "conf") except: pass else: try: self.screen_picture = camera.take_photo(size=(640, 480)) except: pass self.handle_redraw(()) e32.ao_yield() self.handle_redraw(())
def pt(i, ii=True): A.app.title = i if ii: A.app.title = i try: A.app.body.focus = True except: pass e32.ao_yield()
def run(self): while self.running: if not self.timerRunning: log.write('calling timer') self.timer.after(30, self.timerCallback) self.timerRunning = 1 e32.ao_yield() self.lock.signal()
def writeProg(n,s,t): global writeprogress pc = n*s*100/t if pc > 100:pc=100 if pc != writeprogress: infoPopup.show(cn('○ ') + u'%s %%' % pc,(0,0), 1000,0, appuifw_.EHCenterVTop) writeprogress = pc e32.ao_yield()
def start(self): app.screen = 'full' self._oldScreen = app.body app.body = self() ao_yield() self._image = Image.new(self._screen.size) self.width = self._screen.size[0] self.height = self._screen.size[1] self.redraw()
def fx(self, img, x, y, save_img): import appuifw, e32, graphics img2 = graphics.Image.new((x, y)) img0 = img.resize((x, y)) for i in range(y): for j in range(x): t = img.getpixel((j, i))[0] img2.point((x - j, i), t, width=1) e32.ao_yield() img2.save(save_img)
def __init__(self, servport = NETBIOS_NS_PORT, apn=None): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if not apn: apn = socket.select_access_point() e32.ao_yield() if not apn: raise NetBIOSError, 'Please select a AP' ap = socket.access_point(apn) socket.set_default_access_point(ap) ap.start()
def get_request(self): while self.run: try: e32.ao_yield() sock, addr = self.socket.accept() sock.settimeout(None) return (sock, addr) except socket.timeout: if not self.run: self.socket.close() raise socket.error
def rank(): #新建图形 img = graphics.Image.new(canvas.size) #退出键 appuifw.app.exit_key_handler = quit #异常处理,这个算是高级的内容了#try...except...#可能出错的代码放到try 语句块里,如果出错了要执行的操作放到except 里#这样你的代码就健壮了很多 try: #关键函数,e32dbm.open 打开数据库 #前面是路径,后面的是打开方式’r’ 意思为只读模式打开(只能读取数据库信息)#还有其他模式’w’(打开已存在的数据库,读写模式)#’c’(打开已存在的,读写模式,如果不存在新建一个)#’n’ 新建一个空数据库,读写模式 db = e32dbm.open('c:\\rank.e32dbm', 'c') #初始化数据库,具体游戏中不可能放在这里的#但是不初始化没数据的,这里主要是为了演示,所以给出初始化#数据库记录信息是以字典的形式存放的,这里有点难了#如果不能理解也没什么,不过字典必须会用的,不然就做不了什么了#下面就是基本的字典操作添加了 db['player1'] = str(10000) db['player2'] = str(10000) db['player3'] = str(10000) db['player4'] = str(10000) db['player5'] = str(10000) db['player6'] = str(10000) db['player7'] = str(10000) db['player8'] = str(10000) db.close() db = e32dbm.open('c:\\rank.e32dbm', 'r') #用一个变量记录db.items()获得的字典 tdb = db.items() #关闭数据库,这里和文件打开操作一样都要关闭的 db.close() except: #如果没有数据库信息给出错误提示 appuifw.note(chn('error'), 'error') #好了,记录取出来了,怎么显示呢?既然是排行榜当然要排序了#需要说明的是字典是无序的,所以要排序#下面使用冒泡排序,具体原理不做解释,超过范围了。有兴趣的话,可以查看其他参考书 for i in range(len(tdb) - 1): #len(tdb)获得字典长度也就是有几个玩家 for j in range( len(tdb) - i - 1 ): #我倒。。讲到这感觉有点难了,不适合初学者了#尽量说明白吧,给个tdb的例子如{'xiaowang':'100','xiaozhang':'200'}#这里很明显第一项是关键字也就是玩家姓名,第二项是分数但是是字符串#tdb[0][1]=?明显是'100'#int()转换成数字再排序 #下面是冒泡内容,不细讲 if int(tdb[j][1]) > int(tdb[j + 1][1]): t = tdb[j] tdb[j] = tdb[j + 1] tdb[j + 1] = t #又见while死循环,排行榜该显示了 while running: #清屏 img.clear(0) #给点文字说明 img.text((70, 30), chn('排行榜'), 0x0000ff) e32.ao_sleep(1) #唉。。屏幕小酒显示8个玩家吧 for i in range(8): #tdb[i][0]刚才说了,这个就是玩家姓名了,不明白那就是对数组的下标没学好 img.text((30, 55 + i * 20), chn(tdb[i][0]), 0x00ff00) #tdb[i][1]分数喽 img.text((100, 55 + i * 20), chn(': ' + tdb[i][1]), 0xff0000) #画到屏幕吧 canvas.blit(img) e32.ao_yield()
def window(): i = s.index m = ('янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек') t = s.list[i][0] s.info.start(s.list[i][1].decode("utf-8"), lambda: s.stopinfo(1), s.delete_copy, s.stopinfo, s.startinfo) aw.app.title = u'[%d/%d] %s %s\n%s : %s : %s' % (i + 1, len( s.list), t[6:8], m[int(t[4:6]) - 1], t[8:10], t[10:12], t[12:14]) e32.ao_yield()
def play(): global pos_x, pos_y, step generate_Maze() paintMaze() while running: imgtext.clear(0xaaaaaa) img.point((pos_x * 8 + 8, pos_y * 8 + 8), 0x00ff00, width=6) imgtext.text((5, 10), chn(str(step)), 0xff0000) img.blit(imgtext, target=(80, 250)) canvas.blit(img) e32.ao_yield()
def see_pic(): global pic, issee issee = 1 appuifw.app.exit_key_handler = play see_img = graphics.Image.new(canvas.size) while 1: see_img.clear(0) see_img.blit(pic, target=(5, 10)) see_img.text((20, 190), chn("右软键返回游戏"), 0x00ff00, font=ziti) canvas.blit(see_img) e32.ao_yield()
def menu_init(): ''' Go to startup state ''' appuifw.app.title = u"View MBM" appuifw.app.exit_key_handler=cb_quit appuifw.app.menu = [ (u"View", cb_select), (u"About", menu_about), (u"Exit", cb_quit) ] appuifw.app.body = lb e32.ao_yield()
def __drawNote2(s,title,X,height,i,textL,maskColor,textColor): s.__img.blit(s.__imgOld) s.__mask.clear(0) s.__mask.polygon(s.rim((X,i,s.screenSize[0]-X,i+height)),fill=maskColor) s.__img.blit(s.__imgBlack,mask=s.__mask) s.__img.text((s.screenSize[0]/2-s.__img.measure_text(title,("dense",22))[0][2]/2.0,i+25),title,textColor,("dense",22,FONT_BOLD|FONT_ANTIALIAS)) s.__img.line((X+2,i+30,s.screenSize[0]-X-2,i+30),maskColor,width=2) for j in range(len(textL)): s.__img.text((X+5,i+53+j*25),textL[j],textColor,("dense",18)) s.__redraw() e32.ao_yield()
def Update(self): positioning.select_module(positioning.default_module()) positioning.set_requestors([{"type":"service", "format":"application", "data":"GpsLocProvider"}]) # open log file if(self.logmode): self.FILE = open(self.logpath, "w+") self.FILE.write("LOGFILE START:\r") self.FILE.write("GPS Modules detected:\r") self.FILE.write(str(positioning.modules())) self.FILE.write("Using default: " + str(positioning.default_module()) + "\r") global keep_scanning while keep_scanning: # get current location, compare to old current location newLoc = self.getCurrentLocation() if newLoc['lat'] != newLoc['lat']: # if we got a "NaN" response from positioning, this will abort and try again continue # if no(or little) change, don't do anything #latDif = math.fabs(newLoc["lat"] - self.current_location["lat"]) #lngDif = math.fabs(newLoc["lng"] - self.current_location["lng"]) # if latDif < 0.0001 or lngDif < .001: # print "Haven't moved far enough. Cancelling update." #self.current_location = newLoc #self.nearbyLock.signal() self.addPOIs(self.get_nearby_locations(self.current_location["lat"], self.current_location["lng"])) self.actives = self.get_active_list() if len(self.actives) != 0: self.newActives = 1 else: self.newActives = 0 # for poi in actives: # self.GUI.location_cache.appendLocation(poi) # self.GUI.notifyOfNewLocation(poi["name"]) # print "Update in :" + str(time.clock() - initialTime) + " ms." if self.logmode: self.FILE.flush() e32.ao_yield() e32.ao_sleep(5) if self.logmode: self.FILE.write("Total GPS scans performed: " + str(self.total_scans) + "\r") self.FILE.write("Avg time per scan: " + str(self.total_scan_time / self.total_scans) + "\r") self.FILE.close() print "Update thread done."
def progress(self, p): self.win.remove_image(self.top) self.vis() x = (159 - 11) * p / 100 + 11 self.top.rectangle((11, 16, x + 2, 20), fill=0x9999ff) self.top.rectangle((11, 20, x + 2, 34), fill=0x2222dd) self.win.add_image(self.top, (0, 0)) e32.ao_yield() if p > 98: self.win.hide() self.t = 0 return 0
def ton(): f = open(p, 'wb') f.write('.snd' + struct.pack('>5L', 16, 8 * duration, 2, 8000, 1)) for i in range(duration * 8): sin_i = math.sin(i * 2 * math.pi * frequency / 8000) f.write(struct.pack('b', volume * 127 * sin_i)) f.close() s = audio.Sound.open(p) s.play() while s.state() == 2: e32.ao_yield() s.close() os.remove(p)
def __execute(self, list, cur): self.type = self.type self.lb.set_list(list, cur) e32.ao_yield() ui.app.body = self.lb self.lb.bind(63495, self.leftArrow) self.lb.bind(63496, self.rightArrow) self.lb.bind(42, lambda: self.scroll("u")) self.lb.bind(35, self.scroll) try: self.lock.wait() except: pass
def rank(): global in_rank in_menu = 0 canvas.bind(EKeySelect, lambda: None) canvas.bind(EKeyUpArrow, lambda: None) canvas.bind(EKeyDownArrow, lambda: None) canvas.bind(53, lambda: None) canvas.bind(52, lambda: None) canvas.bind(54, lambda: None) canvas.bind(56, lambda: None) canvas.bind(50, lambda: None) canvas.bind(42, lambda: None) canvas.bind(35, lambda: None) rank_img = graphics.Image.new(canvas.size) appuifw.app.exit_key_handler = menu try: db = e32dbm.open("e:\\System\\Apps\\lllook\\llkrank.e32dbm", "r") tdb = db.items() db.close() except: try: db = e32dbm.open("c:\\System\\Apps\\lllook\\llkrank.e32dbm", "r") tdb = db.items() db.close() except: appuifw.note(chn("fail to open rank"), "error") for i in range(len(tdb) - 1): for j in range(len(tdb) - i - 1): if int(tdb[j][1]) > int(tdb[j + 1][1]): t = tdb[j] tdb[j] = tdb[j + 1] tdb[j + 1] = t while in_rank: rank_img.clear(0xffffff) rank_img.text((50, 30), chn('玩家排行榜'), 0xff0000, font=ziti) for i in range(11): rank_img.line((0, i * 20 + 40, 176, i * 20 + 40), 0x0000ff) rank_img.line((90, 40, 90, 200), 0x0000ff) for i in range(8): rank_img.text((30, 55 + i * 20), chn(tdb[i][0]), 0x00ff00, font=ziti) rank_img.text((100, 55 + i * 20), chn(tdb[i][1]), 0xff0000, font=ziti) rank_img.rectangle((0, 0, 176, 208), 0x0000ff) canvas.blit(rank_img) e32.ao_sleep(0.2) e32.ao_yield()
def hide(): # appuifw.app.body.set(u"") global __splash, __img if __img: del __img __img = None if __splash: appuifw.app.body = __appbody del __splash __splash = None e32.reset_inactivity() e32.ao_yield()
def main(): if(closing!=1 & logging == 1): #read the current data: data = bt.readposition() if(data != None): #get the timestamp: # the microseconds keep returning 0 on the phone # microseconds = str(time.time()).split('.')[1] # timeStamp = time.strftime("%a, %d %b %Y %H:%M:%S") +'.' + microseconds # getTime returns: 1226521341.98437 # we only want the three most significant digits of the decimal timeSeconds = getTime() timeStamp = time.strftime(u"%d/%b/%Y %H:%M:%S",time.gmtime(timeSeconds)) microsecond = str(timeSeconds).split('.')[1] timeStamp += u'.' + ljust(microsecond,3,'0') #padding/trimming the microsecond time # there is still weirdness in the time...time() and clock() are not in sync # global lastTime # currentTime = getTime() # millisDelta = (currentTime - lastTime)%1000 # lastTime = currentTime # # timeStamp += u'.'+ str(millisDelta) #format the output string: #split the incoming data into an array and then format for CSV global delimiter fields = data.strip().split(delimiter) output = u",".join(fields) out = u'\"' + timeStamp + u'\"' + u',' + output + u'\n' #print to the screen: global connectionDescription log_panel.set(connectionDescription + u'\n\r' + out) # log_panel.add(out) # write the data to the file file.write(out) # yield needs to be here e.g. in order that key pressings can be noticed e32.ao_yield() #delay then repeat: #e32.ao_sleep(0.25, main) #recursively call the main loop #timer.after(0.25, main) timer.after(0.1, main)
def main(): appuifw.app.exit_key_handler = set_exit appuifw.app.screen = 'full' #定义界面 canvas = glcanvas.GLCanvas(redraw_callback=display, event_callback=keys, resize_callback=reshape) appuifw.app.body = canvas #调用初始化 myinit() #开始绘制 while running: canvas.drawNow() e32.ao_yield()
def show(msg="Loading..."): # appuifw.app.body.set(u"Loading...") global __splash, __img, __msg __msg = unicode(msg) if not __splash: __splash = appuifw.Canvas(__draw) r = min(__splash.size[0],__splash.size[1])*2/3 try: img = graphics.Image.open(IMGFILE) except: img = graphics.Image.new((r,r)); img.clear(0) __img = img.resize((r,r), keepaspect=True) appuifw.app.body = __splash del img __draw() e32.reset_inactivity() e32.ao_yield()
def refresh(self, var): try: if var: ind = self.lb.current() obj = self.all[ind][0] base = os.path.basename(obj) path = os.path.dirname(obj) if path.endswith("\\"): path = path[:-1] if obj.endswith(":"): path, base = "None", obj e32.ao_yield() return self._run(path, base) except: return 1
def draw(): global velocity,running; running=not(running) while running: for i in range(3): while color[i] != ( 255*(1+(velocity/abs(velocity)))/2 ): e32.ao_yield() if running==0: return color[i]=limit(color[i]+velocity) rect(color) while paused: e32.ao_sleep(0.1) e32.ao_yield() if running==0: return velocity=-velocity
def load_offline(self, local): stall(u"Please wait while page is extracted from the archive...") e32.ao_yield() ui = self.chm_file.resolve_object("/"+local) try: if ui: content = ui.get_content() else: content = ERROR_TEMPLATE % "Page cannot be found" except: content = ERROR_TEMPLATE % "Page could not be displayed" try: self.open_local_html(LOCAL_FILE, content) self.refresh() except: self.refresh()
def __init__(self): self.LIBPATH = LIBPATH self.lock = e32.Ao_lock() self.drive_icon = ui.Icon(self.LIBPATH + u"myicons.mbm", 0, 1) self.folder_icon = ui.Icon(self.LIBPATH + u"myicons.mbm", 2, 3) self.wait_icon = ui.Icon(self.LIBPATH + u"myicons.mbm", 6, 7) self.empty_icon = ui.Icon(self.LIBPATH + u"myicons.mbm", 8, 9) self.file_icon = ui.Icon(self.LIBPATH + u"myicons.mbm", 36, 37) e32.ao_yield() entry = [(u"C:", self.drive_icon)] self.lb = ui.Listbox(entry, self.ret) self.old_body = ui.app.body self.old_menu = ui.app.menu self.old_exit = ui.app.exit_key_handler self.old_screen = ui.app.screen self.old_title = ui.app.title self.CH = -1
def piano(): global volume filename = "E:\\Musician\\keyboard%3d.raw" % width img.load(filename ,callback=handle_redraw) appuifw.note(u"You can use up-down to change the volume", "info") handle_redraw(()) delay=0.1 # delay means that loop doesn't burn round so fast that nothing works timer.after(delay) S = None lastfilename = None def open_midi(filename): if filename != lastfilename: if S: S.close() new_S = audio.Sound.open(filename) if (volume != -1): new_S.set_volume(volume) return new_S return S # Load an arbitrary midi file to load the volume global value S = open_midi(keycode2filename.values()[0]) volume = S.current_volume() while 1: if(keyboard.get_last_key() and keycode2filename.has_key(keyboard.get_last_key())): filename = keycode2filename[keyboard.get_last_key()] keyboard.clear_last_key() S.stop() S = open_midi(filename) lastfilename = filename S.play(1,0) elif keyboard.pressed(EScancodeLeftSoftkey): #want to exit piano S.stop() break elif keyboard.pressed(EScancodeDownArrow) : # Decrease volume set_volume(S, -1) elif keyboard.pressed(EScancodeUpArrow): # Increase volume set_volume(S, 1) e32.ao_yield() timer.after(delay)
def tick(self): """Begin a new frame. May sleep until signaled, if we haven't already been signaled. """ e32.ao_yield() while not self._signaled: self._prevTime = None self._lock.wait() self._signaled = False now = time.clock() if self._prevTime is None: self._prevTime = now self.dt = 0.0 else: self.dt = now - self._prevTime self._prevTime = now self.ticks += 1
def draw3(): global velocity,running,to_white running=not(running) while running: for i in range(3): while color[i] != (255*(1+(velocity/abs(velocity)))/2): color[i]=limit(color[i]+velocity) e32.ao_yield() if running==0: return rect(color) while paused: e32.ao_sleep(0.1) e32.ao_yield() if running==0: return if color==[255,255,255]: to_white=0 velocity=-velocity if to_white==1: velocity=abs(velocity)
def run(self): Dialog.refresh(self) try: camera.start_finder(self.redraw) except: note(LABELS.loc.pt_err_cant_start_viewf,"error") return None while (not self.taken) and (not self.cancel): e32.ao_yield() try: camera.stop_finder() camera.release() except: note(LABELS.loc.pt_err_cant_stop_viewf,"error") return self.filename
def cb_select(self): ''' Callback for listbox item selection event ''' ### keypress handler trick, to allow Enter/Select work # fact is: you press the Enter key shortly and this is what happens: # callback called once immediately and once again after ~ 0.04 s # when you press the button for a longer period this is what happens: # callback called once immediately and once again after ~ 0.04 s then after ~ 0.56 s it is called every 0.15 s #self.timer.cancel() # Ignore first (button down) and non-timer triggered (button up) events if (not self.time): # or (time.clock() - self.time < KEY_REPEATE_RATE * .7): self.time = time.clock() # Should be more than start keyrepeat rate #self.timer.after(KEY_START_REPEATE_RATE * 1.25, self.cb_select) return if time.clock() - self.time > KEY_INITIAL_UP_TIME * 2: self.time = 0 return self.time = 0 ### keypress handler trick, done # Current listbox selection index = self.list_box.current() # Change selected item icon: on <-> off if self.e[index][1] == self.icon_on: new_icon = self.icon_off power_socket_on = False else: new_icon = self.icon_on power_socket_on = True self.netio.setPowerSocketPower(index+1,power_socket_on) self.power_sockets[index] = power_socket_on self.e[index] = (self.e[index][0], new_icon) # Show new list, same item selected self.list_box.set_list(self.e, index) appuifw.app.body = self.list_box # Make it visible e32.ao_yield()
def write(self, s, **kwargs): if kwargs: for item in DEFAULT_STYLE: if not item in kwargs: kwargs[item] = DEFAULT_STYLE[item] prompt.toEnd() text.color = kwargs['color'] text.highlight_color = kwargs['highlight_color'] text.style = ((kwargs['highlight_color'] != DEFAULT_STYLE['highlight_color']) * appuifw.HIGHLIGHT_STANDARD | kwargs['bold'] * appuifw.STYLE_BOLD) prompt.add(s) text.color = DEFAULT_STYLE['color'] text.highlight_color = DEFAULT_STYLE['highlight_color'] text.style = DEFAULT_STYLE['style'] else: if DO_CURSOR_REFRESH_FOR_SIMPLE_PRINT: prompt.toEnd() prompt.add(s) if inputHandler.waitForInput: sys.stdout.hasWritten = True elif kwargs or (not kwargs and DO_INPUT_REFRESH_FOR_SIMPLE_PRINT): e32.ao_yield()
def loop(self): import key_codes import e32 start_time = time.time() while self.running: if self.keyboard.pressed(key_codes.EScancodeLeftArrow): self.remote.left() elif self.keyboard.pressed(key_codes.EScancodeRightArrow): self.remote.right() elif self.keyboard.pressed(key_codes.EScancodeDownArrow): self.remote.down() elif self.keyboard.pressed(key_codes.EScancodeUpArrow): self.remote.up() elif self.keyboard.pressed(key_codes.EScancodeSelect): self.remote.select() elif self.keyboard.pressed(key_codes.EStdKeyBackspace): self.remote.back() elif self.keyboard.pressed(key_codes.EKey7): self.remote.volumeDown() elif self.keyboard.pressed(key_codes.EKey8): self.remote.volumeMute() elif self.keyboard.pressed(key_codes.EKey9): self.remote.volumeUp() elif self.keyboard.pressed(key_codes.EKey0): self.quit() if not self.remote.connected: self.quit() print "connection closed" e32.ao_yield() if not start_time + 2000 < time.time(): if appuifw.query(u"Do you want to reset the preferences?","query") == True: self.clear_preferences() self.quit()
def show_splash(self,filename, timeout = 0): img = Image.open(filename) old_screen = app.screen old_body = app.body app.screen = 'full' if timeout == 0: app.body = Canvas(event_callback=self.handle_keyboard_splash) else: app.body = Canvas() app.body.clear(0) app.body.blit(img) e32.ao_yield() if timeout == 0: self.app_lock.wait() else: self.timer.after(timeout) app.screen = old_screen app.body = old_body
def read(): encods=['u8','u16','ascii','cp1251','iso8859','base64','hex'] pat=filebrowser.select('Open file') if pat!=None: global e for e in encods: try: fil=open(pat,"r") w=dialog.Wait(u'Decoding file using %s...'%e) w.show() e32.ao_sleep(1) if pat.endswith(u'.doc'): try: tet=fil.read() t.set(tet[tet.find('\x02\x00\x0c\x01'+'\x00'*74)+78:tet.find('\x0d'+'\x00'*191)].decode(e)) globalui.global_note(u'File loaded','confirm') break except: if e!=encods[len(encods)-1]: continue else: globalui.global_note(u'Unable to decode file','error') else: try: t.set(fil.read().decode(e)) globalui.global_note(u'File loaded','confirm') break except: if e!=encods[len(encods)-1]: continue else: globalui.global_note(u'Unable to decode file','error') w.hide() except: globalui.global_note(u'Unable to open file','error') e32.ao_yield() else: return None
def run(self, params): filename = params[1] appuifw.app.title = unicode(os.path.split(filename)[1]) ext = os.path.splitext(filename)[1].lower() if ext in self.PYTHON_EXTS: source_path = os.path.splitdrive(filename)[1].lower() # It's safe to exit if we have been started from the Messaging # app, but not if we have been started from e.g. the web # browser, since then the whole browser would exit. The # default is to not exit the app, since that's safer. should_exit=source_path.startswith('\\system\\mail') if ext in self.PYTHON_LIB_EXTS: actions = [lambda: self.lib_install(filename)] self.menu = [u"Lib module"] self.menu1 = [u"Lib"] elif ext in self.PYTHON_EXTS: actions = [lambda: self.execfile1(filename), lambda: self.standalone_install(filename), lambda: self.script_install(filename), lambda: self.lib_install(filename)] self.menu = [u"Run now", u"Application", u"Script", u"Lib module"] self.menu1 = [u"Run", u"App", u"Script", u"Lib"] self.index = appuifw.popup_menu(self.menu, u"Install as") try: if not self.index == None: appuifw.app.exit_key_handler = self.exit_wait e32.ao_yield() actions[self.index]() self.note_once(0,2) else: self.noted=1 finally: appuifw.app.exit_key_handler = None if should_exit: appuifw.app.set_exit()