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 _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 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 GetType(): """Ask user for distribution type""" while 1: d = Dlg.GetNewDialog(ID_DTYPE, -1) d.SetDialogDefaultItem(DTYPE_EXIST) d.SetDialogCancelItem(DTYPE_CANCEL) while 1: rv = ModalDialog(None) if rv in (DTYPE_EXIST, DTYPE_NEW, DTYPE_CANCEL): break del d if rv == DTYPE_CANCEL: sys.exit(0) if rv == DTYPE_EXIST: ## macfs.SetFolder(':(MkDistr)') fss, ok = macfs.StandardGetFile('TEXT') if not ok: sys.exit(0) path = fss.as_pathname() basename = os.path.split(path)[-1] if basename[-8:] <> '.include': EasyDialogs.Message('That is not a distribution include file') else: return basename[:-8] else: name = EasyDialogs.AskString('Distribution name:') if name: return name sys.exit(0)
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 opendoc(self, *args): pathname = EasyDialogs.AskFileForOpen() # Any file type if not pathname: return bar = EasyDialogs.ProgressBar('Reading and converting...') try: rdr = img.reader(imgformat.macrgb16, pathname) except img.error, arg: EasyDialogs.Message(repr(arg)) return
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 inserthtml(self, *args): if self.active: path = EasyDialogs.AskFileForOpen(typeList=('TEXT', )) if not path: return try: fp = open(path, 'r') except IOError, arg: EasyDialogs.Message("IOERROR: %r" % (arg, )) return self.active.menu_insert_html(fp)
def insertfile(self, *args): if self.active: path = EasyDialogs.AskFileForOpen(typeList=('TEXT', )) if not path: return try: fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line except IOError, arg: EasyDialogs.Message("IOERROR: %r" % (args, )) return self.active.menu_insert(fp)
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 _open(self, askfile): if askfile: path = EasyDialogs.AskFileForOpen(typeList=('TEXT', )) if not path: return name = os.path.split(path)[-1] try: fp = open(path, 'rb') # NOTE binary, we need cr as end-of-line data = fp.read() fp.close() except IOError, arg: EasyDialogs.Message("IOERROR: %r" % (arg, )) return
def lowlevelhandler(self, event): what, message, when, where, modifiers = event h, v = where if what == kHighLevelEvent: msg = "High Level Event: %s %s" % \ (`code(message)`, `code(h | (v<<16))`) try: AE.AEProcessAppleEvent(event) except AE.Error, err: EasyDialogs.Message(msg + "\015AEProcessAppleEvent error: %s" % str(err)) traceback.print_exc() else: EasyDialogs.Message(msg + "\015OK!")
def main(): pathname = EasyDialogs.AskFileForOpen(message='File to check end-of-lines in:') if not pathname: sys.exit(0) fp = open(pathname, 'rb') try: data = fp.read() except MemoryError: EasyDialogs.Message('Sorry, file is too big.') sys.exit(0) if len(data) == 0: EasyDialogs.Message('File is empty.') sys.exit(0) number_cr = string.count(data, '\r') number_lf = string.count(data, '\n') if number_cr == number_lf == 0: EasyDialogs.Message('File contains no lines.') if number_cr == 0: EasyDialogs.Message('File has unix-style line endings') elif number_lf == 0: EasyDialogs.Message('File has mac-style line endings') elif number_cr == number_lf: EasyDialogs.Message('File probably has MSDOS-style line endings') else: EasyDialogs.Message('File has no recognizable line endings (binary file?)') sys.exit(0)
def macGetArgs(): import EasyDialogs EasyDialogs.Message("""\ Use the next dialog to build a command line: 1. Choose an output format from the [Option] list 2. Click [Add] 3. Choose an input file: [Add existing file...] 4. Save the output: [Add new file...] 5. [OK]""") optionlist = [(longopt, description) for (longopt, shortopt, description) in options] argv = EasyDialogs.GetArgv(optionlist=optionlist, addfolder=0) return posixGetArgs(argv)
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 handle_xml_file(self, path): prefs = getprefs() makesuitcase = int(prefs.get("makesuitcases", 0)) dstfolder = prefs.get("ttoutput", DEFAULTTTOUTPUT) if not os.path.exists(dstfolder): os.mkdir(dstfolder) srcfilename = dstfilename = os.path.basename(path) if dstfilename[-4:] in (".ttx", ".xml"): dstfilename = dstfilename[:-4] if dstfilename[-4:] not in (".TTF", ".ttf"): dstfilename = dstfilename + ".TTF" dst = os.path.join(dstfolder, dstfilename) if makesuitcase: try: # see if the destination file is writable, # otherwise we'll get an error waaay at the end of # the parse procedure testref = Res.FSpOpenResFile(macfs.FSSpec(dst), 3) # read-write except Res.Error, why: if why[0] <> -43: # file not found EasyDialogs.Message( "Can't create '%s'; file already open" % dst) return else: Res.CloseResFile(testref)
def PutFile(message=None, fileName=None): """ Save file dialog. Returns path if one is entered. Otherwise it returns None. Availability: FontLab, Macintosh, PC """ path = None if MAC: if haveMacfs: fss, ok = macfs.StandardPutFile(message, fileName) if ok: path = fss.as_pathname() else: import EasyDialogs path = EasyDialogs.AskFileForSave(message, savedFileName=fileName) elif PC: if inFontLab: if not message: message = '' if not fileName: fileName = '' path = fl.GetFileName(0, message, fileName, '') else: openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_EXPLORER mode_save = 0 myDialog = win32ui.CreateFileDialog(mode_save, None, fileName, openFlags) myDialog.SetOFNTitle(message) is_OK = myDialog.DoModal() if is_OK == 1: path = myDialog.GetPathName() else: _raisePlatformError('GetFile') return path
def askChoice(self, question, choices, defaultValue=None, sortChoices=False, sortCallBack=None): """ Ask the user the supplied question and list the choices to choose from, if no response given the default value is used @param question: question to be display to the user @param choices: list of choices for the user to choose from @param defaultValue: the value that will be used if no response given @param sortChoices: if True, choices will be sorted before showing them to the user @param sortCallBack: A callback function to handle the sorting of the choices (will only be used if sortChoices is set to True) @return: selected choice """ defaultValues = list() if defaultValue: defaultValues = [ value.strip() for value in defaultValue.split(',') ] #we choose tolerant approach by just filtering out the invalid defaultValues entries, without raising an error defaultValues = filter(lambda value: value in choices, defaultValues) messageWihDefault = '%s%s' % (question, ('[%s]' % defaultValue) if defaultValue else '') message = "%(question)s\n\nMake a selection please: %(choices)s" index = 0 formmattedChoices = '' if sortChoices: if not sortCallBack: choices.sort() else: sortCallBack(choices) for section in choices: index += 1 formmattedChoices = "%s\n %s: %s" % (formmattedChoices, index, section) message = message % { 'question': messageWihDefault, 'choices': formmattedChoices } result = EasyDialogs.AskString(message) if result: selections = self._checkSelection(result, choices, False) result = choices[selections[0] - 1] else: if not defaultValues: raise ValueError( "No/Invalid default value provided, please try again and select Nr" ) result = defaultValues return result
def domenu_open(self, *args): filename = EasyDialogs.AskFileForOpen(typeList=("TEXT", )) if filename: filename = urllib.pathname2url(filename) if filename[:5] != 'file:': filename = 'file:' + filename self.opendoc(filename)
def process(template, filename, destname, copy_codefragment=0, rsrcname=None, others=[], raw=0, progress="default", destroot=""): if progress == "default": progress = EasyDialogs.ProgressBar( "Processing %s..." % os.path.split(filename)[1], 120) progress.label("Compiling...") progress.inc(0) # check for the script name being longer than 32 chars. This may trigger a bug # on OSX that can destroy your sourcefile. if '#' in os.path.split(filename)[1]: raise BuildError, "BuildApplet could destroy your sourcefile on OSX, please rename: %s" % filename # Read the source and compile it # (there's no point overwriting the destination if it has a syntax error) fp = open(filename, 'rU') text = fp.read() fp.close() try: code = compile(text + '\n', filename, "exec") except SyntaxError, arg: raise BuildError, "Syntax error in script %s: %s" % (filename, arg)
def menu_save_as(self): path = EasyDialogs.AskFileForSave(message='Save as:') if not path: return self.path = path self.name = os.path.split(self.path)[-1] self.wid.SetWTitle(self.name) self.menu_save()
def precompilesuite(self): """Parse a single suite without generating the output. This step is needed so we can resolve recursive references by suites to enums/comps/etc declared in other suites""" [name, desc, code, level, version, events, classes, comps, enums] = self.suite modname = identify(name) if len(modname) > 28: modname = modname[:27] if self.edit_modnames is None: self.pathname = EasyDialogs.AskFileForSave( message='Python output file', savedFileName=modname + '.py') else: for old, new in self.edit_modnames: if old == modname: modname = new if modname: self.pathname = os.path.join(self.output, modname + '.py') else: self.pathname = None if not self.pathname: return None, None, None self.modname = os.path.splitext(os.path.split(self.pathname)[1])[0] if self.basepackage and self.basepackage._code_to_module.has_key(code): # We are an extension of a baseclass (usually an application extending # Standard_Suite or so). Import everything from our base module basemodule = self.basepackage._code_to_module[code] else: # We are not an extension. basemodule = None self.enumsneeded = {} for event in events: self.findenumsinevent(event) objc = ObjectCompiler(None, self.modname, basemodule, interact=(self.edit_modnames is None), verbose=self.verbose) for cls in classes: objc.compileclass(cls) for cls in classes: objc.fillclasspropsandelems(cls) for comp in comps: objc.compilecomparison(comp) for enum in enums: objc.compileenumeration(enum) for enum in self.enumsneeded.keys(): objc.checkforenum(enum) objc.dumpindex() precompinfo = objc.getprecompinfo(self.modname) return code, self.modname, precompinfo
def GetDirectory(prompt=None): """Ask the user to select a folder. Optionally you can give a prompt.""" import EasyDialogs warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen", DeprecationWarning, stacklevel=2) fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec, defaultLocation=_handleSetFolder()) return fss, not fss is None
def Message(text): import EasyDialogs, string from Carbon import Qd Qd.InitCursor() text = string.replace(text, "\n", "\r") if not text: text = '<Alert text not specified>' EasyDialogs.Message(text)
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 gdzie_zapisac(): # ask for destination folder dir = EasyDialogs.AskFolder( message='Select destinatin folder', defaultLocation=os.getcwd(), wanted=unicode, ) return dir
def open_file_selector(title = 'Open', filters = None, root = ''): filters = filters or [('All Files', ('*.*',))] newFilters = [] for item in filters: for filter in item[1]: newFilters.append(filter.replace('.', '').replace('*', '')) return EasyDialogs.AskFileForOpen(message = title, typeList = newFilters, defaultLocation = root)
def main(): try: buildapplet() except buildtools.BuildError, detail: if EasyDialogs is None: print detail else: EasyDialogs.Message(detail)
def _test(): import EasyDialogs try: from PIL import Image except ImportError: Image = None import MacOS Qt.EnterMovies() path = EasyDialogs.AskFileForOpen(message='Video to convert') if not path: sys.exit(0) rdr = reader(path) if not rdr: sys.exit(1) dstdir = EasyDialogs.AskFileForSave(message='Name for output folder') if not dstdir: sys.exit(0) num = 0 os.mkdir(dstdir) videofmt = rdr.GetVideoFormat() imgfmt = videofmt.getformat() imgw, imgh = videofmt.getsize() timestamp, data = rdr.ReadVideo() while data: fname = 'frame%04.4d.jpg' % num num = num + 1 pname = os.path.join(dstdir, fname) if not Image: print 'Not', print 'Writing %s, size %dx%d, %d bytes' % (fname, imgw, imgh, len(data)) if Image: img = Image.fromstring('RGBA', (imgw, imgh), data) img.save(pname, 'JPEG') timestamp, data = rdr.ReadVideo() MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG') if num > 20: print 'stopping at 20 frames so your disk does not fill up:-)' break print 'Total frames:', num return
def domenu_save_as(self, *args): filename = EasyDialogs.AskFileForSave(message='Save console text as:', savedFileName='console.txt') if not filename: return f = open(filename, 'wb') f.write(self.get()) f.close() MacOS.SetCreatorAndType(filename, W._signature, 'TEXT')