def send_move(self, move, player_name, player_color): evt = events.PlayerInputEvent() evt.move = move evt.player_name = player_name evt.player_color = player_color pubsub.publish('PLAYER_INPUT', evt)
def __init__(self, parent, pos): global widgets_list pb_editor.DirtyUIBase.__init__(self, parent) self.static_box=wx.StaticBox(self, -1, "Category") hs=wx.StaticBoxSizer(self.static_box, wx.HORIZONTAL) self.categories=[] self.category=wx.ListBox(self, -1, choices=self.categories) pubsub.subscribe(self.OnUpdateCategories, pubsub.ALL_CATEGORIES) pubsub.publish(pubsub.REQUEST_CATEGORIES) vbs=wx.BoxSizer(wx.VERTICAL) vbs.Add(wx.StaticText(self, -1, 'Master Category'), 0, wx.TOP|wx.LEFT, 5) vbs.Add(self.category, 1, wx.EXPAND|wx.ALL, 5) hs.Add(vbs, 1, wx.EXPAND|wx.ALL, 5) vbs=wx.BoxSizer(wx.VERTICAL) self.but=wx.Button(self, wx.NewId(), "Manage Categories:") add_btn=wx.Button(self, -1, 'Add ->') del_btn=wx.Button(self, -1, '<- Remove') vbs.Add(self.but, 0, wx.ALIGN_CENTRE|wx.ALL, 5) vbs.Add(add_btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5) vbs.Add(del_btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5) hs.Add(vbs, 0, wx.ALIGN_CENTRE|wx.ALL, 5) wx.EVT_BUTTON(self, add_btn.GetId(), self.OnAddCategory) wx.EVT_BUTTON(self, del_btn.GetId(), self.OnDelCategory) vbs=wx.BoxSizer(wx.VERTICAL) vbs.Add(wx.StaticText(self, -1, 'Selected Category:'), 0, wx.TOP|wx.LEFT, 5) self._my_category=wx.ListBox(self, -1) vbs.Add(self._my_category, 1, wx.EXPAND|wx.ALL, 5) hs.Add(vbs, 1, wx.EXPAND|wx.ALL, 5) wx.EVT_BUTTON(self, self.but.GetId(), self.OnManageCategories) self.SetSizer(hs) hs.Fit(self)
def do_load_base64(self, line): """ load filename=(file) load base64=(base64 encoded) """ cookie = self.cookie executor = self.bot._executor def source_good(): self.print_response(status=RESPONSE_CODE_OK, cookie=cookie) executor.clear_callbacks() def source_bad(tb): if called_good: # good and bad callbacks shouldn't both be called raise ValueError('Good AND Bad callbacks called !') # TODO - get simple_trace_back of exception to send back self.print_response(status=RESPONSE_REVERTED, keep=True, cookie=cookie) self.print_response(tb.replace('\n', '\\n'), cookie=cookie) executor.clear_callbacks() called_good = False source = str(base64.b64decode(line)) # Test compile pubsub.publish("shoebot", SOURCE_CHANGED_EVENT) executor.load_edited_source(source, good_cb=source_good, bad_cb=source_bad)
def get_chart(self, _id): """Get or create the chart containing the plot identified as <_id>.""" chart = self.find_chart(_id) #print(chart) if not chart: # determine if we need to construct a new chart single_chart_exists = bool(self.charts) if single_chart_exists: chart = self.charts[0] else: chart = self.add_chart() # we don't have a buffer for this id, so construct one plot = chart.add_plot(_id, App.COLORS[self.next_color]) #plot.label = 'nT ' #print('plot.label') self.next_color += 1 self.next_color %= len(App.COLORS) if not single_chart_exists: self.set_scaling(chart) _dict = self.cfg.scale_settings mode = self.scaling.mode pubsub.publish('scale_mode', mode, False) self.scale_mode.set(mode) self.set_scaling(chart) #else: return chart
def on_smoothing(self, data): """The smoothing slider has changed.""" data = int(data) self.cfg.smoothing = data pubsub.publish('smoothing', data) if not self.running: self.update_charts()
def playback_from_file(file_name): "start a playback session from the specified file" global DR_Play, _the_player if DR_Play and _the_player: _the_player.stop() _player = DR_Read_File(file_name) _player.start() pubsub.publish(pubsub.DR_PLAY, data=_player)
def playback_from_file(file_name): "start a playback session from the specified file" global DR_Play, _the_player if DR_Play and _the_player: _the_player.stop() _player=DR_Read_File(file_name) _player.start() pubsub.publish(pubsub.DR_PLAY, data=_player)
def stop(): "stop a recording and/or playback session" global DR_Play, DR_On, _the_recorder, _the_player if DR_On and _the_recorder: _the_recorder.stop() if DR_Play and _the_player: _the_player.stop() pubsub.publish(pubsub.DR_STOP)
def publish_event(event_t, data=None, extra_channels=None, wait=None): event = Event(event_t, data) pubsub.publish("shoebot", event) for channel_name in extra_channels or []: pubsub.publish(channel_name, event) if wait is not None: channel = pubsub.subscribe(wait) channel.listen(wait)
def test_unsubscribe(self): sub = pubsub.subscribe('test') pubsub.publish('test', 'hello world 1') sub.unsubscribe() pubsub.publish('test', 'hello world 2') msgs = list(sub.listen(block=False)) self.assertEqual(len(msgs), 1) self.assertEqual(msgs[0]['data'], 'hello world 1')
def record_to_file(file_name, append=False): "start a data recording session into the specified file" global DR_On, _the_recorder if DR_On and _the_recorder: _the_recorder.stop() _rec=DR_Rec_File(file_name, append) _rec.start() pubsub.publish(pubsub.DR_RECORD, data=_rec)
def record_to_file(file_name, append=False): "start a data recording session into the specified file" global DR_On, _the_recorder if DR_On and _the_recorder: _the_recorder.stop() _rec = DR_Rec_File(file_name, append) _rec.start() pubsub.publish(pubsub.DR_RECORD, data=_rec)
def timerAction(): global old_kbd kbd = tm.keys() if kbd[0] > 0: if kbd[0] != old_kbd: # print("ps_tm: ",str(kbd)) pubsub.publish('tm_button', kbd[0]) old_kbd = kbd[0]
def handle_accept(self): conn, addr = self.accept() # Drop existing connection. if self._handler is not None: self._handler.handle_close() self._handler = MonkeyHandler(conn) pubsub.publish('conn', addr, self._handler)
def camStaus(): global camera # camera._init_defaults print("exception status " + str(camera._camera_exception)) print("message " + msg) if camera._camera_exception == None and msg != "disconnected": pubsub.publish("agricert/pingBack", CamName) else: pubsub.publish("agricert/pingBack", "disconnected")
def loop(self): sub_cmd = pubsub.subscribe("CVWinCmd") msg_cmd = '' while msg_cmd != 'quit': self.update_window_frames() self.handle_keys(cv2.waitKey(1)) msg_cmd = listen_default(sub_cmd, block=False, empty='') pubsub.publish("CVWinCmd", 'quit') self.__stop_all_cams()
def set_run_state(self, state): # save the running state self.running = state # get text description of the /other/ state text = App.running_text[state] # change the button text self.btn_running["text"] = text # tell the world about the change pubsub.publish('running', state)
def handle_data(protocol, data, address): proto = protocol() try: event = proto.read(data) except (ValueError, TypeError): log.exception("Error decoding event from %s", address) return else: pubsub.publish("events", event)
def print_keys_thread(): sub_key = pubsub.subscribe("CVKeyStroke") sub_cmd = pubsub.subscribe("CVWinCmd") msg_cmd = '' while msg_cmd != 'quit': key_chr = listen_default(sub_key, timeout=.1) # type: np.ndarray if key_chr is not None: print("key pressed: " + str(key_chr)) msg_cmd = listen_default(sub_cmd, block=False, empty='') pubsub.publish("CVWinCmd", 'quit')
def do_window_close(self, widget,data=None): pubsub.publish("shoebot", "quit") if self.has_server: self.sock.close() self.hide_variables_window() self.destroy() self.window_open = False
def run(self): while self.running: if self.is_dirty: pubsub.publish('DISPLAY', self.model.data, self.model.move_history) self.is_dirty = False for event in self.get_events(): self.handle_player_input(event) self.is_dirty = True
def capture(fileName): global msg if camera._camera_exception == None and msg != "disconnected": camera.capture("./images/" + fileName) upload.Upload(filePath="./images/" + fileName, filename=fileName, topic="agricert/image/uploadStatus") else: pubsub.publish("agricert/pingBack", "disconnected")
def on_freq_sample(self, data): """The smoothing slider has changed. Its meaning varies with plot type. """ data = int(data) self.cfg.freq_sample = data pubsub.publish('freq_sample', data) if not self.running: self.update_charts()
def run(project, topic): Faker.seed(0) faker = Faker() pubsub.get_or_create_topic(project, topic) id = 0 while True: simple_profile = faker.simple_profile() simple_profile["id"] = id id += 1 simple_profile = json.dumps(simple_profile, default=str) pubsub.publish(project, topic, data=simple_profile.encode("utf-8"))
def OnPageChanged(self, event): if event: event.Skip() if self.calling: return try: self.calling = 1 old = event.GetOldSelection() new = event.GetSelection() if old > -1: owin = self.GetPage(old).GetWindow1() ## owin.docstate.Hide() if new > -1: self.root.dragger._SelectItem(new) win = self.GetPage(new).GetWindow1() #fix for dealing with current paths. if win.dirname: try: __main__.current_path = win.dirname except: traceback.print_exc() pass pubsub.publish('document.selected', stc_id=id(win)) #width = self.GetClientSize()[0] #split = win.parent #if win.GetWrapMode() == wx.STC_WRAP_NONE: # self.parent.SetStatusText("", 1) #else: # self.parent.SetStatusText("WRAP",1) ## self.root.OnDocumentChange(win, None) ## win.docstate.Show() _, flags = __main__.CARET_OPTION_TO_ID[__main__.caret_option] win.SetXCaretPolicy( flags, __main__.caret_slop * __main__.caret_multiplier) win.SetYCaretPolicy(flags, __main__.caret_slop) win.SetCaretWidth(__main__.CARET_WIDTH) if not win.loaded: win.loadfile() self.root.timer.Start(10, wx.TIMER_ONE_SHOT) if self.other_focus: wx.CallAfter(win.SetFocus) self.other_focus = 0 else: self.root.dragger.justdragged = time.time() self._seen() ## print "pagechanged", new, old finally: self.calling = 0
def publisher(): ''' Publishes a random blob of data after a random number of seconds ''' backend = get_backend('backends', BACKEND, 'my.app') for x in range(0, 100): data = fake.pydict() print("-----------------------") publish(backend, 'foo', data) sleeptime = random.choice(range(1, 10)) time.sleep(sleeptime)
def add_chart(self): """Add a chart to the application.""" _row = len(self.charts) new_chart = chart_.Chart(self.chart_frame, self.running) new_chart.grid(row=_row, column=0, sticky=tk.NSEW) self.charts.append(new_chart) pubsub.publish('focus', new_chart) self.focus_chart = new_chart # allow charts to expand vertically # (horizontal expansion has already been set) self.chart_frame.rowconfigure(_row, weight=3) return new_chart
def capture(): imgName = str(int(time.time())) + ".png" obj = dbops.dbConn() obj.operation("insert_image") obj.insert({ "image": imgName, "image-hist": "hist-" + imgName, "image-red": "red_comp_" + imgName }) pubsub.publish("agricert/capture", imgName) print("cappture method") return imgName
def _populate(self): for k,e in self._data.items(): if e.name: if not self._name_map.has_key(e.number): self._name_map[e.number]=e.name else: if not self._name_map.has_key(e.number): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e.number } ) self.list_widget.populate() self.CalculateStats() self._publish_today_data()
def isConnected(): if not (pubsub.initStatus): pubsub.init() time.sleep(1) global statusCam1 global statusCam2 statusCam1 = statusCam2 = False pubsub.publish(getpingTopic(), "") closeTime = time.time() + 6 while True: if (statusCam1 and statusCam2) or time.time() > closeTime: break return str(statusCam1 and statusCam2)
def publisher(): """ Publishes a random blob of data after a random number of seconds """ backend = get_backend("school_backends", BACKEND, CHANNEL, "my.app") for x in range(0, 100): data = {"foo": "bar", "nested": [{"foo": "baz"}]} print("-----------------------") publish(backend, random.choice(events), data) sleep_time = random.choice(range(0, 10)) print("Next publication in {}".format(sleep_time)) time.sleep(sleep_time)
def run(self): while self.running: if self.is_dirty: with self._buffer_lock: row = [8, 7, 6, 5, 4, 3, 2, 1] for i in range(0, 64, 8): print(str(row.pop(0)) + self.buffer[i:i + 8]) print(' abcdefgh') evt = PlayerInputEvent() evt.move = input('Enter move: ') pubsub.publish('PLAYER_INPUT', evt) self.is_dirty = False
def _populate(self): self._clear() self._node_dict={} for k,e in self._data.items(): if e.name: if not self._name_map.has_key(e.number): self._name_map[e.number]=e.name else: if not self._name_map.has_key(e.number): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e.number } ) self._display_func[self._by_mode]() self._OnExpandAll(None) self._publish_today_data()
def on_scale_mode(self): """Scaling mode has changed.""" # get value from radio buttons and save it mode = self.scale_mode.get() if not self.focus_chart or not self.focus_chart.plots: return # record the new mode for this plot self.save_scale_setting('mode', mode) pubsub.publish('scale_mode', mode, shift) self.set_scaling(self.focus_chart) if not self.running: self.update_charts()
def on_message(self, client, userdata, msg): info('mqtt', 'on_message:' + msg.topic + ': ' + str(msg.payload)) try: if self.queue: m = Message(msg.topic, msg.payload) if m.is_valid(): if m.for_device() and not m.get_name() in [ 'CONNECTED', 'REGISTERED', 'TX' ]: self.queue.put(m) publish(m, channel='inbound') else: publish(m, channel='inbound') except Exception as ex: error('mqtt', 'on_message: ' + str(ex))
def _populate(self): # lookup phone book for names for k,e in self._data.items(): if e.name: if not self._name_map.has_key(e.number): self._name_map[e.number]=e.name else: if not self._name_map.has_key(e.number): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e.number } ) self.list_widget.populate() #update stats self.CalculateStats() # tell today 'bout it self._publish_today_data()
def _populate(self): # lookup phone book for names for k, e in self._data.items(): if e.name: if not self._name_map.has_key(e.number): self._name_map[e.number] = e.name else: if not self._name_map.has_key(e.number): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, {'item': e.number}) self.list_widget.populate() #update stats self.CalculateStats() # tell today 'bout it self._publish_today_data()
def on_man_base(self, data): """The manual-scaling base slider has been changed.""" # convert the slider value to the range we want base = self.slider2base(data) # save it in the configuration file self.save_scale_setting('base', base) if self.scale_mode.get() != App.MANUAL: self.scale_mode.set(App.MANUAL) self.on_scale_mode() # display the value to the user self.base_label['text'] = str(base) start = self.scrollbar.get()[0] pubsub.publish('man_base', base, start, shift)
def create_module(): if request.method == 'POST': data = request.form.to_dict(flat=True) media_url = upload_file(request.files.get('module_media')) pieces = media_url.split('/') object_name = pieces[len(pieces)-1] pubsub.publish(TOPIC, b'file submitted', object_name) for index in range(0,10): pubsub.stuff_queue(TOPIC) db = MySQLdb.connect(host="127.0.0.1", user="******", passwd=config.SQL_PASSWORD) cur = db.cursor() cur.execute('INSERT INTO lms.modules (name, description, content, media) VALUES ("{}","{}","{}","{}")'.format(data['title'],data['description'],data['author'],object_name)) db.commit() db.close() return redirect('/modules', code=302) return render_template('module_form.html', instance_metadata=INSTANCE_METADATA)
def publish_event(event_t, data=None, extra_channels=None, wait=None): """ Publish an event ot any subscribers. :param event_t: event type :param data: event data :param extra_channels: :param wait: :return: """ event = Event(event_t, data) pubsub.publish("shoebot", event) for channel_name in extra_channels or []: pubsub.publish(channel_name, event) if wait is not None: channel = pubsub.subscribe(wait) channel.listen(wait)
def OnRename(self, _=None): items=self.GetSelectedItems() if len(items)!=1: return old_name=items[0].name dlg=wx.TextEntryDialog(self, "Enter a new name:", "Item Rename", old_name) if dlg.ShowModal()==wx.ID_OK: new_name=dlg.GetValue() if len(new_name) and new_name!=old_name: old_name=items[0].name new_name=self.get_media_name_from_filename(new_name) items[0].RenameInIndex(new_name) pubsub.publish(pubsub.MEDIA_NAME_CHANGED, data={ pubsub.media_change_type: self.media_notification_type, pubsub.media_old_name: old_name, pubsub.media_new_name: new_name }) dlg.Destroy()
def populate(self): self.nodes={} self.nodes_keys={} index=0 for k,e in self._stats._data.items(): if len(e._from) and not self._name_map.has_key(e._from): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e._from } ) if len(e._to) and not self._name_map.has_key(e._to): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e._to } ) if len(e.callback) and not self._name_map.has_key(e.callback): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e.callback } ) if self._display_filter=='All' or e.folder==self._display_filter: _from=self._me_name if e.folder in (e.Folder_Sent, e.Folder_Saved) \ else self._number2name(e._from) _to=self._me_name if e.folder==e.Folder_Inbox \ else self._number2name(e._to) self.nodes[index]=(_from, _to, e.get_date_time_str()) self.nodes_keys[index]=k self._data_map[k]=index index+=1 self._item_list.ResetView(self.nodes, self.nodes_keys) self.publish_today_data()
def populate(self): self.nodes={} self.nodes_keys={} index=0 for k,e in self._stats._data.items(): if len(e._from) and not self._name_map.has_key(e._from): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e._from } ) if len(e._to) and not self._name_map.has_key(e._to): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e._to } ) if len(e.callback) and not self._name_map.has_key(e.callback): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e.callback } ) if e.folder==self._display_filter: col=self._item_list.GetColumn(0) col.SetMask(wx.LIST_MASK_TEXT) if e.folder==sms.SMSEntry.Folder_Inbox: col.SetText("From") name=e._from else: col.SetText("To") name=e._to self._item_list.SetColumn(0, col) if name!=None and name!="": temp=self._name_map.get(name, None) if temp !=None: name=temp self.nodes[index]=(name, e.get_date_time_str(), e.subject) self.nodes_keys[index]=k self._data_map[k]=index index+=1 self._item_list.ResetView(self.nodes, self.nodes_keys) self.publish_today_data()
def widget_changed(self, widget, v): ''' Called when a slider is adjusted. ''' # set the appropriate bot var if v.type is NUMBER: self.bot._namespace[v.name] = widget.get_value() self.bot._vars[v.name].value = widget.get_value() ## Not sure if this is how to do this - stu pubsub.publish("shoebot", EVENT_VARIABLE_UPDATED) # pretty dumb for now elif v.type is BOOLEAN: self.bot._namespace[v.name] = widget.get_active() self.bot._vars[v.name].value = widget.get_active() ## Not sure if this is how to do this - stu pubsub.publish("shoebot", EVENT_VARIABLE_UPDATED) # pretty dumb for now elif v.type is TEXT: self.bot._namespace[v.name] = widget.get_text() self.bot._vars[v.name].value = widget.get_text() ## Not sure if this is how to do this - stu pubsub.publish("shoebot", EVENT_VARIABLE_UPDATED) # pretty dumb for now
def _populate(self): self._clear() self._data_map={} keys=[(x.datetime, k) for k,x in self._data.items()] keys.sort() for (_,k) in keys: n=self._data[k] i=self._item_list.AppendItem(self._nodes[n.folder], n.subject) self._item_list.SetItemPyData(i, k) self._data_map[k]=i if len(n._from) and not self._name_map.has_key(n._from): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': n._from } ) if len(n._to) and not self._name_map.has_key(n._to): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': n._to } ) if len(n.callback) and not self._name_map.has_key(n.callback): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': n.callback } ) self.canned_list.SetStrings( self.canned_data.user_list) self.builtin_canned_list.Set(self.canned_data.builtin_list)
def OnListRequest(self, msg=None): l=[self._data['wallpaper-index'][x]['name'] \ for x in self._data['wallpaper-index']\ if self._data['wallpaper-index'][x].get('origin', None)!='video' ] l.sort() pubsub.publish(pubsub.ALL_WALLPAPERS, l) def OnIdle(self, _): "Save out changed data" if self.modified: self.modified=False self.populatefs(self._data) self.OnListRequest() def _OnKey(self, evt): self._shift_down=evt.ShiftDown() evt.Skip() def OnAdd(self, evt=None): self._raw_image=self._shift_down super(WallpaperView, self).OnAdd(evt) self._shift_down=False def OrganizeChange(self, evt): self.mainwindow.config.Write('imageorganizedby', evt.GetEventObject().GetLabel(evt.GetId())) evt.GetEventObject().Check(evt.GetId(), True) self.OnRefresh() def GetSections(self): items=[DisplayItem(self, key, self.mainwindow.wallpaperpath) for key in self._data['wallpaper-index']] items=[item for item in items if os.path.exists(item.filename)] self.sections=[] if len(items)==0: return self.sections for i in range(len(self.organizetypes)): item=self.organizemenu.FindItemByPosition(i) if self.organizemenu.IsChecked(item.GetId()): for sectionlabel, items in self.organizeinfo[item.GetId()](items): sh=aggregatedisplay.SectionHeader(sectionlabel) sh.itemsize=(self.usewidth+120, self.useheight+DisplayItem.PADDING*2) for item in items: item.thumbnailsize=self.usewidth, self.useheight items=[(item.name.lower(), item) for item in items] items.sort() items=[item for name,item in items] self.sections.append( (sh, items) ) return [sh for sh,items in self.sections] assert False, "Can't get here" def GetItemSize(self, sectionnumber, sectionheader): return sectionheader.itemsize def GetItemsFromSection(self, sectionnumber, sectionheader): return self.sections[sectionnumber][1] def organizeby_ImageType(self, items): types={} for item in items: t=item.fileinfo.format if t is None: t="<Unknown>" l=types.get(t, []) l.append(item) types[t]=l keys=types.keys() keys.sort() return [ (key, types[key]) for key in types] def organizeby_Origin(self, items): types={} for item in items: t=item.origin if t is None: t="Default" l=types.get(t, []) l.append(item) types[t]=l keys=types.keys() keys.sort() return [ (key, types[key]) for key in types] def organizeby_FileSize(self, items): sizes={0: ('Less than 8kb', []), 8192: ('8 kilobytes', []), 16384: ('16 kilobytes', []), 32768: ('32 kilobytes', []), 65536: ('64 kilobytes', []), 131052: ('128 kilobytes', []), 524208: ('512 kilobytes', []), 1024*1024: ('One megabyte', [])} keys=sizes.keys() keys.sort() for item in items: t=item.size if t>=keys[-1]: sizes[keys[-1]][1].append(item) continue for i,k in enumerate(keys): if t<keys[i+1]: sizes[k][1].append(item) break return [sizes[k] for k in keys if len(sizes[k][1])] def isBCI(self, filename): """Returns True if the file is a Brew Compressed Image""" return open(filename, "rb").read(4)=="BCI\x00" def RemoveFromIndex(self, names): for name in names: wp=self._data['wallpaper-index'] for k in wp.keys(): if wp[k]['name']==name: del wp[k] self.modified=True def GetItemThumbnail(self, name, width, height): img,_=self.GetImage(name.encode(fileview.media_codec)) if img is None or not img.Ok(): img=wx.Image(guihelper.getresourcefile('wallpaper.png')) if width!=img.GetWidth() or height!=img.GetHeight(): sfactorw=float(width)/img.GetWidth() sfactorh=float(height)/img.GetHeight() sfactor=min(sfactorw,sfactorh) newwidth=int(img.GetWidth()*sfactor) newheight=int(img.GetHeight()*sfactor) img.Rescale(newwidth, newheight) bitmap=img.ConvertToBitmap() return bitmap def GetImage(self, file): """Gets the named image @return: (wxImage, filesize) """ file,cons = self.GetImageConstructionInformation(file) return cons(file), int(os.stat(file).st_size) def GetImageConstructionInformation(self, file): """Gets information for constructing an Image from the file @return: (filename to use, function to call that returns wxImage) """ file=os.path.join(self.mainwindow.wallpaperpath, file) fi=self.GetFileInfo(file) if file.endswith(".mp4") or not os.path.isfile(file): return guihelper.getresourcefile('wallpaper.png'), wx.Image if fi: if fi.format=='AVI': return file, conversions.convertavitobmp if fi.format=='LGBIT': return file, conversions.convertfilelgbittobmp if fi.format=='3GPP2': return file, lambda name: None return file, wx.Image def GetFileInfo(self, filename): return fileinfo.identify_imagefile(filename) def GetImageStatInformation(self, file): """Returns the statinfo for file""" file=os.path.join(self.mainwindow.wallpaperpath, file) return statinfo(file) def updateindex(self, index): if index!=self._data['wallpaper-index']: self._data['wallpaper-index']=index.copy() self.modified=True def populate(self, dict): if self._data['wallpaper-index']!=dict['wallpaper-index']: self._data['wallpaper-index']=dict['wallpaper-index'].copy() self.modified=True self.OnRefresh() def OnPaste(self, evt=None): super(WallpaperView, self).OnPaste(evt) if not wx.TheClipboard.Open(): return if wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)): do=wx.BitmapDataObject() success=wx.TheClipboard.GetData(do) else: success=False wx.TheClipboard.Close() if success: self.OnAddImage(wx.ImageFromBitmap(do.GetBitmap()), None) def CanPaste(self): """ Return True if can accept clipboard data, False otherwise """ if not wx.TheClipboard.Open(): return False r=wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_FILENAME)) or\ wx.TheClipboard.IsSupported(wx.DataFormat(wx.DF_BITMAP)) wx.TheClipboard.Close() return r def AddToIndex(self, file, origin): for i in self._data['wallpaper-index']: if self._data['wallpaper-index'][i]['name']==file: self._data['wallpaper-index'][i]['origin']=origin return keys=self._data['wallpaper-index'].keys() idx=10000 while idx in keys: idx+=1 self._data['wallpaper-index'][idx]={'name': file, 'origin': origin} self.modified=True def OnAddFiles(self, filenames): for file in filenames: if self._raw_image: decoded_file=self.decodefilename(file) targetfilename=self.getshortenedbasename(decoded_file) open(targetfilename, 'wb').write(open(file, 'rb').read()) self.AddToIndex(str(os.path.basename(targetfilename)).decode(fileview.media_codec), 'images') else: fi=self.GetFileInfo(file) if fi is not None and fi.format=='LGBIT': img=conversions.convertfilelgbittobmp(file) else: img=wx.Image(file) if not img.Ok(): dlg=wx.MessageDialog(self, "Failed to understand the image in '"+file+"'", "Image not understood", style=wx.OK|wx.ICON_ERROR) dlg.ShowModal() continue self.OnAddImage(img,file,refresh=False) self.OnRefresh() def OnAddImage(self, img, file, refresh=True): dlg=ImagePreviewDialog(self, img, file, self.mainwindow.phoneprofile) if dlg.ShowModal()!=wx.ID_OK: dlg.Destroy() return img=dlg.GetResultImage() imgparams=dlg.GetResultParams() origin=dlg.GetResultOrigin() extension={'BMP': 'bmp', 'JPEG': 'jpg', 'PNG': 'png'}[imgparams['format']] decoded_file=self.decodefilename(file) targetfilename=self.getshortenedbasename(decoded_file, extension) res=getattr(self, "saveimage_"+imgparams['format'])( img, targetfilename, imgparams) if not res: try: os.remove(targetfilename) except: pass dlg=wx.MessageDialog(self, "Failed to convert the image in '"+file+"'", "Image not converted", style=wx.OK|wx.ICON_ERROR) dlg.ShowModal() return self.AddToIndex(str(os.path.basename(targetfilename)).decode(fileview.media_codec), origin) if refresh: self.OnRefresh() def saveimage_BMP(self, img, targetfilename, imgparams): if img.ComputeHistogram(wx.ImageHistogram())<=236: img.SetOptionInt(wx.IMAGE_OPTION_BMP_FORMAT, wx.BMP_8BPP) return img.SaveFile(targetfilename, wx.BITMAP_TYPE_BMP) def saveimage_JPEG(self, img, targetfilename, imgparams): img.SetOptionInt("quality", 100) return img.SaveFile(targetfilename, wx.BITMAP_TYPE_JPEG) def saveimage_PNG(self, img, targetfilename, imgparams): return img.SaveFile(targetfilename, wx.BITMAP_TYPE_PNG) def populatefs(self, dict): self.thedir=self.mainwindow.wallpaperpath return self.genericpopulatefs(dict, 'wallpapers', 'wallpaper-index', self.CURRENTFILEVERSION) def getfromfs(self, result): self.thedir=self.mainwindow.wallpaperpath return self.genericgetfromfs(result, None, 'wallpaper-index', self.CURRENTFILEVERSION) def versionupgrade(self, dict, version): """Upgrade old data format read from disk @param dict: The dict that was read in @param version: version number of the data on disk """ if version==0: version=1 if version==1: print "converting to version 2" version=2 d={} input=dict.get('wallpaper-index', {}) for i in input: d[i]={'name': input[i]} dict['wallpaper-index']=d return dict def getdata(self,dict,want=fileview.FileView.NONE): return self.genericgetdata(dict, want, self.mainwindow.wallpaperpath, 'wallpapers', 'wallpaper-index') class WallpaperPreview (wx.PyWindow) : def __init__(self, parent, image=None, id=1, size=wx.DefaultSize, pos=wx.DefaultPosition, style=0): wx.PyWindow.__init__(self, parent, id=id, size=size, pos=pos, style=style|wx.FULL_REPAINT_ON_RESIZE) self.bg=wx.Brush(parent.GetBackgroundColour()) self._bufbmp=None wx.EVT_ERASE_BACKGROUND(self, lambda evt: None) wx.EVT_PAINT(self, self.OnPaint) self.SetImage(image) def SetImage(self, name): if name is None: self.theimage=None else: self.theimage, _=thewallpapermanager.GetImage(name) self.thesizedbitmap=None self.Refresh(False) def OnPaint(self, _): sz=self.GetClientSize() if self._bufbmp is None or sz.width>self._bufbmp.GetWidth() or sz.height>self._bufbmp.GetHeight(): self._bufbmp=wx.EmptyBitmap((sz.width+64)&~8, (sz.height+64)&~8) dc=wx.BufferedPaintDC(self, self._bufbmp, style=wx.BUFFER_VIRTUAL_AREA) dc.SetBackground(self.bg) dc.Clear() if self.theimage is None: return sfactorw=float(sz.width)/self.theimage.GetWidth() sfactorh=float(sz.height)/self.theimage.GetHeight() sfactor=min(sfactorw,sfactorh) newwidth=int(self.theimage.GetWidth()*sfactor) newheight=int(self.theimage.GetHeight()*sfactor) if self.thesizedbitmap is None or self.thesizedbitmap.GetWidth()!=newwidth or \ self.thesizedbitmap.GetHeight()!=newheight: self.thesizedbitmap=self.theimage.Scale(newwidth, newheight).ConvertToBitmap() dc.DrawBitmap(self.thesizedbitmap, sz.width/2-newwidth/2, sz.height/2-newheight/2, True) def ScaleImageIntoBitmap(img, usewidth, useheight, bgcolor=None, valign="center"): """Scales the image and returns a bitmap @param usewidth: the width of the new image @param useheight: the height of the new image @param bgcolor: the background colour as a string ("ff0000" is red etc). If this is none then the background is made transparent""" if bgcolor is None: bitmap=wx.EmptyBitmap(usewidth, useheight, 24) else: bitmap=wx.EmptyBitmap(usewidth, useheight) mdc=wx.MemoryDC() mdc.SelectObject(bitmap) sfactorw=usewidth*1.0/img.GetWidth() sfactorh=useheight*1.0/img.GetHeight() sfactor=min(sfactorw,sfactorh) newwidth=int(img.GetWidth()*sfactor/1.0) newheight=int(img.GetHeight()*sfactor/1.0) img.Rescale(newwidth, newheight) if bgcolor is not None: transparent=None assert len(bgcolor)==6 red=int(bgcolor[0:2],16) green=int(bgcolor[2:4],16) blue=int(bgcolor[4:6],16) mdc.SetBackground(wx.TheBrushList.FindOrCreateBrush(wx.Colour(red,green,blue), wx.SOLID)) else: transparent=wx.Colour(*(img.FindFirstUnusedColour()[1:])) mdc.SetBackground(wx.TheBrushList.FindOrCreateBrush(transparent, wx.SOLID)) mdc.Clear() mdc.SelectObject(bitmap) posx=usewidth-(usewidth+newwidth)/2 if valign in ("top", "clip"): posy=0 elif valign=="center": posy=useheight-(useheight+newheight)/2 else: assert False, "bad valign "+valign posy=0 mdc.DrawBitmap(img.ConvertToBitmap(), posx, posy, True) mdc.SelectObject(wx.NullBitmap) if transparent is not None: mask=wx.Mask(bitmap, transparent) bitmap.SetMask(mask) if valign=="clip" and newheight!=useheight: return bitmap.GetSubBitmap( (0,0,usewidth,newheight) ) return bitmap statinfo=common.statinfo class BPFSHandler (wx.FileSystemHandler) : CACHELOWWATER=80 CACHEHIGHWATER=100 def __init__(self, wallpapermanager): wx.FileSystemHandler.__init__(self) self.wpm=wallpapermanager self.cache={} def _GetCache(self, location, statinfo): """Return the cached item, or None Note that the location value includes the filename and the parameters such as width/height """ if statinfo is None: print "bad location",location return None return self.cache.get( (location, statinfo), None) def _AddCache(self, location, statinfo, value): "Add the item to the cache" if len(self.cache)>=self.CACHEHIGHWATER: print "BPFSHandler cache flush" while len(self.cache)>self.CACHELOWWATER: del self.cache[random.choice(self.cache.keys())] self.cache[(location, statinfo)]=value def CanOpen(self, location): if location.startswith("/"): return False proto=self.GetProtocol(location) if proto=="bpimage" or proto=="bpuserimage": return True return False def OpenFile(self,filesystem,location): try: res=self._OpenFile(filesystem,location) except: res=None print "Exception in getting image file - you can't do that!" print common.formatexception() if res is not None: res[0].seek(0) args=(wx.InputStream(res[0]),)+res[1:] res=wx.FSFile(*args) return res def _OpenFile(self, filesystem, location): proto=self.GetProtocol(location) r=self.GetRightLocation(location) params=r.split(';') r=params[0] params=params[1:] p={} for param in params: x=param.find('=') key=str(param[:x]) value=param[x+1:] if key=='width' or key=='height': p[key]=int(value) else: p[key]=value if proto=="bpimage": return self.OpenBPImageFile(location, r, **p) elif proto=="bpuserimage": return self.OpenBPUserImageFile(location, r, **p) return None def OpenBPUserImageFile(self, location, name, **kwargs): si=self.wpm.GetImageStatInformation(name) res=self._GetCache(location, si) if res is not None: return res file,cons=self.wpm.GetImageConstructionInformation(name) if cons == wx.Image: res=BPFSImageFile(self, location, file, **kwargs) else: res=BPFSImageFile(self, location, img=cons(file), **kwargs) self._AddCache(location, si, res) return res def OpenBPImageFile(self, location, name, **kwargs): f=guihelper.getresourcefile(name) if not os.path.isfile(f): print f,"doesn't exist" return None si=statinfo(f) res=self._GetCache(location, si) if res is not None: return res res=BPFSImageFile(self, location, name=f, **kwargs) self._AddCache(location, si, res) return res def BPFSImageFile(fshandler, location, name=None, img=None, width=-1, height=-1, valign="center", bgcolor=None): """Handles image files If we have to do any conversion on the file then we return PNG data. This used to be a class derived from wx.FSFile, but due to various wxPython bugs it instead returns the parameters to make a wx.FSFile since a new one has to be made every time. """ if img is None and width<0 and height<0: mime=guihelper.getwxmimetype(name) if mime not in (None, "image/x-bmp"): return (open(name, "rb"), location, mime, "", wx.DateTime_Now()) if img is None: img=wx.Image(name) if width>0 and height>0: b=ScaleImageIntoBitmap(img, width, height, bgcolor, valign) else: b=img.ConvertToBitmap() f=common.gettempfilename("png") if not b.SaveFile(f, wx.BITMAP_TYPE_PNG): raise Exception, "Saving to png failed" data=open(f, "rb").read() os.remove(f) return (cStringIO.StringIO(data), location, "image/png", "", wx.DateTime_Now()) class ImageCropSelect (wx.ScrolledWindow) : def __init__(self, parent, image, previewwindow=None, id=1, resultsize=(100,100), size=wx.DefaultSize, pos=wx.DefaultPosition, style=0): wx.ScrolledWindow.__init__(self, parent, id=id, size=size, pos=pos, style=style|wx.FULL_REPAINT_ON_RESIZE) self.previewwindow=previewwindow self.bg=wx.Brush(wx.WHITE) self.parentbg=wx.Brush(parent.GetBackgroundColour()) self._bufbmp=None self.anchors=None wx.EVT_ERASE_BACKGROUND(self, lambda evt: None) wx.EVT_PAINT(self, self.OnPaint) self.image=image self.origimage=image self.setresultsize(resultsize) self.cursors=[wx.StockCursor(c) for c in (wx.CURSOR_ARROW, wx.CURSOR_HAND, wx.CURSOR_SIZING, wx.CURSOR_NO_ENTRY)] self.clickpoint=None wx.EVT_MOTION(self, self.OnMotion) wx.EVT_LEFT_DOWN(self, self.OnLeftDown) wx.EVT_LEFT_UP(self, self.OnLeftUp) def SetPreviewWindow(self, previewwindow): self.previewwindow=previewwindow def OnPaint(self, _): sz=self.thebmp.GetWidth(), self.thebmp.GetHeight() sz2=self.GetClientSize() sz=max(sz[0],sz2[0])+32,max(sz[1],sz2[1])+32 if self._bufbmp is None or self._bufbmp.GetWidth()<sz[0] or self._bufbmp.GetHeight()<sz[1]: self._bufbmp=wx.EmptyBitmap((sz[0]+64)&~8, (sz[1]+64)&~8) dc=wx.BufferedPaintDC(self, self._bufbmp, style=wx.BUFFER_VIRTUAL_AREA) if sz2[0]<sz[0] or sz2[1]<sz[1]: dc.SetBackground(self.parentbg) dc.Clear() dc.DrawBitmap(self.thebmp, 0, 0, False) l,t,r,b=self.anchors points=(l,t), (r,t), (r,b), (l,b) dc.DrawLines( points+(points[0],) ) for x,y in points: dc.DrawRectangle(x-5, y-5, 10, 10) OUTSIDE=0 INSIDE=1 HANDLE_LT=2 HANDLE_RT=3 HANDLE_RB=4 HANDLE_LB=5 def _hittest(self, evt): l,t,r,b=self.anchors within=lambda x,y,l,t,r,b: l<=x<=r and t<=y<=b x,y=self.CalcUnscrolledPosition(evt.GetX(), evt.GetY()) for i,(ptx,pty) in enumerate(((l,t), (r,t), (r,b), (l,b))): if within(x,y,ptx-5, pty-5, ptx+5,pty+5): return self.HANDLE_LT+i if within(x,y,l,t,r,b): return self.INSIDE return self.OUTSIDE def OnMotion(self, evt): if evt.Dragging(): return self.OnMotionDragging(evt) self.UpdateCursor(evt) def UpdateCursor(self, evt): ht=self._hittest(evt) self.SetCursor(self.cursors[min(2,ht)]) def OnMotionDragging(self, evt): if not evt.LeftIsDown() or self.clickpoint is None: self.SetCursor(self.cursors[3]) return xx,yy=self.CalcUnscrolledPosition(evt.GetX(), evt.GetY()) deltax=xx-self.origevtpos[0] deltay=yy-self.origevtpos[1] if self.clickpoint==self.INSIDE: newanchors=self.origanchors[0]+deltax, self.origanchors[1]+deltay, \ self.origanchors[2]+deltax, self.origanchors[3]+deltay iw=self.dimensions[0] ih=self.dimensions[1] if newanchors[0]<0: newanchors=0,newanchors[1], self.origanchors[2]-self.origanchors[0], newanchors[3] if newanchors[1]<0: newanchors=newanchors[0], 0, newanchors[2], self.origanchors[3]-self.origanchors[1] if newanchors[2]>iw: newanchors=iw-(self.origanchors[2]-self.origanchors[0]),newanchors[1],iw, newanchors[3] if newanchors[3]>ih: newanchors=newanchors[0],ih-(self.origanchors[3]-self.origanchors[1]), newanchors[2],ih self.anchors=newanchors self.Refresh(False) self.updatepreview() return if self.clickpoint==self.HANDLE_LT: aa=0,1,-1,-1 elif self.clickpoint==self.HANDLE_RT: aa=2,1,+1,-1 elif self.clickpoint==self.HANDLE_RB: aa=2,3,+1,+1 elif self.clickpoint==self.HANDLE_LB: aa=0,3,-1,+1 else: assert False, "can't get here" na=[self.origanchors[0],self.origanchors[1],self.origanchors[2],self.origanchors[3]] na[aa[0]]=na[aa[0]]+deltax na[aa[1]]=na[aa[1]]+deltay neww=na[2]-na[0] newh=na[3]-na[1] ar=float(neww)/newh if ar<self.aspectratio: na[aa[0]]=na[aa[0]]+(self.aspectratio*newh-neww)*aa[2] elif ar>self.aspectratio: na[aa[1]]=na[aa[1]]+(neww/self.aspectratio-newh)*aa[3] if neww<10 or newh<10: return if na[0]<0: xdiff=-na[0] ydiff=xdiff/self.aspectratio na[0]=0 na[1]+=ydiff if na[1]<0: ydiff=-na[1] xdiff=ydiff*self.aspectratio na[1]=0 na[0]-=xdiff if na[2]>self.dimensions[0]: xdiff=na[2]-self.dimensions[0] ydiff=xdiff/self.aspectratio na[2]=na[2]-xdiff na[3]=na[3]-ydiff if na[3]>self.dimensions[1]: ydiff=na[3]-self.dimensions[1] xdiff=ydiff*self.aspectratio na[2]=na[2]-xdiff na[3]=na[3]-ydiff if na[0]<0 or na[1]<0 or na[2]>self.dimensions[0] or na[3]>self.dimensions[1]: print "offscreen fixup not written yet" return self.anchors=na self.Refresh(False) self.updatepreview() return def OnLeftDown(self, evt): ht=self._hittest(evt) if ht==self.OUTSIDE: self.SetCursor(self.cursors[3]) return self.clickpoint=ht xx,yy=self.CalcUnscrolledPosition(evt.GetX(), evt.GetY()) self.origevtpos=xx,yy self.origanchors=self.anchors def OnLeftUp(self, evt): self.clickpoint=None self.UpdateCursor(evt) def setlbcolour(self, colour): self.bg=wx.Brush(colour) self.remakebitmap() def SetZoom(self, factor): curzoom=float(self.image.GetWidth())/self.origimage.GetWidth() self.anchors=[a*factor/curzoom for a in self.anchors] self.image=self.origimage.Scale(self.origimage.GetWidth()*factor, self.origimage.GetHeight()*factor) self.setresultsize(self.resultsize) def setresultsize(self, (w,h)): self.resultsize=w,h self.aspectratio=ratio=float(w)/h imgratio=float(self.image.GetWidth())/self.image.GetHeight() neww=self.image.GetWidth() newh=self.image.GetHeight() if imgratio<ratio: neww*=ratio/imgratio elif imgratio>ratio: newh*=imgratio/ratio neww=max(neww, 50) newh=max(newh, 50) if self.anchors==None: self.anchors=0.1 * neww, 0.1 * newh, 0.9 * neww, 0.9 * newh l,t,r,b=self.anchors l=min(neww-40, l) r=min(neww-10, r) if r-l<20: r=40 t=min(newh-40, t) b=min(newh-10, b) if b-t<20: b=40 aratio=float(r-l)/(b-t) if aratio<ratio: b=t+(r-l)/ratio elif aratio>ratio: r=l+(b-t)*ratio self.anchors=l,t,r,b self.dimensions=neww,newh self.thebmp=wx.EmptyBitmap(neww, newh) self.remakebitmap() def remakebitmap(self): w,h=self.dimensions dc=wx.MemoryDC() dc.SelectObject(self.thebmp) dc.SetBackground(self.bg) dc.Clear() dc.DrawBitmap(self.image.ConvertToBitmap(), w/2-self.image.GetWidth()/2, h/2-self.image.GetHeight()/2, True) dc.SelectObject(wx.NullBitmap) self.imageofthebmp=None self.SetVirtualSize( (w, h) ) self.SetScrollRate(1,1) self.updatepreview() self.Refresh(False) def updatepreview(self): if self.previewwindow: self.previewwindow.SetUpdated(self.GetPreview) def GetPreview(self): w,h=self.resultsize l,t,r,b=self.anchors scale=max(float(w+0.99999)/(r-l), float(h+0.99999)/(b-t)) if True and scale<1: sub=wx.EmptyBitmap(w,h) mdcsub=wx.MemoryDC() mdcsub.SelectObject(sub) mdcsub.SetUserScale(scale, scale) mdc=wx.MemoryDC() mdc.SelectObject(self.thebmp) mdcsub.Blit(0,0,r-l,b-t,mdc,l,t) mdc.SelectObject(wx.NullBitmap) mdcsub.SelectObject(wx.NullBitmap) return sub sub=self.thebmp.GetSubBitmap( (l,t,(r-l),(b-t)) ) sub=sub.ConvertToImage() sub.Rescale(w,h) return sub.ConvertToBitmap() class ImagePreview (wx.PyWindow) : def __init__(self, parent): wx.PyWindow.__init__(self, parent) wx.EVT_ERASE_BACKGROUND(self, lambda evt: None) wx.EVT_PAINT(self, self.OnPaint) self.bmp=wx.EmptyBitmap(1,1) self.updater=None def SetUpdated(self, updater): self.updater=updater self.Refresh(True) def OnPaint(self, _): if self.updater is not None: self.bmp=self.updater() self.updater=None dc=wx.PaintDC(self) dc.DrawBitmap(self.bmp, 0, 0, False) class ImagePreviewDialog (wx.Dialog) : SCALES=[ (0.25, "1/4"), (0.5, "1/2"), (1, "1"), (2, "2"), (4, "4")] def __init__(self, parent, image, filename, phoneprofile): wx.Dialog.__init__(self, parent, -1, "Image Preview", style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.SYSTEM_MENU|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX) self.phoneprofile=phoneprofile self.filename=filename self.image=image vbsouter=wx.BoxSizer(wx.VERTICAL) hbs=wx.BoxSizer(wx.HORIZONTAL) self.cropselect=ImageCropSelect(self, image) vbs=wx.BoxSizer(wx.VERTICAL) self.colourselect=wx.lib.colourselect.ColourSelect(self, wx.NewId(), "Background ...", (255,255,255)) vbs.Add(self.colourselect, 0, wx.ALL|wx.EXPAND, 5) wx.lib.colourselect.EVT_COLOURSELECT(self, self.colourselect.GetId(), self.OnBackgroundColour) vbs.Add(wx.StaticText(self, -1, "Origin"), 0, wx.ALL, 5) self.originbox=wx.ListBox(self, size=(-1, 100)) vbs.Add(self.originbox, 0, wx.ALL|wx.EXPAND, 5) vbs.Add(wx.StaticText(self, -1, "Target"), 0, wx.ALL, 5) self.targetbox=wx.ListBox(self, size=(-1,100)) vbs.Add(self.targetbox, 0, wx.EXPAND|wx.ALL, 5) vbs.Add(wx.StaticText(self, -1, "Scale"), 0, wx.ALL, 5) for one,(s,_) in enumerate(self.SCALES): if s==1: break self.slider=wx.Slider(self, -1, one, 0, len(self.SCALES)-1, style=wx.HORIZONTAL|wx.SL_AUTOTICKS) wx.EVT_SCROLL(self, self.SetZoom) vbs.Add(self.slider, 0, wx.ALL|wx.EXPAND, 5) self.zoomlabel=wx.StaticText(self, -1, self.SCALES[one][1]) vbs.Add(self.zoomlabel, 0, wx.ALL|wx.ALIGN_CENTRE_HORIZONTAL, 5) vbs.Add(wx.StaticText(self, -1, "Preview"), 0, wx.ALL, 5) self.imagepreview=ImagePreview(self) self.cropselect.SetPreviewWindow(self.imagepreview) vbs.Add(self.imagepreview, 0, wx.ALL, 5) hbs.Add(vbs, 0, wx.ALL, 5) hbs.Add(self.cropselect, 1, wx.ALL|wx.EXPAND, 5) vbsouter.Add(hbs, 1, wx.EXPAND|wx.ALL, 5) vbsouter.Add(wx.StaticLine(self, -1, style=wx.LI_HORIZONTAL), 0, wx.EXPAND|wx.ALL, 5) vbsouter.Add(self.CreateButtonSizer(wx.OK|wx.CANCEL|wx.HELP), 0, wx.ALIGN_CENTRE|wx.ALL, 5) wx.EVT_LISTBOX(self, self.originbox.GetId(), self.OnOriginSelect) wx.EVT_LISTBOX_DCLICK(self, self.originbox.GetId(), self.OnOriginSelect) wx.EVT_LISTBOX(self, self.targetbox.GetId(), self.OnTargetSelect) wx.EVT_LISTBOX_DCLICK(self, self.targetbox.GetId(), self.OnTargetSelect) wx.EVT_BUTTON(self, wx.ID_HELP, lambda _: wx.GetApp().displayhelpid(helpids.ID_DLG_IMAGEPREVIEW)) self.originbox.Set(phoneprofile.GetImageOrigins().keys()) self.originbox.SetSelection(0) self.OnOriginSelect(None) self.SetSizer(vbsouter) vbsouter.Fit(self) import guiwidgets guiwidgets.set_size("wallpaperpreview", self, 80, 1.0) def ShowModal(self): res=wx.Dialog.ShowModal(self) import guiwidgets guiwidgets.save_size("wallpaperpreview", self.GetRect()) return res def SetZoom(self, evt): self.cropselect.SetZoom(self.SCALES[evt.GetPosition()][0]) self.zoomlabel.SetLabel(self.SCALES[evt.GetPosition()][1]) return def OnBackgroundColour(self, evt): self.cropselect.setlbcolour(evt.GetValue()) def OnOriginSelect(self, _): v=self.originbox.GetStringSelection() assert v is not None t=self.targetbox.GetStringSelection() self.targets=self.phoneprofile.GetTargetsForImageOrigin(v) keys=self.targets.keys() keys.sort() self.targetbox.Set(keys) if t in keys: self.targetbox.SetSelection(keys.index(t)) else: self.targetbox.SetSelection(0) self.OnTargetSelect(None) def OnTargetSelect(self, _): v=self.targetbox.GetStringSelection() print "target is",v w,h=self.targets[v]['width'],self.targets[v]['height'] self.imagepreview.SetSize( (w,h) ) self.cropselect.setresultsize( (w, h) ) sz=self.GetSizer() if sz is not None: sz.Layout() self.Refresh(True) def GetResultImage(self): return self.imagepreview.bmp.ConvertToImage() def GetResultParams(self): return self.targets[self.targetbox.GetStringSelection()] def GetResultOrigin(self): return self.originbox.GetStringSelection() if __name__=='__main__': if __debug__: def profile(filename, command): import hotshot, hotshot.stats, os file=os.path.abspath(filename) profile=hotshot.Profile(file) profile.run(command) profile.close() del profile howmany=100 stats=hotshot.stats.load(file) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(100) stats.sort_stats('cum', 'calls') stats.print_stats(100) stats.sort_stats('calls', 'time') stats.print_stats(100) sys.exit(0) class FakeProfile: def GetImageOrigins(self): return {"images": {'description': 'General images'}, "mms": {'description': 'Multimedia Messages'}, "camera": {'description': 'Camera images'}} def GetTargetsForImageOrigin(self, origin): return {"wallpaper": {'width': 100, 'height': 200, 'description': 'Display as wallpaper'}, "photoid": {'width': 100, 'height': 150, 'description': 'Display as photo id'}, "outsidelcd": {'width': 90, 'height': 80, 'description': 'Display on outside screen'}} def run(): app=wx.PySimpleApp() dlg=ImagePreviewDialog(None, wx.Image("test.jpg"), "foobar.png", FakeProfile()) dlg.ShowModal() if __debug__ and True: profile("wp.prof", "run()") run() import fileview if __name__=='__main__': if __debug__: def profile(filename, command): import hotshot, hotshot.stats, os file=os.path.abspath(filename) profile=hotshot.Profile(file) profile.run(command) profile.close() del profile howmany=100 stats=hotshot.stats.load(file) stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(100) stats.sort_stats('cum', 'calls') stats.print_stats(100) stats.sort_stats('calls', 'time') stats.print_stats(100) sys.exit(0) class FakeProfile: def GetImageOrigins(self): return {"images": {'description': 'General images'}, "mms": {'description': 'Multimedia Messages'}, "camera": {'description': 'Camera images'}} def GetTargetsForImageOrigin(self, origin): return {"wallpaper": {'width': 100, 'height': 200, 'description': 'Display as wallpaper'}, "photoid": {'width': 100, 'height': 150, 'description': 'Display as photo id'}, "outsidelcd": {'width': 90, 'height': 80, 'description': 'Display on outside screen'}} def run(): app=wx.PySimpleApp() dlg=ImagePreviewDialog(None, wx.Image("test.jpg"), "foobar.png", FakeProfile()) dlg.ShowModal() if __debug__ and True: profile("wp.prof", "run()") run()
def broadcast(self): pubsub.publish(pubsub.NEW_DATA_AVAILABLE, data=self)
def OnHyperlinkLeft(self, evt): if self.tab_index: pubsub.publish(pubsub.REQUEST_TAB_CHANGED, data=self.tab_index)
def send_request_event(): pubsub.publish(pubsub.REQUEST_TODAY_DATA)
def _populate(self): self._clear() self._node_dict={} for k,e in self._data.items(): if e.name: if not self._name_map.has_key(e.number): self._name_map[e.number]=e.name else: if not self._name_map.has_key(e.number): pubsub.publish(pubsub.REQUEST_PB_LOOKUP, { 'item': e.number } ) self._display_func[self._by_mode]() self._OnExpandAll(None) self._publish_today_data() def OnDelete(self, _): if self.read_only: return sels_idx=self._item_list.GetSelections() if not sels_idx: return for sel_idx in sels_idx: if not sel_idx.Ok(): continue k=self._item_list.GetPyData(sel_idx) if k is None: continue self._item_list.Delete(sel_idx) del self._data[k] self._save_to_db(self._data) def getdata(self, dict, want=None): dict[self._data_key]=copy.deepcopy(self._data) def populate(self, dict, force=False): if self.read_only and not force: return self._data=dict.get(self._data_key, {}) self._populate() def _save_to_db(self, dict): if self.read_only: return db_rr={} for k,e in dict.items(): db_rr[k]=CallHistoryDataobject(e) database.ensurerecordtype(db_rr, callhistoryobjectfactory) self._main_window.database.savemajordict(self._data_key, db_rr) def populatefs(self, dict): if self.read_only: wx.MessageBox('You are viewing historical data which cannot be changed or saved', 'Cannot Save Call History Data', style=wx.OK|wx.ICON_ERROR) else: self._save_to_db(dict.get(self._data_key, {})) return dict def getfromfs(self, result, timestamp=None): dict=self._main_window.database.\ getmajordictvalues(self._data_key, callhistoryobjectfactory, at_time=timestamp) r={} for k,e in dict.items(): ce=CallHistoryEntry() ce.set_db_dict(e) r[ce.id]=ce result.update({ self._data_key: r}) return result def merge(self, dict): if self.read_only: wx.MessageBox('You are viewing historical data which cannot be changed or saved', 'Cannot Save Call History Data', style=wx.OK|wx.ICON_ERROR) return d=dict.get(self._data_key, {}) l=[e for k,e in self._data.items()] for k,e in d.items(): if e not in l: self._data[e.id]=e self._save_to_db(self._data) self._populate() def OnHistoricalData(self): """Display current or historical data""" if self.read_only: current_choice=guiwidgets.HistoricalDataDialog.Historical_Data else: current_choice=guiwidgets.HistoricalDataDialog.Current_Data dlg=guiwidgets.HistoricalDataDialog(self, current_choice=current_choice, historical_date=self.historical_date, historical_events=\ self._main_window.database.getchangescount(self._data_key)) if dlg.ShowModal()==wx.ID_OK: self._main_window.OnBusyStart() current_choice, self.historical_date=dlg.GetValue() r={} if current_choice==guiwidgets.HistoricalDataDialog.Current_Data: self.read_only=False msg_str='Current Data' self.getfromfs(r) else: self.read_only=True msg_str='Historical Data as of %s'%\ str(wx.DateTimeFromTimeT(self.historical_date)) self.getfromfs(r, self.historical_date) self.populate(r, True) self.historical_data_label.SetLabel(msg_str) self._main_window.OnBusyEnd() dlg.Destroy() def get_selected_data(self): res={} for sel_idx in self._item_list.GetSelections(): k=self._item_list.GetPyData(sel_idx) if k: res[k]=self._data[k] return res def get_data(self): return self._data
def _report_event(self, event, *args): pubsub.publish('calib', event, *args)
def OnListRequest(self, msg=None): l=[self._data[self.database_key][x].name \ for x in self._data[self.database_key] \ if self._data[self.database_key][x].origin not in self.excluded_origins ] l.sort() pubsub.publish(pubsub.ALL_RINGTONES, l)
def post(self): '''Handle post requests to create / edit blog posts''' new = self.get_argument('new', False) title = self.get_argument('title', None) text = self.get_argument('text', None) slug = self.get_argument('slug', None) tags = self.get_argument('tags', None).lower() if new: if not text: self.redirect("/blog/new?title=" +tornado.escape.url_escape(title or "") +"&tags="+tornado.escape.url_escape(tags or "") +"&text_missing=true") return elif not title: self.redirect("/blog/new?text=" +tornado.escape.url_escape(text or "") +"&tags="+tornado.escape.url_escape(tags or "") +"&title_missing=true") return else: slug = slugify( title ) # creates something to be used as 'id' and part of the url for the post else: # edit post if not slug or slug=="undefined": raise tornado.web.HTTPError(400, "Post field slug missing") if not text: self.redirect("/blog/edit?title=" +tornado.escape.url_escape(title or "") +"&slug="+slug +"&tags="+tornado.escape.url_escape(tags or "") +"&text_missing=true") return elif not title: self.redirect("/blog/new?text=" +tornado.escape.url_escape(text or "") +"&slug="+slug +"&tags="+tornado.escape.url_escape(tags or "") +"&title_missing=true") return update = {} pubsubData = {} newSlug = slug if title: update['title'] = title if new or self.get_argument('change_slug', False): # change_slug is an extra option because you probably don't want to do this # by default as it breaks external links update['slug'] = slugify( title ) newSlug = update['slug'] pubsubData['title'] = title if text: update['text'] = text pubsubData['summary'] = excerpt( text ) if tags: update['tags'] = tags.split(" ") pubsubData['author'] = { 'name': self.settings["author_name"], 'email': self.settings["author_email"]} pubsubData['updated'] = datetime.datetime.utcnow().isoformat() + "Z" pubsubData['id'] = pubsubData['link'] = "http://%s/blog/%s"%(self.settings["domain"], newSlug) publish("blog", pubsubData, self.settings) # publish through xmpp pubsub db = self.settings["db"] if new: update['date'] = datetime.datetime.utcnow() db.posts.insert( update, callback=lambda response, error: self._on_edit(response, error, slug=slug)) else: db.posts.update( {'slug': slug}, { '$set': update }, callback=lambda response, error: self._on_edit(response, error, slug=newSlug))
def OnDictRequest(self, msg=None): pubsub.publish(pubsub.ALL_RINGTONE_INDEX, self._data[self.database_key].copy())
def OnListRequest(self, msg=None): l=[self._data['wallpaper-index'][x]['name'] \ for x in self._data['wallpaper-index']\ if self._data['wallpaper-index'][x].get('origin', None)!='video' ] l.sort() pubsub.publish(pubsub.ALL_WALLPAPERS, l)
def OnHyperlinkLeft(self, evt): if self.tab_index: pubsub.publish(pubsub.REQUEST_TAB_CHANGED, data=self.tab_index) def OnItemSelected(self, evt): if evt_handler: self.OnHyperlinkLeft(evt) evt_handler.process(self.name, evt.GetEventObject().client_data) def Set(self, data): data_len=len(data) if data_len>self.max_total_items: self._data=data[:self.max_items] self._data.append(self._last_item) data_len=self.max_total_items else: self._data=data for i in range(data_len): self._widgets[i].SetLabel(self._data[i].get(Today_Item_Name, ''), self._data[i].get(Today_Item_Data, None)) self._vbs.Show(i) for i in range(data_len, self.max_total_items): self._vbs.Hide(i) self._vbs.Layout() self.Fit() self.Refresh() def not_empty(self): return self._data class SectionHeader (aggr.SectionHeader) : default_width=10 default_height=10 def __init__(self, label): super(SectionHeader, self).__init__(label) self._items=[] def Add(self, item): self._items.append(item) def GetAllItems(self): return self._items def GetItems(self): l=[] for x in self._items: if x.not_empty(): l.append(x) x.Show() else: x.Hide() return l def GetItemSize(self): w=self.default_width h=self.default_height for e in self._items: w1,h1=e.GetSizeTuple() w=max(w, w1) h=max(h,h1) return (w,h) def not_empty(self): return self.GetItems() class TodayWidget (aggr.Display) : _section_names=('Today','This Week') _item_names=(({ 'name': Today_Group_Calendar, 'tab_index': Tab_Calendar }, { 'name': Today_Group_Todo, 'tab_index': Tab_Todo }, { 'name': Today_Group_Memo, 'tab_index': Tab_Memo }, { 'name': Today_Group_IncomingSMS, 'tab_index': Tab_SMS }, { 'name': Today_Group_IncomingCalls, 'tab_index': Tab_CallHistory }, { 'name': Today_Group_MissedCalls, 'tab_index': Tab_CallHistory }), ({ 'name': Today_Group_Calendar, 'tab_index': Tab_Calendar }, { 'name': Today_Group_Todo, 'tab_index': Tab_Todo } )) def __init__(self, mainwindow, parent): self._sections=[] super(TodayWidget, self).__init__(parent, self) self._main_window=mainwindow self._sections=[SectionHeader(s) for s in self._section_names] for i,group in enumerate(self._item_names): for name in group: w=GroupWidget(self, name) self._sections[i].Add(w) self.UpdateItems() BaseEvent.bind(self.OnNewData) pubsub.subscribe(self._OnMidnight, pubsub.MIDNIGHT) def GetSections(self): "Return a list of section headers" return [x for x in self._sections if x.not_empty()] def GetItemSize(self, sectionnumber, sectionheader): "Return (width, height of each item)" return sectionheader.GetItemSize() def GetItemsFromSection(self,sectionnumber,sectionheader): return sectionheader.GetItems() def _populate(self, data): section_name=data.section group_name=data.group for s in self._sections: if s.label!=section_name: continue for group in s.GetAllItems(): if group.name==group_name: group.Set(data.items) break break self.UpdateItems() self.Refresh() def OnNewData(self, msg=None): if msg is None: return self._populate(msg.data) def _OnMidnight(self, _): send_request_event()