def test_touched(self): # This really only tests that nothing unforeseen happens. import warnings with warnings.catch_warnings(): warnings.filterwarnings('ignore', 'macostools.touched*', DeprecationWarning) macostools.touched(test_support.TESTFN)
def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1): """Makes a one-page PDF with just the drawing. If autoSize=1, the PDF will be the same size as the drawing; if 0, it will place the drawing on an A4 page with a title above it - possibly overflowing if too big.""" d = renderScaledDrawing(d) c = Canvas(fn) if msg: c.setFont(rl_config.defaultGraphicsFontName, 36) c.drawString(80, 750, msg) c.setTitle(msg) if autoSize: c.setPageSize((d.width, d.height)) draw(d, c, 0, 0, showBoundary=showBoundary) else: #show with a title c.setFont(rl_config.defaultGraphicsFontName, 12) y = 740 i = 1 y = y - d.height draw(d, c, 80, y, showBoundary=showBoundary) c.showPage() c.save() if sys.platform=='mac' and not hasattr(fn, "write"): try: import macfs, macostools macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ") macostools.touched(fn) except: pass
def writenode(node, evallicense = 0, tostring = 0, silent = 0): if not hasattr(node, 'tmpfile') and not tostring: return import realsupport data = realsupport.writeRP(None, node.slideshow.rp, node, savecaptions=1, tostring = 1, silent = silent) if tostring: return data url = MMAttrdefs.getattr(node, 'file') url = node.GetContext().findurl(url) utype, host, path, params, query, tag = urlparse.urlparse(url) if (not utype or utype == 'file') and \ (not host or host == 'localhost'): try: localpathname = MMurl.url2pathname(path) f = open(localpathname, 'w') f.write(data) f.close() except: windowinterface.showmessage("cannot write `%s' for node `%s'" % (url, MMAttrdefs.getattr(node, 'name') or '<unnamed>')) else: if os.name == 'mac': import macfs import macostools fss = macfs.FSSpec(localpathname) fss.SetCreatorType('PNst', 'PNRA') macostools.touched(fss) del node.tmpfile else: windowinterface.showmessage("cannot write remote file for node `%s'" % (MMAttrdefs.getattr(node, 'name') or '<unnamed>'))
def drawToFile(d, fn, msg="", showBoundary=rl_config._unset_, autoSize=1): """Makes a one-page PDF with just the drawing. If autoSize=1, the PDF will be the same size as the drawing; if 0, it will place the drawing on an A4 page with a title above it - possibly overflowing if too big.""" d = renderScaledDrawing(d) c = Canvas(fn) if msg: c.setFont(rl_config.defaultGraphicsFontName, 36) c.drawString(80, 750, msg) c.setTitle(msg) if autoSize: c.setPageSize((d.width, d.height)) draw(d, c, 0, 0, showBoundary=showBoundary) else: #show with a title c.setFont(rl_config.defaultGraphicsFontName, 12) y = 740 i = 1 y = y - d.height draw(d, c, 80, y, showBoundary=showBoundary) c.showPage() c.save() if sys.platform == 'mac' and not hasattr(fn, "write"): try: import macfs, macostools macfs.FSSpec(fn).SetCreatorType("CARO", "PDF ") macostools.touched(fn) except: pass
def markfilename(filename,creatorcode=None,filetype=None,ext='PDF'): try: if creatorcode is None or filetype is None and ext is not None: try: creatorcode, filetype = _KNOWN_MAC_EXT[ext.upper()] except: return macfs.FSSpec(filename).SetCreatorType(creatorcode,filetype) macostools.touched(filename) except: pass
def markfilename(filename, creatorcode=None, filetype=None, ext='PDF'): try: if creatorcode is None or filetype is None and ext is not None: try: creatorcode, filetype = _KNOWN_MAC_EXT[ext.upper()] except: return macfs.FSSpec(filename).SetCreatorType(creatorcode, filetype) macostools.touched(filename) except: pass
def walktree(name, change): if os.path.isfile(name): fs = macfs.FSSpec(name) cur_cr, cur_tp = fs.GetCreatorType() if cur_cr == OLD: fs.SetCreatorType(NEW, cur_tp) macostools.touched(fs) print "Fixed ", name elif os.path.isdir(name): print "->", name files = os.listdir(name) for f in files: walktree(os.path.join(name, f), change)
def converttextfile(u, srcurl, dstdir, file, node): import MMAttrdefs, windowinterface import colors # ignore suggested extension and make our own file = os.path.splitext(file)[0] + '.rt' fullpath = os.path.join(dstdir, file) if identicalfiles(srcurl, fullpath): # src and dst files are the same, don't do anything u.close() if __debug__: print 'src and dst files are identical', fullpath return file data = u.read() u.close() f = open(fullpath, 'w') f.write('<window') if node is not None: dur = MMAttrdefs.getattr(node, 'duration') if dur: f.write(' duration="%g"' % dur) ch = node.GetChannel() color = ch.get('bgcolor') if color is not None: if colors.rcolors.has_key(color): color = colors.rcolors[color] else: color = '#%02x%02x%02x' % color f.write(' bgcolor="%s"' % color) geom = ch.get('base_winoff') units = ch.get('units', windowinterface.UNIT_SCREEN) if geom and units == windowinterface.UNIT_PXL: f.write(' width="%d" height="%d"' % (geom[2], geom[3])) f.write('>\n') f.write(data) f.write('</window>\n') f.close() if os.name == 'mac': import macfs import macostools fss = macfs.FSSpec(fullpath) fss.SetCreatorType('PNst', 'PNRA') macostools.touched(fss) return file
def save(self, verbose=None, fnRoot=None, outDir=None, title='', **kw): if not outDir: outDir = '.' fnroot = os.path.normpath(os.path.join(outDir, fnRoot)) if fnroot.endswith('.pdf'): filename = fnroot else: filename = fnroot + '.pdf' drawToFile(self, filename, title, showBoundary=getattr(self, 'showBorder', rl_config.showBoundary), **_extraKW(self, '_renderPDF_', **kw)) if sys.platform == 'mac': import macfs, macostools macfs.FSSpec(filename).SetCreatorType("CARO", "PDF ") macostools.touched(filename)
def domenu_save(self, *args): if not self.path: # Will call us recursively return self.domenu_save_as() data = self.editgroup.editor.get() if self._eoln != '\r': data = string.replace(data, '\r', self._eoln) fp = open(self.path, 'wb') # open file in binary mode, data has '\r' line-endings fp.write(data) fp.close() MacOS.SetCreatorAndType(self.path, self._creator, 'TEXT') self.getsettings() self.writewindowsettings() self.editgroup.editor.changed = 0 self.editgroup.editor.selchanged = 0 import linecache if linecache.cache.has_key(self.path): del linecache.cache[self.path] import macostools macostools.touched(self.path) self.addrecentfile(self.path)
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[], filename=None, destroot=""): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others, filename, destroot) if others: raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template if progress: progress.label("Copy data fork...") progress.set(10) if copy_codefragment: tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl # Open the output resource fork if progress: progress.label("Copy resources...") progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#'] if not copy_codefragment: skiptypes.append('cfrg') ## skipowner = (ownertype <> None) # Copy the resources from the template input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) Res.CloseResFile(input) ## if ownertype == None: ## raise BuildError, "No owner resource found in either resource file or template" # Make sure we're manipulating the output resource file now Res.UseResFile(output) if ownertype == None: # No owner resource in the template. We have skipped the # Python owner resource, so we have to add our own. The relevant # bundle stuff is already included in the interpret/applet template. newres = Res.Resource('\0') newres.AddResource(DEFAULT_APPLET_CREATOR, 0, "Owner resource") ownertype = DEFAULT_APPLET_CREATOR if code: # Delete any existing 'PYC ' resource named __main__ try: res = Res.Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Res.Error: pass # Create the raw data for the resource from the code object if progress: progress.label("Write PYC resource...") progress.set(120) data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Res.Unique1ID(RESTYPE) res = Res.Resource(data) res.AddResource(RESTYPE, id, RESNAME) attrs = res.GetResAttrs() attrs = attrs | 0x04 # set preload res.SetResAttrs(attrs) res.WriteResource() res.ReleaseResource() # Close the output file Res.CloseResFile(output) # Now set the creator, type and bundle bit of the destination. # Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+) dest_fss = Carbon.File.FSSpec(destname) dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype dest_finfo.Type = 'APPL' dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited dest_fss.FSpSetFInfo(dest_finfo) macostools.touched(destname) if progress: progress.label("Done.") progress.inc(0)
def test_touched(self): # This really only tests that nothing unforeseen happens. macostools.touched(test_support.TESTFN)
#
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[], filename=None, destroot=''): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others, filename, destroot) else: if others: raise BuildError, 'Extra files only allowed for MachoPython applets' template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() if progress: progress.label('Copy data fork...') progress.set(10) if copy_codefragment: tmpl = open(template, 'rb') dest = open(destname, 'wb') data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl if progress: progress.label('Copy resources...') progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + [ 'BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#' ] if not copy_codefragment: skiptypes.append('cfrg') input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) Res.CloseResFile(input) Res.UseResFile(output) if ownertype is None: newres = Res.Resource('\x00') newres.AddResource(DEFAULT_APPLET_CREATOR, 0, 'Owner resource') ownertype = DEFAULT_APPLET_CREATOR if code: try: res = Res.Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Res.Error: pass if progress: progress.label('Write PYC resource...') progress.set(120) data = marshal.dumps(code) del code data = MAGIC + '\x00\x00\x00\x00' + data id = 0 while id < 128: id = Res.Unique1ID(RESTYPE) res = Res.Resource(data) res.AddResource(RESTYPE, id, RESNAME) attrs = res.GetResAttrs() attrs = attrs | 4 res.SetResAttrs(attrs) res.WriteResource() res.ReleaseResource() Res.CloseResFile(output) dest_fss = Carbon.File.FSSpec(destname) dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype dest_finfo.Type = 'APPL' dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited dest_fss.FSpSetFInfo(dest_finfo) macostools.touched(destname) if progress: progress.label('Done.') progress.inc(0) return
def test_touched(self): # This really only tests that nothing unforeseen happens. with test_support.check_warnings( ('macostools.touched*', DeprecationWarning), quiet=True): macostools.touched(test_support.TESTFN)
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw = 0, others = [], filename = None, destroot = ''): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others, filename, destroot) else: if others: raise BuildError, 'Extra files only allowed for MachoPython applets' template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() if progress: progress.label('Copy data fork...') progress.set(10) if copy_codefragment: tmpl = open(template, 'rb') dest = open(destname, 'wb') data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl if progress: progress.label('Copy resources...') progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + ['BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#'] if not copy_codefragment: skiptypes.append('cfrg') input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) Res.CloseResFile(input) Res.UseResFile(output) if ownertype is None: newres = Res.Resource('\x00') newres.AddResource(DEFAULT_APPLET_CREATOR, 0, 'Owner resource') ownertype = DEFAULT_APPLET_CREATOR if code: try: res = Res.Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Res.Error: pass if progress: progress.label('Write PYC resource...') progress.set(120) data = marshal.dumps(code) del code data = MAGIC + '\x00\x00\x00\x00' + data id = 0 while id < 128: id = Res.Unique1ID(RESTYPE) res = Res.Resource(data) res.AddResource(RESTYPE, id, RESNAME) attrs = res.GetResAttrs() attrs = attrs | 4 res.SetResAttrs(attrs) res.WriteResource() res.ReleaseResource() Res.CloseResFile(output) dest_fss = Carbon.File.FSSpec(destname) dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype dest_finfo.Type = 'APPL' dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited dest_fss.FSpSetFInfo(dest_finfo) macostools.touched(destname) if progress: progress.label('Done.') progress.inc(0) return
def convertimagefile(u, srcurl, dstdir, file, node): # ignore suggested extension and make our own file = os.path.splitext(file)[0] + '.jpg' fullpath = os.path.join(dstdir, file) if identicalfiles(srcurl, fullpath): # src and dst files are the same, don't do anything u.close() if __debug__: print 'src and dst files are identical', fullpath return file import imgjpeg, imgconvert if u is not None: u.close() f, hdr = MMurl.urlretrieve(srcurl) wt = imgjpeg.writer(fullpath) wt.restart_interval = 1 if node is not None: if type(node) == type({}): quality = node.get('project_quality') else: quality = node.GetAttrDef('project_quality', None) if quality: wt.quality = quality if hdr.subtype == 'jpeg': # special-case code for JPEG images so that we don't loose info rdr = imgjpeg.reader(f) wt.copy(rdr) if os.name == 'mac': import macfs import macostools fss = macfs.FSSpec(fullpath) fss.SetCreatorType('ogle', 'JPEG') macostools.touched(fss) return file if sys.platform == 'win32': import __main__ import imgformat from win32ig import win32ig doc = __main__.toplevel.getActiveDocFrame() img = __main__.toplevel._image_handle(f, doc) if __main__.toplevel._image_depth(f, doc) != 24: win32ig.color_promote(img, 3) # IG_PROMOTE_TO_24 width, height = __main__.toplevel._image_size(f, doc) data = win32ig.read(img) srcfmt = imgformat.bmprgble_noalign else: import img rdr = img.reader(wt.format_choices[0], f) width = rdr.width height = rdr.height data = rdr.read() srcfmt = rdr.format imgconvert.setquality(0) wt = imgconvert.stackwriter(srcfmt, wt) wt.width = width wt.height = height wt.write(data) if os.name == 'mac': import macfs import macostools fss = macfs.FSSpec(fullpath) fss.SetCreatorType('ogle', 'JPEG') macostools.touched(fss) return file
"""tools for BuildApplet and BuildApplication"""
"""IC wrapper module, based on Internet Config 1.3"""
def settypecreator(self, file): file = Carbon.File.pathname(file) record = self.mapfile(os.path.split(file)[1]) MacOS.SetCreatorAndType(file, record[2], record[1]) macostools.touched(fss)
# specific to g2 try: open(ramfile, 'w').write(smilurl + '\n') except IOError, arg: windowinterface.showmessage('I/O Error writing %s: %s' % (ramfile, arg), mtype='error') return if os.name == 'mac': import macfs import macostools fss = macfs.FSSpec(ramfile) fss.SetCreatorType('PNst', 'PNRA') macostools.touched(fss) ramurl = MMurl.pathname2url(ramfile) try: writer = HTMLWriter(root, fp, filename, ramurl, oldfilename, evallicense, templatedir, 'REAL') writer.write() fp.close() except Error, msg: windowinterface.showmessage(msg, mtype='error') return if os.name == 'mac': fss = macfs.FSSpec(filename) fss.SetCreatorType('MOSS', 'TEXT') macostools.touched(fss)
class Drawing(Group, Flowable): """Outermost container; the thing a renderer works on. This has no properties except a height, width and list of contents.""" _saveModes = ( 'pdf', 'ps', 'eps', 'gif', 'png', 'jpg', 'jpeg', 'pct', 'pict', 'tiff', 'tif', 'py', 'bmp', 'svg', 'tiffp', 'tiffl', 'tiff1', ) _xtraAttrMap = AttrMap( width=AttrMapValue(isNumber, desc="Drawing width in points."), height=AttrMapValue(isNumber, desc="Drawing height in points."), canv=AttrMapValue(None), background=AttrMapValue(isValidChildOrNone, desc="Background widget for the drawing"), hAlign=AttrMapValue( OneOf("LEFT", "RIGHT", "CENTER", "CENTRE"), desc="Horizontal alignment within parent document"), vAlign=AttrMapValue(OneOf("TOP", "BOTTOM", "CENTER", "CENTRE"), desc="Vertical alignment within parent document"), #AR temporary hack to track back up. #fontName = AttrMapValue(isStringOrNone), renderScale=AttrMapValue(isNumber, desc="Global scaling for rendering"), ) _attrMap = AttrMap(BASE=Group) _attrMap.update(_xtraAttrMap) def __init__(self, width=400, height=200, *nodes, **keywords): self.background = None apply(Group.__init__, (self, ) + nodes, keywords) self.width = width self.height = height self.hAlign = 'LEFT' self.vAlign = 'BOTTOM' self.renderScale = 1.0 def _renderPy(self): I = { 'reportlab.graphics.shapes': ['_DrawingEditorMixin', 'Drawing', 'Group'] } G = _renderGroupPy(self._explode(), 'self', I) n = 'ExplodedDrawing_' + self.__class__.__name__ s = '#Autogenerated by ReportLab guiedit do not edit\n' for m, o in I.items(): s = s + 'from %s import %s\n' % ( m, string.replace(str(o)[1:-1], "'", "")) s = s + '\nclass %s(_DrawingEditorMixin,Drawing):\n' % n s = s + '\tdef __init__(self,width=%s,height=%s,*args,**kw):\n' % ( self.width, self.height) s = s + '\t\tapply(Drawing.__init__,(self,width,height)+args,kw)\n' s = s + G s = s + '\n\nif __name__=="__main__": #NORUNTESTS\n\t%s().save(formats=[\'pdf\'],outDir=\'.\',fnRoot=None)\n' % n return s def draw(self, showBoundary=_unset_): """This is used by the Platypus framework to let the document draw itself in a story. It is specific to PDF and should not be used directly.""" import renderPDF renderPDF.draw(self, self.canv, 0, 0, showBoundary=showBoundary) def wrap(self, availWidth, availHeight): width = self.width height = self.height renderScale = self.renderScale if renderScale != 1.0: width *= renderScale height *= renderScale return width, height def expandUserNodes(self): """Return a new drawing which only contains primitive shapes.""" obj = Group.expandUserNodes(self) obj.width = self.width obj.height = self.height return obj def copy(self): """Returns a copy""" return self._copy(self.__class__(self.width, self.height)) def asGroup(self, *args, **kw): return self._copy(apply(Group, args, kw)) def save(self, formats=None, verbose=None, fnRoot=None, outDir=None, title='', **kw): """Saves copies of self in desired location and formats. Multiple formats can be supported in one call the extra keywords can be of the form _renderPM_dpi=96 (which passes dpi=96 to renderPM) """ from reportlab import rl_config ext = '' if not fnRoot: fnRoot = getattr(self, 'fileNamePattern', (self.__class__.__name__ + '%03d')) chartId = getattr(self, 'chartId', 0) if callable(fnRoot): fnRoot = fnRoot(chartId) else: try: fnRoot = fnRoot % getattr(self, 'chartId', 0) except TypeError, err: #the exact error message changed from 2.2 to 2.3 so we need to #check a substring if str(err).find('not all arguments converted') < 0: raise if os.path.isabs(fnRoot): outDir, fnRoot = os.path.split(fnRoot) else: outDir = outDir or getattr(self, 'outDir', '.') outDir = outDir.rstrip().rstrip(os.sep) if not outDir: outDir = '.' if not os.path.isabs(outDir): outDir = os.path.join( getattr(self, '_override_CWD', os.path.dirname(sys.argv[0])), outDir) if not os.path.isdir(outDir): os.makedirs(outDir) fnroot = os.path.normpath(os.path.join(outDir, fnRoot)) plotMode = os.path.splitext(fnroot) if string.lower(plotMode[1][1:]) in self._saveModes: fnroot = plotMode[0] plotMode = map(str.lower, formats or getattr(self, 'formats', ['pdf'])) verbose = (verbose is not None and (verbose, ) or (getattr(self, 'verbose', verbose), ))[0] _saved = logger.warnOnce.enabled, logger.infoOnce.enabled logger.warnOnce.enabled = logger.infoOnce.enabled = verbose if 'pdf' in plotMode: from reportlab.graphics import renderPDF filename = fnroot + '.pdf' if verbose: print "generating PDF file %s" % filename renderPDF.drawToFile(self, filename, title, showBoundary=getattr(self, 'showBorder', rl_config.showBoundary), **_extraKW(self, '_renderPDF_', **kw)) ext = ext + '/.pdf' if sys.platform == 'mac': import macfs, macostools macfs.FSSpec(filename).SetCreatorType("CARO", "PDF ") macostools.touched(filename) for bmFmt in ('gif', 'png', 'tif', 'jpg', 'tiff', 'pct', 'pict', 'bmp', 'tiffp', 'tiffl', 'tiff1'): if bmFmt in plotMode: from reportlab.graphics import renderPM filename = '%s.%s' % (fnroot, bmFmt) if verbose: print "generating %s file %s" % (bmFmt, filename) renderPM.drawToFile(self, filename, fmt=bmFmt, showBoundary=getattr( self, 'showBorder', rl_config.showBoundary), **_extraKW(self, '_renderPM_', **kw)) ext = ext + '/.' + bmFmt if 'eps' in plotMode: try: from rlextra.graphics import renderPS_SEP as renderPS except ImportError: from reportlab.graphics import renderPS filename = fnroot + '.eps' if verbose: print "generating EPS file %s" % filename renderPS.drawToFile(self, filename, title=fnroot, dept=getattr(self, 'EPS_info', ['Testing'])[0], company=getattr(self, 'EPS_info', ['', 'ReportLab'])[1], preview=getattr(self, 'preview', rl_config.eps_preview), showBoundary=getattr(self, 'showBorder', rl_config.showBoundary), ttf_embed=getattr(self, 'ttf_embed', rl_config.eps_ttf_embed), **_extraKW(self, '_renderPS_', **kw)) ext = ext + '/.eps' if 'svg' in plotMode: from reportlab.graphics import renderSVG filename = fnroot + '.svg' if verbose: print "generating EPS file %s" % filename renderSVG.drawToFile(self, filename, showBoundary=getattr(self, 'showBorder', rl_config.showBoundary), **_extraKW(self, '_renderSVG_', **kw)) ext = ext + '/.svg' if 'ps' in plotMode: from reportlab.graphics import renderPS filename = fnroot + '.ps' if verbose: print "generating EPS file %s" % filename renderPS.drawToFile(self, filename, showBoundary=getattr(self, 'showBorder', rl_config.showBoundary), **_extraKW(self, '_renderPS_', **kw)) ext = ext + '/.ps' if 'py' in plotMode: filename = fnroot + '.py' if verbose: print "generating py file %s" % filename open(filename, 'w').write(self._renderPy()) ext = ext + '/.py' logger.warnOnce.enabled, logger.infoOnce.enabled = _saved if hasattr(self, 'saveLogger'): self.saveLogger(fnroot, ext) return ext and fnroot + ext[1:] or ''
def test_touched(self): # This really only tests that nothing unforeseen happens. with test_support.check_warnings(("macostools.touched*", DeprecationWarning), quiet=True): macostools.touched(test_support.TESTFN)
def _other_convertvideofile(u, srcurl, dstdir, file, node, progress=None): global engine import MMAttrdefs u.close() try: import videoreader except ImportError: return try: reader = videoreader.reader(srcurl) if not reader: return # ignore suggested extension and make our own file = os.path.splitext(file)[0] + '.rm' fullpath = os.path.join(dstdir, file) if identicalfiles(srcurl, fullpath): # src and dst files are the same, don't do anything u.close() if __debug__: print 'src and dst files are identical', fullpath return file if engine is None: engine = producer.CreateRMBuildEngine() videopin = None audiopin = None has_video = reader.HasVideo() has_audio = reader.HasAudio() if not has_video: import windowinterface windowinterface.showmessage("Warning: no video track found in %s" % srcurl) for pin in engine.GetPins(): if pin.GetOutputMimeType() == producer.MIME_REALVIDEO: videopin = pin elif pin.GetOutputMimeType() == producer.MIME_REALAUDIO: audiopin = pin warning = '' if has_video and not videopin: has_video = 0 warning = 'Video conversion support appears to be missing!\n' if has_audio and not audiopin: warning = 'Audio conversion support appears to be missing!\n' has_audio = 0 if warning: import windowinterface windowinterface.showmessage('Warning:\n' + warning) if not (has_audio or has_video): return engine.SetDoOutputMimeType(producer.MIME_REALAUDIO, has_audio) engine.SetDoOutputMimeType(producer.MIME_REALVIDEO, has_video) engine.SetDoOutputMimeType(producer.MIME_REALEVENT, 0) engine.SetDoOutputMimeType(producer.MIME_REALIMAGEMAP, 0) engine.SetDoOutputMimeType(producer.MIME_REALPIX, 0) engine.SetRealTimeEncoding(0) cp = engine.GetClipProperties() ts = engine.GetTargetSettings() ts.RemoveAllTargetAudiences() if node is not None: cp.SetTitle(MMAttrdefs.getattr(node, 'title')) cp.SetAuthor(MMAttrdefs.getattr(node, 'author')) cp.SetCopyright(MMAttrdefs.getattr(node, 'copyright')) cp.SetPerfectPlay(MMAttrdefs.getattr(node, 'project_perfect')) cp.SetMobilePlay(MMAttrdefs.getattr(node, 'project_mobile')) if has_video: ts.SetVideoQuality( MMAttrdefs.getattr(node, 'project_videotype')) if has_audio: ts.SetAudioContent( MMAttrdefs.getattr(node, 'project_audiotype')) target = MMAttrdefs.getattr(node, 'project_targets') ntargets = 0 for i in range(6): if (1 << i) & target: ts.AddTargetAudience(i) ntargets = ntargets + 1 if ntargets == 0: ts.AddTargetAudience(producer.ENC_TARGET_28_MODEM) ntargets = ntargets + 1 else: # we don't know nothin' about the node so use some defaults cp.SetTitle('') cp.SetAuthor('') cp.SetCopyright('') cp.SetPerfectPlay(1) cp.SetMobilePlay(0) ts.AddTargetAudience(producer.ENC_TARGET_28_MODEM) ntargets = 1 if has_video: ts.SetVideoQuality(producer.ENC_VIDEO_QUALITY_NORMAL) if has_audio: ts.SetAudioContent(producer.ENC_AUDIO_CONTENT_VOICE) engine.SetDoMultiRateEncoding(ntargets != 1) cp.SetSelectiveRecord(0) cp.SetDoOutputServer(0) cp.SetDoOutputFile(1) cp.SetOutputFilename(fullpath) if has_video: import imgformat video_props = videopin.GetPinProperties() video_props.SetFrameRate(reader.GetVideoFrameRate()) video_fmt = reader.GetVideoFormat() # XXXX To be done better if video_fmt.getformat() == imgformat.macrgb: prod_format = producer.ENC_VIDEO_FORMAT_BGR32_NONINVERTED elif video_fmt.getformat() == imgformat.bmprgble_noalign: prod_format = producer.ENC_VIDEO_FORMAT_RGB24 else: raise 'Unsupported video source format', video_fmt.getformat() w, h = video_fmt.getsize() video_props.SetVideoSize(w, h) video_props.SetVideoFormat(prod_format) video_props.SetCroppingEnabled(0) video_sample = engine.CreateMediaSample() if has_audio: audio_fmt = reader.GetAudioFormat() encoding = audio_fmt.getencoding() if not encoding in ('linear-excess', 'linear-signed'): has_audio = 0 engine.SetDoOutputMimeType(producer.MIME_REALAUDIO, 0) import windowinterface windowinterface.showmessage( 'Converting video only: cannot handle %s audio\n(linear audio only)' % encoding) if has_audio: audio_props = audiopin.GetPinProperties() audio_props.SetSampleRate(reader.GetAudioFrameRate()) audio_props.SetNumChannels(audio_fmt.getnchannels()) audio_props.SetSampleSize(audio_fmt.getbps()) audio_sample = engine.CreateMediaSample() engine.PrepareToEncode() # Put the rest inside a try/finally, so a KeyboardInterrupt will cleanup # the engine. try: if has_audio: nbytes = audiopin.GetSuggestedInputSize() nbpf = audio_fmt.getblocksize() / audio_fmt.getfpb() audio_inputsize_frames = nbytes / nbpf audio_done = video_done = 0 audio_flags = video_flags = 0 audio_time = video_time = 0 audio_data = video_data = None if has_audio: audio_time, audio_data = reader.ReadAudio( audio_inputsize_frames) if not audio_data: audio_done = 1 if has_video: video_time, video_data = reader.ReadVideo() if not video_data: video_done = 1 if progress: dur = max(reader.GetVideoDuration(), reader.GetAudioDuration()) now = 0 while not audio_done or not video_done: if not audio_done: next_audio_time, next_audio_data = reader.ReadAudio( audio_inputsize_frames) if not next_audio_data: audio_done = 1 audio_flags = producer.MEDIA_SAMPLE_END_OF_STREAM audio_sample.SetBuffer(audio_data, audio_time, audio_flags) audiopin.Encode(audio_sample) audio_time = next_audio_time audio_data = next_audio_data if audio_time > now: now = audio_time if not video_done: next_video_time, next_video_data = reader.ReadVideo() if not next_video_data: video_done = 1 video_flags = producer.MEDIA_SAMPLE_END_OF_STREAM video_sample.SetBuffer(video_data, video_time, video_flags) videopin.Encode(video_sample) video_time = next_video_time video_data = next_video_data if video_time > now: now = video_time if progress: apply(progress[0], progress[1] + (now, dur)) finally: engine.DoneEncoding() if os.name == 'mac': import macfs import macostools fss = macfs.FSSpec(fullpath) fss.SetCreatorType('PNst', 'PNRA') macostools.touched(fss) return file except producer.error, arg: import windowinterface windowinterface.showmessage("RealEncoder error: %s" % (arg, ))
def process_common(template, progress, code, rsrcname, destname, is_update, copy_codefragment, raw=0, others=[], filename=None, destroot=""): if MacOS.runtimemodel == 'macho': return process_common_macho(template, progress, code, rsrcname, destname, is_update, raw, others, filename, destroot) if others: raise BuildError, "Extra files only allowed for MachoPython applets" # Create FSSpecs for the various files template_fsr, d1, d2 = Carbon.File.FSResolveAliasFile(template, 1) template = template_fsr.as_pathname() # Copy data (not resources, yet) from the template if progress: progress.label("Copy data fork...") progress.set(10) if copy_codefragment: tmpl = open(template, "rb") dest = open(destname, "wb") data = tmpl.read() if data: dest.write(data) dest.close() tmpl.close() del dest del tmpl # Open the output resource fork if progress: progress.label("Copy resources...") progress.set(20) try: output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) except MacOS.Error: destdir, destfile = os.path.split(destname) Res.FSCreateResourceFile(destdir, unicode(destfile), RESOURCE_FORK_NAME) output = Res.FSOpenResourceFile(destname, RESOURCE_FORK_NAME, WRITE) # Copy the resources from the target specific resource template, if any typesfound, ownertype = [], None try: input = Res.FSOpenResourceFile(rsrcname, RESOURCE_FORK_NAME, READ) except (MacOS.Error, ValueError): pass if progress: progress.inc(50) else: if is_update: skip_oldfile = ['cfrg'] else: skip_oldfile = [] typesfound, ownertype = copyres(input, output, skip_oldfile, 0, progress) Res.CloseResFile(input) # Check which resource-types we should not copy from the template skiptypes = [] if 'vers' in typesfound: skiptypes.append('vers') if 'SIZE' in typesfound: skiptypes.append('SIZE') if 'BNDL' in typesfound: skiptypes = skiptypes + [ 'BNDL', 'FREF', 'icl4', 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#' ] if not copy_codefragment: skiptypes.append('cfrg') ## skipowner = (ownertype <> None) # Copy the resources from the template input = Res.FSOpenResourceFile(template, RESOURCE_FORK_NAME, READ) dummy, tmplowner = copyres(input, output, skiptypes, 1, progress) Res.CloseResFile(input) ## if ownertype == None: ## raise BuildError, "No owner resource found in either resource file or template" # Make sure we're manipulating the output resource file now Res.UseResFile(output) if ownertype == None: # No owner resource in the template. We have skipped the # Python owner resource, so we have to add our own. The relevant # bundle stuff is already included in the interpret/applet template. newres = Res.Resource('\0') newres.AddResource(DEFAULT_APPLET_CREATOR, 0, "Owner resource") ownertype = DEFAULT_APPLET_CREATOR if code: # Delete any existing 'PYC ' resource named __main__ try: res = Res.Get1NamedResource(RESTYPE, RESNAME) res.RemoveResource() except Res.Error: pass # Create the raw data for the resource from the code object if progress: progress.label("Write PYC resource...") progress.set(120) data = marshal.dumps(code) del code data = (MAGIC + '\0\0\0\0') + data # Create the resource and write it id = 0 while id < 128: id = Res.Unique1ID(RESTYPE) res = Res.Resource(data) res.AddResource(RESTYPE, id, RESNAME) attrs = res.GetResAttrs() attrs = attrs | 0x04 # set preload res.SetResAttrs(attrs) res.WriteResource() res.ReleaseResource() # Close the output file Res.CloseResFile(output) # Now set the creator, type and bundle bit of the destination. # Done with FSSpec's, FSRef FInfo isn't good enough yet (2.3a1+) dest_fss = Carbon.File.FSSpec(destname) dest_finfo = dest_fss.FSpGetFInfo() dest_finfo.Creator = ownertype dest_finfo.Type = 'APPL' dest_finfo.Flags = dest_finfo.Flags | Carbon.Files.kHasBundle | Carbon.Files.kIsShared dest_finfo.Flags = dest_finfo.Flags & ~Carbon.Files.kHasBeenInited dest_fss.FSpSetFInfo(dest_finfo) macostools.touched(destname) if progress: progress.label("Done.") progress.inc(0)