def main(): # Ask the user for the plugins directory dir, ok = macfs.GetDirectory('Where is the PlugIns folder?') if not ok: sys.exit(0) os.chdir(dir.as_pathname()) # Remove old .slb aliases and collect a list of .slb files if EasyDialogs.AskYesNoCancel('Proceed with removing old aliases?') <= 0: sys.exit(0) LibFiles = [] allfiles = os.listdir(':') for f in allfiles: if f[-4:] == '.slb': finfo = macfs.FSSpec(f).GetFInfo() if finfo.Flags & 0x8000: os.unlink(f) else: LibFiles.append(f) print LibFiles # Create the new aliases. if EasyDialogs.AskYesNoCancel('Proceed with creating new ones?') <= 0: sys.exit(0) for dst, src in goals: if src in LibFiles: macostools.mkalias(src, dst) else: EasyDialogs.Message(dst + ' not created: ' + src + ' not found') EasyDialogs.Message('All done!')
def _test(): import EasyDialogs print 'Original findertools functionality test...' print 'Testing launch...' pathname = EasyDialogs.AskFileForOpen('File to launch:') if pathname: result = launch(pathname) if result: print 'Result: ', result print 'Press return-', sys.stdin.readline() print 'Testing print...' pathname = EasyDialogs.AskFileForOpen('File to print:') if pathname: result = Print(pathname) if result: print 'Result: ', result print 'Press return-', sys.stdin.readline() print 'Testing copy...' pathname = EasyDialogs.AskFileForOpen('File to copy:') if pathname: destdir = EasyDialogs.AskFolder('Destination:') if destdir: result = copy(pathname, destdir) if result: print 'Result:', result print 'Press return-', sys.stdin.readline() print 'Testing move...' pathname = EasyDialogs.AskFileForOpen('File to move:') if pathname: destdir = EasyDialogs.AskFolder('Destination:') if destdir: result = move(pathname, destdir) if result: print 'Result:', result print 'Press return-', sys.stdin.readline() print 'Testing sleep...' if EasyDialogs.AskYesNoCancel('Sleep?') > 0: result = sleep() if result: print 'Result:', result print 'Press return-', sys.stdin.readline() print 'Testing shutdown...' if EasyDialogs.AskYesNoCancel('Shut down?') > 0: result = shutdown() if result: print 'Result:', result print 'Press return-', sys.stdin.readline() print 'Testing restart...' if EasyDialogs.AskYesNoCancel('Restart?') > 0: result = restart() if result: print 'Result:', result print 'Press return-', sys.stdin.readline()
def _run(self): if self.run_with_interpreter: if self.editgroup.editor.changed: Qd.InitCursor() save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1) if save > 0: if self.domenu_save(): return elif save < 0: return if not self.path: raise W.AlertError, "Can't run unsaved file" self._run_with_interpreter() elif self.run_with_cl_interpreter: if self.editgroup.editor.changed: Qd.InitCursor() save = EasyDialogs.AskYesNoCancel('Save "%s" before running?' % self.title, 1) if save > 0: if self.domenu_save(): return elif save < 0: return if not self.path: raise W.AlertError, "Can't run unsaved file" self._run_with_cl_interpreter() else: pytext = self.editgroup.editor.get() globals, file, modname = self.getenvironment() self.execstring(pytext, globals, globals, file, modname)
def FrontWindowInsert(stuff): if not stuff: return if type(stuff) <> StringType: raise TypeError, 'string expected' import W app = W.getapplication() wid = MyFrontWindow() if wid and app._windows.has_key(wid): window = app._windows[wid] if hasattr(window, "insert"): try: window.insert(stuff) return except: pass import EasyDialogs if EasyDialogs.AskYesNoCancel( "Can't find window or widget to insert text into; copy to clipboard instead?", 1) == 1: from Carbon import Scrap if hasattr(Scrap, 'PutScrap'): Scrap.ZeroScrap() Scrap.PutScrap('TEXT', stuff) else: Scrap.ClearCurrentScrap() sc = Scrap.GetCurrentScrap() sc.PutScrapFlavor('TEXT', 0, stuff)
def main_interactive(interact=0, basepkgname='StdSuites'): if interact: edit_modnames = None else: edit_modnames = [] appsfolder = Carbon.Folder.FSFindFolder(-32765, 'apps', 0) filename = EasyDialogs.AskFileForOpen( message='Select scriptable application', dialogOptionFlags=4182, defaultLocation=appsfolder) if not filename: return else: if not is_scriptable(filename): if EasyDialogs.AskYesNoCancel( 'Warning: application does not seem scriptable', yes='Continue', default=2, no='') <= 0: return try: processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) except MacOS.Error as arg: print 'Error getting terminology:', arg print 'Retry, manually parsing resources' processfile_fromresource(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) return
def main_interactive(interact=0, basepkgname='StdSuites'): if interact: # Ask for save-filename for each module edit_modnames = None else: # Use default filenames for each module edit_modnames = [] appsfolder = Carbon.Folder.FSFindFolder(-32765, 'apps', 0) filename = EasyDialogs.AskFileForOpen( message='Select scriptable application', dialogOptionFlags=0x1056, # allow selection of .app bundles defaultLocation=appsfolder) if not filename: return if not is_scriptable(filename): if EasyDialogs.AskYesNoCancel( "Warning: application does not seem scriptable", yes="Continue", default=2, no="") <= 0: return try: processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr) except MacOS.Error, arg: print "Error getting terminology:", arg print "Retry, manually parsing resources" processfile_fromresource(filename, edit_modnames=edit_modnames, basepkgname=basepkgname, verbose=sys.stderr)
def quit(self, *args): if self.main.is_modified(): rv = EasyDialogs.AskYesNoCancel('Database modified. Save?', -1) if rv == -1: return if rv == 1: self.main.save() raise self
def close(self): if self.editgroup.editor.changed: Qd.InitCursor() save = EasyDialogs.AskYesNoCancel('Save window "%s" before closing?' % self.title, default=1, no="Don\xd5t save") if save > 0: if self.domenu_save(): return 1 elif save < 0: return 1 self.globals = None W.Window.close(self)
def close(self): if self.ted.WEGetModCount(): save = EasyDialogs.AskYesNoCancel( 'Save window "%s" before closing?' % self.name, 1) if save > 0: self.menu_save() elif save < 0: return if self.parent.active == self: self.parent.active = None self.parent.updatemenubar() del self.ted self.do_postclose()
def domenu_openURL(self, *args): ok = EasyDialogs.AskYesNoCancel( "Warning: by opening a non-standard database " "you are trusting the maintainer of it " "to run arbitrary code on your machine.", yes="OK", no="") if ok <= 0: return url = EasyDialogs.AskString("URL of database to open:", default=self.defaulturl, ok="Open") if url: self.opendoc(url)
def AskYesNoCancel(message, title='RoboFab', default=0): """ Returns 1 for 'Yes', 0 for 'No' and -1 for 'Cancel'. Availability: FontLab, Macintosh ("default" argument only available on Macintosh) """ if inFontLab: gync = _FontLabDialogGetYesNoCancel(message, title) gync.Run() v = gync.value return v elif MAC: import EasyDialogs gync = EasyDialogs.AskYesNoCancel(message, default=default) return gync else: _raisePlatformError('GetYesNoCancel')
def mac_getargs(args): inputs = [] output = None commands = None ramprefix = None switched = 0 import macfs import EasyDialogs if args[1:]: inputs = args[1:] else: fss, ok = macfs.StandardGetFile() if not ok: sys.exit(0) inputs = [fss.as_pathname()] dir = os.path.split(inputs[0])[0] os.chdir(dir) for i in range(len(inputs)): filename = inputs[i] if filename[:len(dir)] == dir: inputs[i] = filename[len(dir):] if len(inputs) == 1: dft = 'g2_' + inputs[0][1:] fss, ok = macfs.StandardPutFile("G2 output file", dft) if not ok: sys.exit(0) output = fss.as_pathname() fss, ok = macfs.StandardPutFile("Script output (cancel for text)", "Conversion script") if ok: commands = fss.as_pathname() reply = EasyDialogs.AskString("URL prefix for use in .ram file (cancel for no ram file)") if reply: ramprefix = reply reply = EasyDialogs.AskYesNoCancel("Create G2/GRiNS switch statements?") if reply > 0: switched = 1 return inputs, output, commands, ramprefix, switched
sys.exit(0) # Now, another, simpler dialog, uses the system's folder-chooser dialog: path = EasyDialogs.AskFolder("Choose destination directory") if not path: sys.exit(0) if not os.path.isdir(path): EasyDialogs.Message("Destination directory not found") sys.exit(0) # and now a progress bar: tot_numfiles = sum([len(os.listdir(d)) for d in dirs]) bar = EasyDialogs.ProgressBar("Processing", tot_numfiles) for d in dirs: for item in os.listdir(d): bar.inc() try: objpict = Image.open(d + "/" + item) if resize: objpict.thumbnail((100, 100, 1)) if rotationr: objpict = objpict.rotate(-90) if rotationl: objpict = objpict.rotate(90) objpict.save(path + "/" + item + "." + format, format) except: print item + " is not an image" # and one last dialog...: score = EasyDialogs.AskYesNoCancel("Do you like this program?") if score == 1: EasyDialogs.Message("Wwowowowow, EasyDialog roolz, ;-)") elif score == 0: EasyDialogs.Message("Sigh, sorry, will do better next time!-(") elif score == -1: EasyDialogs.Message("Hey, you didn't answer?!")
#
def GetOKCancel(prompt, parent=None): import EasyDialogs rv = EasyDialogs.AskYesNoCancel(prompt, 1, yes='OK', no='') if rv > 0: return 0 return 1
"""macgen_bin - Generate application from shared libraries"""
def generate(input, output, module_dict=None, architecture='fat', debug=0): # try to remove old file try: os.remove(output) except: pass if module_dict is None: import macmodulefinder print "Searching for modules..." module_dict, missing = macmodulefinder.process(input, [], [], 1) if missing: import EasyDialogs missing.sort() answer = EasyDialogs.AskYesNoCancel( "Some modules could not be found; continue anyway?\n(%s)" % string.join(missing, ", ")) if answer <> 1: sys.exit(0) applettemplatepath = buildtools.findtemplate() corepath = findpythoncore() dynamicmodules, dynamicfiles, extraresfiles = findfragments( module_dict, architecture) print 'Adding "__main__"' buildtools.process(applettemplatepath, input, output, 0) outputref = Res.FSpOpenResFile(output, 3) try: Res.UseResFile(outputref) print "Adding Python modules" addpythonmodules(module_dict) print "Adding PythonCore resources" copyres(corepath, outputref, ['cfrg', 'Popt', 'GU\267I'], 1) print "Adding resources from shared libraries" for ppcpath, cfm68kpath in extraresfiles: if os.path.exists(ppcpath): copyres(ppcpath, outputref, ['cfrg'], 1) elif os.path.exists(cfm68kpath): copyres(cfm68kpath, outputref, ['cfrg'], 1) print "Fixing sys.path prefs" Res.UseResFile(outputref) try: res = Res.Get1Resource('STR#', 228) # from PythonCore except Res.Error: pass else: res.RemoveResource() # setting pref file name to empty string res = Res.Get1NamedResource('STR ', "PythonPreferenceFileName") res.data = Pstring("") res.ChangedResource() syspathpref = "$(APPLICATION)" res = Res.Resource("\000\001" + Pstring(syspathpref)) res.AddResource("STR#", 229, "sys.path preference") print "Creating 'PYD ' resources" for modname, (ppcfrag, cfm68kfrag) in dynamicmodules.items(): res = Res.Resource(Pstring(ppcfrag) + Pstring(cfm68kfrag)) id = 0 while id < 128: id = Res.Unique1ID('PYD ') res.AddResource('PYD ', id, modname) finally: Res.CloseResFile(outputref) print "Merging code fragments" cfmfile.mergecfmfiles([applettemplatepath, corepath] + dynamicfiles.keys(), output, architecture) print "done!"
def GetYesNo(prompt, parent=None): import EasyDialogs rv = EasyDialogs.AskYesNoCancel(prompt, 1) if rv < 0: return 1 if rv > 0: return 0 return 1
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import EasyDialogs valid_responses = { 1:'yes', 0:'no', -1:'cancel', } response = EasyDialogs.AskYesNoCancel('Select an option') print 'You selected:', valid_responses[response]
if options.loop: # if in loop mode, ensure that there is a "ready to go" question in the loop options.ask_start = True # init jtag.init_backend(options.backend) if jtag.backend == jtag.CTYPES_TI: options.fake_progress = True # - - - - - - - - - - - - - - optional questions - - - - - - - - - - - - - - - if options.lpt == 'ask': #swap the buttons, so that cancel is the sparate button at left answer = EasyDialogs.AskYesNoCancel( "MSP430 downloader\n\nDownload '%s'?\n\n" % (options.filename, ), default=0, cancel="USB", yes="Parallel port", no="Cancel") if answer == 0: #NO -> abort abort_on_user_request() elif answer == 1: #YES -> parallel options.lpt = "1" else: #CANCEL -> USB options.lpt = "TIUSB" # check for aliases for the interface if options.lpt == 'parallel': options.lpt = '1' # choose erase mode if options.erase_mode == 'ask':
"""Utility routines depending on the finder,
def askYesNo(self, question, defaultValue=None): """ Default value is not working in the current implementation """ return True if EasyDialogs.AskYesNoCancel(question) > 0 else False
def main(): # - - - - - - - - - - - - - load binary or config - - - - - - - - - - - - - - - # if parameter is given use this filename, open a requester otherwise if len(sys.argv) < 2: options.filename = ask_for_binary() if options.filename is None: abort_on_user_request() else: options.filename = sys.argv[1] # - - - - - - - - - - - detect and handle config files - - - - - - - - - - - - # interpret manifest files here if options.filename.endswith('.m43'): # this is a simple ini file with settings config_filename = options.filename options.filename = None config = ConfigParser.RawConfigParser() config.read(config_filename) interpret_config(config, root=os.path.dirname(config_filename)) if options.readme: if options.viewer == 'browser': import webbrowser webbrowser.open(options.readme) else: EasyDialogs.Message(open(options.readme).read()) elif options.filename.endswith('.z43'): # a zip file containing the manifest file and the binary and a readme config_filename = options.filename options.filename = None import zipfile archive = zipfile.ZipFile(config_filename) # in a loop, search for the manifest file for info in archive.infolist(): if info.filename.endswith('.m43'): config_filename = options.filename config = ConfigParser.RawConfigParser() config.readfp(StringIO(archive.read(info.filename))) interpret_config(config, abspath=False) # get binary from zip file if options.filename: binary = msp430.memory.Memory() # prepare downloaded data binary.loadFile(options.filename, fileobj=BytesIO(archive.read(options.filename))) # get readme from zip file and display it if options.readme: readme_text = archive.read(options.readme) if options.viewer == 'browser': import webbrowser import tempfile import atexit tmp_name = tempfile.mktemp(options.readme) tmp = open(tmp_name, 'wb') tmp.write(readme_text) tmp.close() # ensure that the readme is deleted at the end def cleanup(filename=tmp_name): os.remove(tmp_name) atexit.register(cleanup) webbrowser.open(tmp_name) else: EasyDialogs.Message(readme_text) # checks if binary is None: if options.filename is None: options.filename = ask_for_binary() if options.filename is None: abort_on_user_request() if not os.path.isabs(options.filename): options.filename = os.path.abspath(options.filename) if os.path.isfile(options.filename): binary = msp430.memory.load( options.filename) # format=options.input_format) else: abort_on_error("File not found:\n%s" % (options.filename, )) if options.loop: # if in loop mode, ensure that there is a "ready to go" question in the loop options.ask_start = True # init jtag.init_backend(options.backend) if jtag.backend == jtag.CTYPES_TI: options.fake_progress = True # - - - - - - - - - - - - - - optional questions - - - - - - - - - - - - - - - if options.lpt == 'ask': #swap the buttons, so that cancel is the sparate button at left answer = EasyDialogs.AskYesNoCancel( "MSP430 downloader\n\nDownload '%s'?\n\n" % (options.filename, ), default=0, cancel="USB", yes="Parallel port", no="Cancel") if answer == 0: # NO -> abort abort_on_user_request() elif answer == 1: # YES -> parallel options.lpt = "1" else: # CANCEL -> USB options.lpt = "TIUSB" # check for aliases for the interface if options.lpt == 'parallel': options.lpt = '1' # choose erase mode if options.erase_mode == 'ask': answer = EasyDialogs.AskYesNoCancel("Choose erase mode", default=0, yes="ALL", cancel="Main only", no="Cancel") if answer == 0: # NO abort_on_user_request() elif answer == 1: # YES options.erase_mode = 'mass' else: # CANCEL options.erase_mode = 'main' # - - - - - - - - - - - - - - - - logging - - - - - - - - - - - - - - - - - - if options.debug: print('\n'.join(["%s: %r" % kv for kv in options.__dict__.items()])) # - - - - - - - - - - - - - main programming loop - - - - - - - - - - - - - - # capture console output sys.stdout = sys.stderr = StringIO() class ProgressJTAG(jtag.JTAG): def progess_update(self, count, total): self.bar.set(100 * count / total) while True: if options.ask_start: answer = EasyDialogs.AskYesNoCancel("""\ Ready to program... 1. Connect the programmer. 2. Power on target 3. Press 'Start' """, default=0, cancel='Start', yes='', no='Cancel') if answer == 0: # NO -> abort print("User aborted") break elif answer == 1: # YES -> ?? sys.exit(1) else: # CANCEL -> start pass try: jtagobj = ProgressJTAG() if not options.fake_progress: jtagobj.showprogess = True jtagobj.bar = EasyDialogs.ProgressBar( 'Programming %r' % options.filename[-50:], 100) showError = False try: connected = False jtagobj.data = binary jtagobj.bar.label('Connecting...') jtagobj.open(options.lpt) # try to open port try: jtagobj.connect() # try to connect to target connected = True if options.fake_progress: jtagobj.bar.set(10) jtagobj.bar.label('Erasing...') if options.erase_mode == 'mass' or options.erase_mode == 'all': jtagobj.actionMassErase() elif options.erase_mode == 'main': jtagobj.actionMainErase() if options.fake_progress: jtagobj.bar.set(20) showError = True jtagobj.bar.label('Programming...') jtagobj.actionProgram() if options.fake_progress: jtagobj.bar.set(60) jtagobj.bar.label('Verifying...') jtagobj.actionVerify() if options.fake_progress: jtagobj.bar.set(100) finally: if sys.exc_info()[:1]: # if there is an exception pending jtagobj.verbose = 0 # do not write any more messages if connected: jtagobj.bar.label('Reset...') jtagobj.reset(1, 1) # reset and release target jtagobj.close() # Release communication port finally: del jtagobj.bar # close progress bar except IOError as e: if showError: EasyDialogs.Message( 'An error occoured: "%s"\n\nMessages:\n%s' % (e, sys.stdout.getvalue())) else: EasyDialogs.Message("%s: Can't connect to target" % name) except (SystemExit, KeyboardInterrupt): raise except Exception as e: if options.debug: messages = sys.stdout.getvalue() sys.__stdout__.write(messages) traceback.print_exc(file=sys.__stdout__) EasyDialogs.Message('An error occoured: %s\nMessages:\n%s' % (e, sys.stdout.getvalue())) else: messages = sys.stdout.getvalue() if options.debug: sys.__stdout__.write(messages) EasyDialogs.Message('Messages:\n%s\nSuccess!' % (messages, )) if not options.loop: break