Best JavaScript code snippet using wpt
popup_manager.py
Source:popup_manager.py
...29 self.signature_index = 030 self.current_parameter = 031 # Track current popup location to see if we only need to update the text32 self.current_location = None33 def queue_signature_popup(self, view):34 cursor = view.rowcol(view.sel()[0].begin())35 point = Location(cursor[0] + 1, cursor[1] + 1)36 filename = view.file_name()37 # Define a function to do the request and notify on completion38 def get_signature_data(on_done):39 # Issue 233: In the middle of an argument list, the popup40 # disappears after user enters a line-break then immediately types41 # one (or more) character.42 # This is because we only send one reload request after the43 # line-break and never send reload request after the other44 # character.45 # We fix this issue by making sure a reload request is always sent46 # before every signature help request.47 # Check if user has just quickly typed a line-break followed48 # with one (or more) character. If yes, send a reload request.49 last_command, args, repeat_times = view.command_history(0)50 if last_command == "insert":51 if len(args['characters']) > 1 and '\n' in args['characters']:52 reload_buffer(view)53 54 # Send a signagure_help request to server55 self.proxy.async_signature_help(filename, point, '', on_done)56 # Schedule the request57 self.scheduler.queue_request(get_signature_data,58 lambda resp: self.on_response(resp, view))59 def on_response(self, responseJson, view):60 # Needs to be set even if failed for on_close_popup to clear regions61 self.current_view = view62 if not responseJson["success"] or not responseJson["body"]:63 log.debug('No results for signature request')64 self.on_close_popup()65 return66 log.debug('Setting signature help data')67 self.current_view = view68 self.signature_help = responseJson["body"]69 self.signature_index = responseJson["body"]["selectedItemIndex"]70 self.current_parameter = responseJson["body"]["argumentIndex"]71 # Add a region to track the arg list as the user types72 # Needs to be adjusted to 0-based indexing73 arg_span = self.signature_help["applicableSpan"]74 span_start = view.text_point(75 arg_span["start"]["line"] - 1,76 arg_span["start"]["offset"] - 2)77 span_end = view.text_point(78 arg_span["end"]["line"] - 1,79 arg_span["end"]["offset"])80 arg_region = sublime.Region(span_start, span_end)81 view.add_regions('argSpan', [arg_region],82 flags=sublime.HIDDEN)83 # To view region, set to: scope='comments', flags=sublime.DRAW_EMPTY)84 self.display()85 def display(self):86 popup_parts = self.get_current_signature_parts()87 popup_text = PopupManager.html_template.substitute(popup_parts)88 log.debug('Displaying signature popup')89 arg_region = self.current_view.get_regions('argSpan')[0]90 location = arg_region.begin() # Default to start of arg list91 # If the cursor is not in the first line of the arg list, set the popup92 # location to first non-whitespace, or EOL, of the current line93 cursor_point = self.current_view.sel()[0].begin()94 opening_line = self.current_view.line(arg_region.begin())95 if(not opening_line.contains(cursor_point)):96 cursor_line_start = self.current_view.line(cursor_point).begin()97 location = self.current_view.find(98 r'\s*?(?=[\S\n\r]|$)',99 cursor_line_start100 ).end()101 # If the popup is currently visible and at the right location, then102 # call 'update' instead of 'show', else this can get in a loop when show103 # causes the old popup to be hidden (and on_hidden is called), as well104 # as causing some unnecessary UI flickering.105 if self.current_view.is_popup_visible() and self.current_location == location:106 self.current_view.update_popup(popup_text)107 else:108 self.current_location = location109 self.current_view.show_popup(110 popup_text,111 sublime.COOPERATE_WITH_AUTO_COMPLETE,112 on_navigate=self.on_navigate,113 on_hide=self.on_hidden,114 location=location,115 max_width=800)116 def move_next(self):117 if not self.signature_help:118 return119 self.signature_index += 1120 if self.signature_index >= len(self.signature_help["items"]):121 self.signature_index = len(self.signature_help["items"]) - 1122 self.display()123 def move_prev(self):124 if not self.signature_help:125 return126 self.signature_index -= 1127 if self.signature_index < 0:128 self.signature_index = 0129 self.display()130 def on_navigate(self, loc):131 # Clicked the overloads link. Dismiss this popup and show the panel132 view = self.current_view133 self.on_close_popup()134 view.run_command('typescript_signature_panel')135 def on_hidden(self):136 log.debug('In popup on_hidden handler')137 if not self.current_view:138 log.debug('No current view for popup session. Hiding popup')139 return140 # If we're still in the arg list, then redisplay141 cursor_region = self.current_view.sel()[0]142 arg_regions = self.current_view.get_regions('argSpan')143 if len(arg_regions):144 argSpan = self.current_view.get_regions('argSpan')[0]145 if argSpan.contains(cursor_region):146 log.debug('Was hidden while in region. Redisplaying')147 # Occurs on cursor movement. Rerun to redisplay popup.148 self.display()149 else:150 # Cleanup151 self.on_close_popup()152 def on_close_popup(self):153 """ Call whenever the view loses focus, of the region is exited """154 if self.current_view:155 self.current_view.erase_regions('argSpan')156 self.current_view.hide_popup()157 self.current_view = None158 self.signature_help = None159 def is_active(self):160 """ Return True if a current popup session is running """161 return True if self.current_view else False162 def signature_to_html(self, item):163 result = ""164 def html_escape(str):165 return str.replace('&', '&').replace(166 '<', '<').replace('>', ">")167 def normalize_style(name):168 if name in ['methodName']:169 return 'name'170 elif name in ['keyword', 'interfaceName']:...
scriptWindow.py
Source:scriptWindow.py
1import tkinter as tk2from tkinter import font as tkf3from tkinter import ttk4import PyInterpreter.PyInterpreter as pyi5import os6import time7import messagePopup8import scriptHelp9import bytes2String10win=None11send=None12receive=None13def close():14 #guiEnable()15 win.popupWait.destroy()16def received():17 rec = receive()18 print (f"Rec: {rec} of type {type(rec)}")19 if rec==None: rec==['']20 return rec21def show(rootWin,scriptpath,rmtSend,rmtReceive):22 global win,send,receive23 win=rootWin24 send=rmtSend25 receive=rmtReceive26 scriptHelp.init(win)27 scriptname=os.path.basename(scriptpath).split(".")[0]28 # construct dialog29 popupWait = tk.Toplevel(win)30 popupWait.transient(win) 31 popupWait.scriptname=scriptname32 popupWait.wm_title(f"Script - {scriptname}")33 #popupWait.resizable(False,False)34 popupWait.scriptpath=scriptpath35 win.popupWait=popupWait 36 backcolor=win["bg"]#"#DDDDDD"37 #popupWait.protocol("WM_DELETE_WINDOW", pass_WaitForScript) # custom function which sets winDestroyed so we can check state of win38 # header/message39 headerframe=tk.Frame(popupWait,background=backcolor)40 headerframe.pack(side=tk.TOP,fill='x',padx=(0,0),pady=(8,4))41 lb = tk.Label(headerframe, anchor='w',text='Status:')42 lb.pack(side=tk.LEFT,padx=8)43 popupWait.varInfo=tk.StringVar()44 popupWait.varInfo.set(f"Loaded '{scriptname}'")45 lbInfo = tk.Label(headerframe, anchor=tk.W,textvariable=popupWait.varInfo)46 lbInfo.pack(side=tk.LEFT,padx=8,fill=tk.X,expand=True)47 # resize grip48 resizeGrip=ttk.Sizegrip(popupWait,style='popupWait.TSizegrip')49 resizeGrip.place(rely=1.0, relx=1.0, x=0, y=0, anchor=tk.SE)50 # draw sep51 separator = ttk.Separator(popupWait,orient='horizontal').pack(side=tk.TOP,fill='x',pady=8)52 # footer53 footerframe=tk.Frame(popupWait,background=backcolor)54 footerframe.pack(side=tk.BOTTOM,fill='x',padx=(8,8),pady=(4,4))55 lb = tk.Label(footerframe, text='Delay')56 lb.pack(side=tk.LEFT)57 popupWait.varDelay=tk.StringVar()58 popupWait.delayList=("No delay","0.01 sec","0.1 sec","0.5 sec","1 sec","2 sec","5 sec")59 popupWait.delayTimes=(0,0.01,0.1,0.5,1.0,2.0,5.0)60 popupWait.varDelay.set('0.5 sec')61 ddDelay=tk.OptionMenu(footerframe,popupWait.varDelay,*popupWait.delayList)62 ddDelay.pack(side=tk.LEFT,padx=(3,0))63 ddDelay.configure(width=6)64 ddDelay.configure(relief=tk.FLAT)65 ddDelay.configure(bg='white')66 footerbgcolor,footersgcolor,footerfgcolor=backcolor,backcolor,'#000'67 ddDelay.configure(background=footerbgcolor,activebackground=footersgcolor,foreground=footerfgcolor,activeforeground=footerfgcolor,highlightbackground='red')68 ddDelay.configure(bd=3)69 ddDelay["menu"].configure(background=footerbgcolor,activebackground=footersgcolor,foreground=footerfgcolor,activeforeground=footerfgcolor)70 ddDelay["menu"].configure(relief=tk.FLAT)71 ddDelay.pack(side=tk.LEFT,padx=(3,0))72 ddDelay.configure(bd='0p')73 ddDelay.configure(highlightthickness=0)74 popupWait.varSkipVars=tk.BooleanVar(value=True)75 cbSkipVars=tk.Checkbutton(footerframe,text="Skip Vars:",variable=popupWait.varSkipVars)76 cbSkipVars.configure(background=footerbgcolor,activebackground=footersgcolor,fg=footerfgcolor,activeforeground=footerfgcolor,highlightbackground=footerbgcolor,selectcolor=footerbgcolor)77 cbSkipVars.pack(side=tk.LEFT)78 cbSkipVars.configure(relief=tk.FLAT)79 popupWait.cmdRun = tk.Button(footerframe, text="Run",command= process)80 popupWait.cmdRun.pack(side=tk.RIGHT)81 popupWait.cmdRun.configure(relief=tk.FLAT)82 popupWait.cmdSave = tk.Button(footerframe, text="Save",command= save)83 popupWait.cmdSave.pack(side=tk.RIGHT)84 popupWait.cmdSave.configure(relief=tk.FLAT)85 popupWait.cmdReload = tk.Button(footerframe, text="Reload",command= load)86 popupWait.cmdReload.pack(side=tk.RIGHT)87 popupWait.cmdReload.configure(relief=tk.FLAT)88 popupWait.cmdHelp = tk.Button(footerframe, text="Help",command= scriptHelp.show)89 popupWait.cmdHelp.pack(side=tk.RIGHT)90 popupWait.cmdHelp.configure(relief=tk.FLAT)91 # draw sep92 separator = ttk.Separator(popupWait,orient='horizontal').pack(side=tk.BOTTOM,fill='x',pady=(8,0))93 # tabs94 popupWait.tabs=ttk.Notebook(popupWait)95 popupWait.scriptTab=ttk.Frame(popupWait.tabs)96 popupWait.tabs.add(popupWait.scriptTab,text=" Script ")#,command=showScript)97 popupWait.errorsTab=ttk.Frame(popupWait.tabs)98 popupWait.tabs.add(popupWait.errorsTab,text=" Errors ")#,command=showErrors)99 popupWait.tabs.pack(side=tk.TOP, fill=tk.BOTH,expand=True,padx=(8,8),pady=(2,0))100 # script area101 #popupWait.varScript=tk.StringVar() #use textInput.get()102 popupWait.scrollText = tk.Scrollbar(popupWait.scriptTab)#popupWait)103 popupWait.scriptText=tk.Text(popupWait.scriptTab,bg='white')#popupWait,bg="white")104 popupWait.scrollText.pack(side=tk.RIGHT, fill=tk.Y,padx=(0,0),pady=(2,2))105 popupWait.scriptText.pack(expand=True,padx=(2,0),pady=(2,0),fill=tk.BOTH)106 popupWait.scrollText.config(command=popupWait.scriptText.yview)107 popupWait.scriptText.config(yscrollcommand=popupWait.scrollText.set)108 popupWait.scriptText.configure(wrap=tk.NONE) # needed for autoscroll (using .see) to function reliably109 popupWait.scriptText.configure(relief=tk.SOLID)110 popupWait.scrollText.configure(relief=tk.FLAT)111 popupWait.scrollText.configure(borderwidth=0)112 popupWait.scrollText.configure(elementborderwidth=1)113 popupWait.scrollText.configure(width=14)114 #popupWait.scrollText.configure(trough=backcolor)115 popupWait.scriptText.configure(wrap=tk.NONE)116 popupWait.scriptText.configure(font= tkf.Font(family='Terminal', weight = 'normal', size = 9)) #TkFixedFont117 popupWait.scriptText.oldlinenr=0118 # error area119 #popupWait.varScript=tk.StringVar() #use textInput.get()120 popupWait.scrollErrors = tk.Scrollbar(popupWait.errorsTab)#popupWait)121 popupWait.scriptErrors=tk.Text(popupWait.errorsTab,bg='white')#popupWait,bg="white")122 popupWait.scrollErrors.pack(side=tk.RIGHT, fill=tk.Y,padx=(0,0),pady=(2,2))123 popupWait.scriptErrors.pack(expand=True,padx=(2,0),pady=(2,0),fill=tk.BOTH)124 popupWait.scrollErrors.config(command=popupWait.scriptErrors.yview)125 popupWait.scriptErrors.config(yscrollcommand=popupWait.scrollErrors.set)126 popupWait.scriptErrors.configure(wrap=tk.NONE) # needed for autoscroll (using .see) to function reliably127 popupWait.scriptErrors.configure(relief=tk.SOLID)128 popupWait.scrollErrors.configure(relief=tk.FLAT)129 popupWait.scrollErrors.configure(borderwidth=0)130 popupWait.scrollErrors.configure(elementborderwidth=1)131 popupWait.scrollErrors.configure(width=14)132 #popupWait.scrollText.configure(trough=backcolor)133 popupWait.scriptErrors.configure(wrap=tk.NONE)134 popupWait.scriptErrors.configure(font= tkf.Font(family='Terminal', weight = 'normal', size = 9)) #TkFixedFont135 # show script136 load()137 # bindings and show138 popupWait.protocol("WM_DELETE_WINDOW", close) # custom function which sets winDestroyed so we can check state of win139 #guiDisable()140 popupWait.update()141 popupWait.grab_set() # to redirect all user input to this popup142def save(event=None):143 scriptpath=win.popupWait.scriptpath144 scriptlines=win.popupWait.scriptText.get(0.0,tk.END)145 with open(win.popupWait.scriptpath, "w") as writer: # open file146 writer.write(scriptlines)147def load(event=None):148 win.popupWait.scriptText.delete(0.0,tk.END)149 with open(win.popupWait.scriptpath, "r") as reader: # open file150 scriptlines=reader.readlines() # read all lines151 for nr,lineStr in enumerate(scriptlines):152 tagname=f"{nr}"153 taglist=(tagname,)154 win.popupWait.scriptText.insert(tk.END, lineStr,taglist) 155 #print(f"scripText append:{nr} {lineStr}")156def showScriptLine(linenr):157 popupWait=win.popupWait158 popupWait.scriptText.tag_config(f"{popupWait.scriptText.oldlinenr}",background='white')159 popupWait.scriptText.tag_config(f"{linenr}",background='yellow')160 popupWait.scriptText.see(float(linenr+2))161 popupWait.update()162 popupWait.scriptText.oldlinenr=linenr163isProcessingScript=False164def process(event=None):165 global isProcessingScript166 popupWait=win.popupWait167 # set flag168 isProcessingScript = not isProcessingScript169 # check if user interupted script170 if not isProcessingScript: 171 pyi.stopScript()172 return173 #disable yellow cursor from previous runs174 popupWait.scriptText.tag_config(f"{popupWait.scriptText.oldlinenr}",background='white')175 popupWait.scriptText.oldlinenr=0176 #read script (can be edited by user) 177 scriptpath=popupWait.scriptpath178 scriptlines=popupWait.scriptText.get(0.0,tk.END).split('\n')179 pyi.setScript(scriptlines)180 #get delay time between commands181 delayIndex = popupWait.delayList.index(popupWait.varDelay.get())182 delayTime = popupWait.delayTimes[delayIndex]183 #setup script environment184 # callback handler so we can follow which line the script is running185 pyi.setCallbackHandler(showScriptLine)186 #rename run button so we can use it as stop button187 popupWait.cmdRun.configure(text="Stop")188 # error handler should output to striptErrors widget instead of console189 def errhndlr(errStack):190 win.popupWait.scriptErrors.delete(0.0,tk.END)191 win.popupWait.scriptErrors.insert(tk.END, '\n\n'.join(errStack)) 192 win.popupWait.tabs.select(win.popupWait.errorsTab) 193 msgbox=messagePopup.show(win,type="error",title="Script failed", message=f"Errors in script '{popupWait.scriptname}'!")194 pyi.setErrorHandler(errhndlr)195 # reroute print to infobos196 def print2InfoBox(msg):197 if isinstance(msg,bytes): 198 popupWait.varInfo.set(bytes2String.raw(msg).strip())199 elif isinstance(msg,str): 200 popupWait.varInfo.set(msg.strip())201 else: 202 popupWait.varInfo.set(msg)203 pyi.addSystemFunction('print',print2InfoBox,[[str,int,bool,float,bytes],])204 def printAscii2InfoBox(msg):205 popupWait.varInfo.set(bytes2String.ascii(msg).strip())206 pyi.addSystemFunction('printa',printAscii2InfoBox,[[bytes],])207 def printHex2InfoBox(msg): 208 popupWait.varInfo.set(bytes2String.hex(msg).strip())209 pyi.addSystemFunction('printh',printHex2InfoBox,[[bytes],])210 def printDec2InfoBox(msg):211 popupWait.varInfo.set(bytes2String.dec(msg).strip())212 pyi.addSystemFunction('printd',printDec2InfoBox,[[bytes],])213 def printRaw2InfoBox(msg):214 popupWait.varInfo.set(f"{msg}")215 pyi.addSystemFunction('printr',printRaw2InfoBox,[[bytes],])216 # add send (over serial) command217 pyi.addSystemFunction('send',send,[[str,],])218 # add received var (to be updated each x msecs)219 pyi.importSystemFunction(pyi,__name__,"received")220 #run script221 scriptStart=time.time()222 runSuccess=pyi.runScript(delaytime=delayTime,skipVarDelay=popupWait.varSkipVars.get())223 scriptDuration=time.time()-scriptStart224 if runSuccess and isProcessingScript:225 msgbox=messagePopup.show(win,type="info",title="Script finished", message=f"Script '{popupWait.scriptname}' finished in {scriptDuration:.4f} seconds!")226 if runSuccess and not isProcessingScript:227 msgbox=messagePopup.show(win,type="warning",title="Script stopped", message=f"Script '{popupWait.scriptname}' interupted after {scriptDuration:.4f} seconds!")228 # set flag 229 isProcessingScript=False230 #rename stop button so we can use it as run button...
gesturedatabase.py
Source:gesturedatabase.py
1__all__ = ('GestureDatabase', 'GestureDatabaseItem')2from kivy.clock import Clock3from kivy.lang import Builder4from kivy.properties import NumericProperty, StringProperty5from kivy.properties import ListProperty, ObjectProperty6from kivy.uix.gridlayout import GridLayout7from kivy.uix.floatlayout import FloatLayout8from kivy.uix.popup import Popup9from kivy.graphics import Rectangle, Color10from kivy.multistroke import Recognizer11# local libraries12from helpers import InformationPopup13Builder.load_file('gesturedatabase.kv')14class GestureExportPopup(Popup):15 pass16class GestureImportPopup(Popup):17 pass18class GestureDatabaseItem(FloatLayout):19 name = StringProperty('(no name)')20 template_count = NumericProperty(0)21 gesture_list = ListProperty([])22 def __init__(self, **kwargs):23 super(GestureDatabaseItem, self).__init__(**kwargs)24 self.rect = None25 self._draw_trigger = Clock.create_trigger(self.draw_item, 0)26 self.update_template_count()27 self.bind(gesture_list=self.update_template_count)28 self.register_event_type('on_select')29 self.register_event_type('on_deselect')30 def toggle_selected(self, *l):31 self._draw_rect(clear=True)32 if self.ids.select.state == 'down':33 self.dispatch('on_select')34 self.ids.select.text = 'Deselect'35 else:36 self.dispatch('on_deselect')37 self.ids.select.text = 'Select'38 def update_template_count(self, *l):39 tpl_count = 040 for g in self.gesture_list:41 tpl_count += len(g.templates)42 self.template_count = tpl_count43 def draw_item(self, *l):44 self.ids.namelbl.pos = self.pos45 self.ids.namelbl.y += 9046 self.ids.stats.pos = self.pos47 self.ids.stats.y += 4048 self.ids.select.pos = self.pos49 self._draw_rect()50 def _draw_rect(self, clear=False, *l):51 col = self.ids.select.state == 'down' and 1 or .252 with self.canvas:53 Color(col, 0, 0, .15)54 if self.rect or clear:55 self.canvas.remove(self.rect)56 self.rect = Rectangle(size=self.size, pos=self.pos)57 def on_select(*l):58 pass59 def on_deselect(*l):60 pass61class GestureDatabase(GridLayout):62 selected_count = NumericProperty(0)63 recognizer = ObjectProperty(None)64 export_popup = ObjectProperty(GestureExportPopup())65 import_popup = ObjectProperty(GestureImportPopup())66 info_popup = ObjectProperty(InformationPopup())67 def __init__(self, **kwargs):68 super(GestureDatabase, self).__init__(**kwargs)69 self.redraw_all = Clock.create_trigger(self._redraw_gesture_list, 0)70 self.export_popup.ids.save_btn.bind(on_press=self.perform_export)71 self.import_popup.ids.filechooser.bind(on_submit=self.perform_import)72 def import_gdb(self):73 self.gdict = {}74 for gesture in self.recognizer.db:75 if gesture.name not in self.gdict:76 self.gdict[gesture.name] = []77 self.gdict[gesture.name].append(gesture)78 self.selected_count = 079 self.ids.gesture_list.clear_widgets()80 for k in sorted(self.gdict, key=lambda n: n.lower()):81 gitem = GestureDatabaseItem(name=k, gesture_list=self.gdict[k])82 gitem.bind(on_select=self.select_item)83 gitem.bind(on_deselect=self.deselect_item)84 self.ids.gesture_list.add_widget(gitem)85 def select_item(self, *l):86 self.selected_count += 187 def deselect_item(self, *l):88 self.selected_count -= 189 def mass_select(self, *l):90 if self.selected_count:91 for i in self.ids.gesture_list.children:92 if i.ids.select.state == 'down':93 i.ids.select.state = 'normal'94 i.draw_item()95 else:96 for i in self.ids.gesture_list.children:97 if i.ids.select.state == 'normal':98 i.ids.select.state = 'down'99 i.draw_item()100 def unload_gestures(self, *l):101 if not self.selected_count:102 self.recognizer.db = []103 self.ids.gesture_list.clear_widgets()104 self.selected_count = 0105 return106 for i in self.ids.gesture_list.children[:]:107 if i.ids.select.state == 'down':108 self.selected_count -= 1109 for g in i.gesture_list:110 # if g in self.recognizer.db: # not needed, for testing111 self.recognizer.db.remove(g)112 self.ids.gesture_list.remove_widget(i)113 def perform_export(self, *l):114 path = self.export_popup.ids.filename.text115 if not path:116 self.export_popup.dismiss()117 self.info_popup.text = 'Missing filename'118 self.info_popup.open()119 return120 elif not path.lower().endswith('.kg'):121 path += '.kg'122 self.save_selection_to_file(path)123 self.export_popup.dismiss()124 self.info_popup.text = 'Gestures exported!'125 self.info_popup.open()126 def perform_import(self, filechooser, *l):127 count = len(self.recognizer.db)128 for f in filechooser.selection:129 self.recognizer.import_gesture(filename=f)130 self.import_gdb()131 self.info_popup.text = ("Imported %d gestures.\n" %132 (len(self.recognizer.db) - count))133 self.import_popup.dismiss()134 self.info_popup.open()135 def save_selection_to_file(self, filename, *l):136 if not self.selected_count:137 self.recognizer.export_gesture(filename=filename)138 else:139 tmpgdb = Recognizer()140 for i in self.ids.gesture_list.children:141 if i.ids.select.state == 'down':142 for g in i.gesture_list:143 tmpgdb.db.append(g)144 tmpgdb.export_gesture(filename=filename)145 def _redraw_gesture_list(self, *l):146 for child in self.ids.gesture_list.children:...
PopupMenu.py
Source:PopupMenu.py
1import wx2import images3#----------------------------------------------------------------------4text = """\5Right-click on any bare area of this panel (or Ctrl-click on the Mac)6to show a popup menu. Then look at the code for this sample. Notice7how the PopupMenu method is similar to the ShowModal method of a8wx.Dialog in that it doesn't return until the popup menu has been9dismissed. The event handlers for the popup menu items can either be10attached to the menu itself, or to the window that invokes PopupMenu.11"""12#----------------------------------------------------------------------13class TestPanel(wx.Panel):14 def __init__(self, parent, log):15 self.log = log16 wx.Panel.__init__(self, parent, -1)17 box = wx.BoxSizer(wx.VERTICAL)18 # Make and layout the controls19 fs = self.GetFont().GetPointSize()20 bf = wx.Font(fs+4, wx.SWISS, wx.NORMAL, wx.BOLD)21 nf = wx.Font(fs+2, wx.SWISS, wx.NORMAL, wx.NORMAL)22 t = wx.StaticText(self, -1, "PopupMenu")23 t.SetFont(bf)24 box.Add(t, 0, wx.CENTER|wx.ALL, 5)25 box.Add(wx.StaticLine(self, -1), 0, wx.EXPAND)26 box.Add((10,20))27 t = wx.StaticText(self, -1, text)28 t.SetFont(nf)29 box.Add(t, 0, wx.CENTER|wx.ALL, 5)30 t.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)31 self.SetSizer(box)32 self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)33 def OnContextMenu(self, event):34 self.log.WriteText("OnContextMenu\n")35 # only do this part the first time so the events are only bound once36 #37 # Yet another anternate way to do IDs. Some prefer them up top to38 # avoid clutter, some prefer them close to the object of interest39 # for clarity. 40 if not hasattr(self, "popupID1"):41 self.popupID1 = wx.NewId()42 self.popupID2 = wx.NewId()43 self.popupID3 = wx.NewId()44 self.popupID4 = wx.NewId()45 self.popupID5 = wx.NewId()46 self.popupID6 = wx.NewId()47 self.popupID7 = wx.NewId()48 self.popupID8 = wx.NewId()49 self.popupID9 = wx.NewId()50 self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1)51 self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2)52 self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3)53 self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4)54 self.Bind(wx.EVT_MENU, self.OnPopupFive, id=self.popupID5)55 self.Bind(wx.EVT_MENU, self.OnPopupSix, id=self.popupID6)56 self.Bind(wx.EVT_MENU, self.OnPopupSeven, id=self.popupID7)57 self.Bind(wx.EVT_MENU, self.OnPopupEight, id=self.popupID8)58 self.Bind(wx.EVT_MENU, self.OnPopupNine, id=self.popupID9)59 # make a menu60 menu = wx.Menu()61 # Show how to put an icon in the menu62 item = wx.MenuItem(menu, self.popupID1,"One")63 bmp = images.Smiles.GetBitmap()64 item.SetBitmap(bmp)65 menu.AppendItem(item)66 # add some other items67 menu.Append(self.popupID2, "Two")68 menu.Append(self.popupID3, "Three")69 menu.Append(self.popupID4, "Four")70 menu.Append(self.popupID5, "Five")71 menu.Append(self.popupID6, "Six")72 # make a submenu73 sm = wx.Menu()74 sm.Append(self.popupID8, "sub item 1")75 sm.Append(self.popupID9, "sub item 1")76 menu.AppendMenu(self.popupID7, "Test Submenu", sm)77 # Popup the menu. If an item is selected then its handler78 # will be called before PopupMenu returns.79 self.PopupMenu(menu)80 menu.Destroy()81 def OnPopupOne(self, event):82 self.log.WriteText("Popup one\n")83 def OnPopupTwo(self, event):84 self.log.WriteText("Popup two\n")85 def OnPopupThree(self, event):86 self.log.WriteText("Popup three\n")87 def OnPopupFour(self, event):88 self.log.WriteText("Popup four\n")89 def OnPopupFive(self, event):90 self.log.WriteText("Popup five\n")91 def OnPopupSix(self, event):92 self.log.WriteText("Popup six\n")93 def OnPopupSeven(self, event):94 self.log.WriteText("Popup seven\n")95 def OnPopupEight(self, event):96 self.log.WriteText("Popup eight\n")97 def OnPopupNine(self, event):98 self.log.WriteText("Popup nine\n")99#----------------------------------------------------------------------100def runTest(frame, nb, log):101 win = TestPanel(nb, log)102 return win103#----------------------------------------------------------------------104overview = """<html><body>105<h2><center>PopupMenu</center></h2>106""" + text + """107</body></html>108"""109if __name__ == '__main__':110 import sys,os111 import run...
settings.py
Source:settings.py
1from kivy.app import App2from kivy.uix.button import Button3from kivy.uix.boxlayout import BoxLayout4from kivy.uix.label import Label5from kivy.uix.popup import Popup6from kivy.uix.settings import (SettingsWithSidebar,7 SettingsWithSpinner,8 SettingsWithTabbedPanel)9from kivy.properties import OptionProperty, ObjectProperty10class SettingsApp(App):11 display_type = OptionProperty('normal', options=['normal', 'popup'])12 settings_popup = ObjectProperty(None, allownone=True)13 def build(self):14 paneltype = Label(text='What kind of settings panel to use?')15 sidebar_button = Button(text='Sidebar')16 sidebar_button.bind(on_press=lambda j: self.set_settings_cls(17 SettingsWithSidebar))18 spinner_button = Button(text='Spinner')19 spinner_button.bind(on_press=lambda j: self.set_settings_cls(20 SettingsWithSpinner))21 tabbed_button = Button(text='TabbedPanel')22 tabbed_button.bind(on_press=lambda j: self.set_settings_cls(23 SettingsWithTabbedPanel))24 buttons = BoxLayout(orientation='horizontal')25 buttons.add_widget(sidebar_button)26 buttons.add_widget(spinner_button)27 buttons.add_widget(tabbed_button)28 displaytype = Label(text='How to display the settings?')29 display_buttons = BoxLayout(orientation='horizontal')30 onwin_button = Button(text='on window')31 onwin_button.bind(on_press=lambda j: self.set_display_type('normal'))32 popup_button = Button(text='in a popup')33 popup_button.bind(on_press=lambda j: self.set_display_type('popup'))34 display_buttons.add_widget(onwin_button)35 display_buttons.add_widget(popup_button)36 instruction = Label(text='Click to open the settings panel:')37 settings_button = Button(text='Open settings')38 settings_button.bind(on_press=self.open_settings)39 layout = BoxLayout(orientation='vertical')40 layout.add_widget(paneltype)41 layout.add_widget(buttons)42 layout.add_widget(displaytype)43 layout.add_widget(display_buttons)44 layout.add_widget(instruction)45 layout.add_widget(settings_button)46 return layout47 def on_settings_cls(self, *args):48 self.destroy_settings()49 def set_settings_cls(self, panel_type):50 self.settings_cls = panel_type51 def set_display_type(self, display_type):52 self.destroy_settings()53 self.display_type = display_type54 def display_settings(self, settings):55 if self.display_type == 'popup':56 p = self.settings_popup57 if p is None:58 self.settings_popup = p = Popup(content=settings,59 title='Settings',60 size_hint=(0.8, 0.8))61 if p.content is not settings:62 p.content = settings63 p.open()64 else:65 super(SettingsApp, self).display_settings(settings)66 def close_settings(self, *args):67 if self.display_type == 'popup':68 p = self.settings_popup69 if p is not None:70 p.dismiss()71 else:72 super(SettingsApp, self).close_settings()73if __name__ == '__main__':...
main.py
Source:main.py
...14class Root(FloatLayout):15 loadfile = ObjectProperty(None)16 savefile = ObjectProperty(None)17 text_input = ObjectProperty(None)18 def dismiss_popup(self):19 self._popup.dismiss()20 def show_load(self):21 content = LoadDialog(load=self.load, cancel=self.dismiss_popup)22 self._popup = Popup(title="Load file", content=content,23 size_hint=(0.9, 0.9))24 self._popup.open()25 def show_save(self):26 content = SaveDialog(save=self.save, cancel=self.dismiss_popup)27 self._popup = Popup(title="Save file", content=content,28 size_hint=(0.9, 0.9))29 self._popup.open()30 def load(self, path, filename):31 with open(os.path.join(path, filename[0])) as stream:32 self.text_input.text = stream.read()33 self.dismiss_popup()34 def save(self, path, filename):35 with open(os.path.join(path, filename), 'w') as stream:36 stream.write(self.text_input.text)37 self.dismiss_popup()38class Editor(App):39 pass40Factory.register('Root', cls=Root)41Factory.register('LoadDialog', cls=LoadDialog)42Factory.register('SaveDialog', cls=SaveDialog)43if __name__ == '__main__':...
helpers.py
Source:helpers.py
1__all__ = ('InformationPopup', )2from kivy.uix.popup import Popup3from kivy.properties import StringProperty4from kivy.factory import Factory5from kivy.lang import Builder6from kivy.clock import Clock7Builder.load_string('''8<InformationPopup>:9 auto_dismiss: True10 size_hint: None, None11 size: 400, 20012 on_open: root.dismiss_trigger()13 title: root.title14 Label:15 text: root.text16''')17class InformationPopup(Popup):18 title = StringProperty('Information')19 text = StringProperty('')20 def __init__(self, time=1.5, **kwargs):21 super(InformationPopup, self).__init__(**kwargs)22 self.dismiss_trigger = Clock.create_trigger(self.dismiss, time)...
popup_with_kv.py
Source:popup_with_kv.py
...19class TestApp(App):20 def build(self):21 b = Button(on_press=self.show_popup, text="Show Popup")22 return b23 def show_popup(self, b):24 p = CustomPopup()25 p.open()...
Using AI Code Generation
1var wptools = require('wptools');2var options = {3}4wptools.get('Barack Obama', options, function(err, resp) {5 console.log(resp);6});7var wptools = require('wptools');8var options = {9}10wptools.get('Barack Obama', options, function(err, resp) {11 console.log(resp);12});
Using AI Code Generation
1var wptools = require('wptools');2var page = wptools.page('Albert Einstein');3page.get(function(err, data) {4 console.log(data);5});6### `wptools.page(page[, options])`
Using AI Code Generation
1var wptools = require('wptools');2var popup = wptools.popup('Albert Einstein');3popup.then(function(result) {4 console.log(result);5});6 wptools.popup('Albert Einstein').then(function(result) {7 console.log(result);8 });9### wptools.page(name, [options])
Using AI Code Generation
1const wptools = require('wptools');2(async function() {3 const page = await wptools.page('Albert Einstein').get();4 console.log(await page.popup('birth_place'));5})();6const wptools = require('wptools');7(async function() {8 const page = await wptools.page('Albert Einstein').get();9 console.log(await page.popup('birth_place'));10})();11const wptools = require('wptools');12(async function() {13 const page = await wptools.page('Albert Einstein').get();14 console.log(await page.popup('birth_place'));15})();16const wptools = require('wptools');17(async function() {18 const page = await wptools.page('Albert Einstein').get();19 console.log(await page.popup('birth_place'));20})();21const wptools = require('wptools');22(async function() {23 const page = await wptools.page('Albert Einstein').get();24 console.log(await page.popup('birth_place'));25})();26const wptools = require('wptools');27(async function() {28 const page = await wptools.page('Albert Einstein').get();29 console.log(await page.popup('birth_place'));30})();31const wptools = require('wptools');32(async function() {33 const page = await wptools.page('Albert Einstein').get();34 console.log(await page.popup('birth_place'));35})();36const wptools = require('wptools');37(async function() {38 const page = await wptools.page('Albert Einstein').get();39 console.log(await page.popup('birth_place'));40})();
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var wpt = new WebPageTest(options);5wpt.runTest(testUrl, function(err, data) {6 if (err) return console.log(err);7 console.log('Test status: ' + data.statusText);8 console.log('Test ID: ' + data.data.testId);9 console.log('Test URL: ' + data.data.summary);10 console.log('Test results: ' + data.data.userUrl);11 console.log('Test results: ' + data.data.jsonUrl);12 console.log('Test results: ' + data.data.xmlUrl);13 console.log('Test results: ' + data.data.csvUrl);14});15var wpt = require('webpagetest');16var options = {17};18var wpt = new WebPageTest(options);19wpt.runTest(testUrl, function(err, data) {20 if (err) return console.log(err);21 console.log('Test status: ' + data.statusText);22 console.log('Test ID: ' + data.data.testId);23 console.log('Test URL: ' + data.data.summary);24 console.log('Test results: ' + data.data.userUrl);25 console.log('Test results: ' + data.data.jsonUrl);26 console.log('Test results: ' + data.data.xmlUrl);27 console.log('Test results: ' + data.data.csvUrl);28});29var wpt = require('webpagetest');30var options = {31};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!