async def handler(agent, chat, message, follower, **scope): follower_state = await scope["db_client"].get_follower_state( follower_id=follower.id) if follower_state is None: follower_state = await scope["db_client"].create_follower_state( follower=follower) data = json.loads(follower_state.data) dialog = Dialog(state=follower_state.state) dialog.handle(text=message.text, data=data) await scope["db_client"].update_follower_state( follower_state=follower_state, state=dialog.state, data=dialog.data, ) keyboard = None if dialog.ANSWERS[dialog.state]: keyboard = TelegramKeyboard( buttons=([answer] for answer in dialog.ANSWERS[dialog.state]), resize=True, one_time=True, ) await agent.a_send_message(chat=chat, text=dialog.answer, keyboard=keyboard)
def edit_word(self, widget): # get selected row store, iter_list = self.list.get_selection().get_selected() pk = store[iter_list][0] record = Word.retrieve_by_id(pk) # show dialog and get button clicked code dialog = Dialog(self, record.word, record.translation) response = dialog.run() dialog.destroy() if response != Gtk.ResponseType.OK: return # get entered word & translation word = dialog.word.strip() translation = dialog.translation.strip() if word == '' or translation == '': return # update database field according to given column Word.update_by_id(pk, word, translation) # update edited list row store[iter_list][1] = word store[iter_list][2] = translation
def add_word(self, widget): # show dialog and get button clicked code dialog = Dialog(self) response = dialog.run() dialog.destroy() if response != Gtk.ResponseType.OK: return # get entered word & translation word = dialog.word.strip() translation = dialog.translation.strip() if word == '' or translation == '': return # insert new word entered in database record = Word(word=word, translation=translation, date=datetime.now()) pk = Word.insert(record) record = Word.retrieve_by_id(pk) # add inserted word to list view store = self.list.get_model() store.append([ record.id, record.word, record.translation, record.date.strftime("%Y-%m-%d %H:%M:%S") ])
def createnewsubentry(self, event=None): """ Invoked when the button with same text is pressed. Implemented using a the very generic dialog box. This takes a "fieldvars" argument. This is an ordered dict of: key : [ Variable, description, kwargs ] The kwargs dict is passed on to the constructor and can be used to e.g. change states of input widgets. The default Dialog class will make a two-column grid, where the left column in each row is a label with the description and the right column is the input/control widget. The input widgets will adapt to the variable type: Checkboxes will be used for tk.BooleanVars. The dialog will additionally try to adapt the layout. For example, for booleanvars displayed by checkboxes, the grid can fit two variables side-by-side, one in each column. The results of the user input after clicking 'ok' can be read in two ways, either a) Using the tk.Variables in the fieldvars dict (requires you to use tk Variables) b) Using the values in dialog.result, which are updated when the user presses 'ok'. Note that dialog.result is a dict of key: value pairs, where the value is obtained by invoking tkVar.get(). The key is the same as that of the fieldvars input. """ idx = self.Experiment.getNewSubentryIdx() props = dict(self.Experiment.Props) props['subentry_idx'] = idx props['subentry_titledesc'] = "" props['subentry_date'] = "{:%Y%m%d}".format(datetime.now()) props['makefolder'] = True props['makewikientry'] = True #items are: variable, description, entry widget, kwargs for widget entries = ( ('expid', "Experiment ID"), ('subentry_idx', "Subentry index"), ('subentry_titledesc', "Subentry title desc"), ('makefolder', "Make local folder"), ('makewikientry', "Make wiki entry"), ('subentry_date', "Subentry date") ) fieldvars = OrderedDict( (key, [props[key], desc, dict()] ) for key, desc in entries ) for items in fieldvars.values(): if isinstance(items[0], bool): items[0] = tk.BooleanVar(value=items[0]) else: items[0] = tk.StringVar(value=items[0]) fieldvars['expid'][2]['state'] = 'disabled' # This is the third element, the dict. dia = Dialog(self, "Create new subentry", fieldvars) logger.debug("Dialog result: %s", dia.result) if dia.result: # will be None if the 'ok' button was not pressed. dia.result.pop('expid') self.Experiment.addNewSubentry(**dia.result) # I'm not sure how much clean-up should be done? Do I need to e.g. destroy the dialog completely when I'm done? self.Parent.updatewidgets() # will also invoke self.updatewidgets()
def take_screenshot(self): try: os.mkdir(os.path.join(directories.getCacheDir(), "screenshots")) except OSError: pass screenshot_name = os.path.join(directories.getCacheDir(), "screenshots", time.strftime("%Y-%m-%d (%I-%M-%S-%p)")+".png") pygame.image.save(pygame.display.get_surface(), screenshot_name) self.diag = Dialog() lbl = Label(_("Screenshot taken and saved as '%s'")%screenshot_name, doNotTranslate=True) folderBtn = Button("Open Folder", action=self.open_screenshots_folder) btn = Button("Ok", action=self.screenshot_notify) buttonsRow = Row((btn,folderBtn)) col = Column((lbl,buttonsRow)) self.diag.add(col) self.diag.shrink_wrap() self.diag.present()
def test_dialog(state, data, text, expected): dialog = Dialog(state=state) dialog.handle(text=text, data=data) assert dialog.state is expected
def main(): if sys.version_info[0] < 3: # Py2-vs-Py3: # redirecting output to a file can cause unicode problems # read: https://stackoverflow.com/questions/5530708/ # To fix it either run the scripts as: PYTHONIOENCODING=utf-8 python TrezorSymmetricFileEncryption.py # or add the following line of code. # Only shows up in python2 TrezorSymmetricFileEncryption.py >> log scenarios # Exception: 'ascii' codec can't encode characters in position 10-13: ordinal not in range(128) sys.stdout = codecs.getwriter('utf-8')(sys.stdout) app = QApplication(sys.argv) if app is None: # just to get rid f the linter warning on above line print("Critical error: Qt cannot be initialized.") sets = settings.Settings() # initialize settings # parse command line args = settings.Args(sets) args.parseArgs(sys.argv[1:]) trezor = trezor_app_generic.setupTrezor(sets.TArg, sets.mlogger) # trezor.clear_session() ## not needed trezor.prefillReadpinfromstdin(sets.RArg) trezor.prefillReadpassphrasefromstdin(sets.AArg) if sets.PArg is None: trezor.prefillPassphrase(u'') else: trezor.prefillPassphrase(sets.PArg) # if everything is specified in the command line then do not call the GUI if ((sets.PArg is None) or (len(sets.inputFiles) <= 0)) and (not sets.TArg): dialog = Dialog(trezor, sets) sets.mlogger.setQtextbrowser(dialog.textBrowser) sets.mlogger.setQtextheader(dialog.descrHeader()) sets.mlogger.setQtextcontent(dialog.descrContent()) sets.mlogger.setQtexttrailer(dialog.descrTrailer()) else: sets.mlogger.log( "Everything was specified or --terminal was set, " "hence the GUI will not be called.", logging.INFO, u"Arguments") sets.mlogger.log("Trezor label: %s" % trezor.features.label, logging.INFO, "Trezor IO") sets.mlogger.log( "For each operation click 'Confirm' on Trezor " "to give permission.", logging.INFO, "Trezor IO") fileMap = FileMap(trezor, sets) if ((sets.PArg is None) or (len(sets.inputFiles) <= 0)) and (not sets.TArg): # something was not specified, so we call the GUI # or user wants GUI, so we call the GUI dialog.setFileMap(fileMap) dialog.setVersion(basics.VERSION_STR) showGui(trezor, dialog, sets) else: useTerminal(fileMap, sets) # cleanup sets.mlogger.log("Cleaning up before shutting down.", logging.DEBUG, "Info") trezor.close()
# "action": func, "sub": "Third_level" } } } }) Dialog({ 'add_service': { 'title': "Adding Web Service dialog", 'questions': { 1: { 'ask': "Input Service name and press Enter", 'condition': "Second_level" }, 2: { 'ask': "Input Service URL and press Enter" }, 3: { 'ask': "Input Service description and press Enter" } } } }) Dialog({ 'add_person': { 'title': "Adding Person dialog", 'questions': { 1: { 'ask': "Input First Name and press Enter", 'condition': "Second_level"