rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print filename print self.__getdirname(filename)
def getstore(self, filename): print filename print self.__getdirname(filename) try: store = self.__stores[self.__getdirname(filename)] except KeyError: self.open(filename) store = self.__stores[self.__getdirname(filename)] return store
if node.nodeType == xml.dom.Node.ELEMENT_NODE and node.tagName == "description":
if node.nodeType != xml.dom.Node.ELEMENT_NODE or node.tagName != "description": continue if node.hasChildNodes() and len(node.childNodes) == 1: if xmlutils.hasChildTextNode(node): return node child = node.firstChild if child.nodeType == xml.dom.Node.ELEMENT_NODE and child.tagName == "para" and xmlutils.hasChildTextNode(child): return node else:
def __get_description_element(self): children = self.__node.childNodes for node in children: # Here I assume that description is a text node; I am not sure # it's a good assumption if node.nodeType == xml.dom.Node.ELEMENT_NODE and node.tagName == "description": return node else: return None return None
else: return None
def __get_description_element(self): children = self.__node.childNodes for node in children: # Here I assume that description is a text node; I am not sure # it's a good assumption if node.nodeType == xml.dom.Node.ELEMENT_NODE and node.tagName == "description": return node else: return None return None
if desc_element != None and desc_element.hasChildNodes() and desc_element.firstChild.nodeType == xml.dom.Node.TEXT_NODE: value = desc_element.firstChild.data
if desc_element != None: if desc_element.firstChild.nodeType == xml.dom.Node.ELEMENT_NODE: node = desc_element.firstChild else: node = desc_element value = xmlutils.getChildTextNode(node)
def get_description(self, nonone = 0): desc_element = self.__get_description_element() if desc_element != None and desc_element.hasChildNodes() and desc_element.firstChild.nodeType == xml.dom.Node.TEXT_NODE: value = desc_element.firstChild.data else: value = None if nonone and value == None: value = "" return value
item.set_description(self.desc.get_buffer().get_text())
item.set_description(self.desc.get_buffer().get_text( self.desc.get_buffer().get_start_iter(), self.desc.get_buffer().get_end_iter()))
def save(self, obj): item = self.stores.get_item(self.filename, self) item.set_title(self.title.entry.get_text()) self.__combo_add_entry(self.title, self.title.entry.get_text()) item.set_description(self.desc.get_buffer().get_text())
parser = OptionParser ("usage: %prog [optoins] name")
parser = OptionParser ("usage: %prog [options] name")
def parse_args (): from optparse import OptionParser parser = OptionParser ("usage: %prog [optoins] name") parser.add_option ("-A", "--ACE", dest="project", action="store_const", help="Branch/tag only ACE", default=None, const="ace") parser.add_option ("-T", "--TAO", dest="project", action="store_const", help="Branch/tag ACE and TAO", default=None, const="tao") parser.add_option ("-C", "--CIAO", dest="project", action="store_const", help="Branch/tag ACE, TAO, and CIAO", default=None, const="ciao") parser.add_option ("-t", "--tag", dest="action", help="Create a tag", action="store_true", default=None) parser.add_option ("-b", "--branch", dest="action", action="store_false", help="Create a branch", default=None) parser.add_option ("-v", "--verbose", dest="verbose", action="store_true", help="Print out verbose debugging output", default=False) parser.add_option ("-s", "--svn", dest="svn", default="svn", help="Full path to svn binary, if not in path") parser.add_option ("-r", "--repo", dest="repo", default="https://svn.dre.vanderbilt.edu/DOC/Middleware/", help="Repository to use, defaults to s.d.v.e/DOC/Middleware.") parser.add_option ("--src", dest="source", default="trunk/", help="Path in repository from which to branch, defaults to trunk") parser.add_option ("--dest", dest="dest", default="", help="Specifies a subdirectory of branches or tags in which " + "to place the new branch/tag. dest must already exist.") parser.add_option ("-n", dest="take_action", action="store_false", default=True, help="Take no action") (opts, args) = parser.parse_args () if len(args) != 1: parser.error ("must specify exactly one branch or tag name") if opts.action is None: parser.error ("must specify either a branch or tag action") if opts.project is None: parser.error ("must specity a project to branch") return (opts, args)
o = super(MyCopyClass, self).copyWithZone_(zone)
o = self.__class__.alloc().init()
def copyWithZone_(self, zone): o = super(MyCopyClass, self).copyWithZone_(zone) o.foobar = 2 return o
NSApp = rt.NSApplication.sharedApplication()
def main(): pool = rt.NSAutoreleasePool() # Load Application Framework: rt.NSBundle.bundleWithPath_( '/System/Library/Frameworks/AppKit.framework').load() NSApp = rt.NSApplication.sharedApplication() win = rt.NSWindow.alloc() frame = ((200.0, 300.0), (250.0, 100.0)) win.initWithContentRect_styleMask_backing_defer_ (frame, 15, 2, 0) win.setTitle_ ('HelloWorld') win.setLevel_ (3) # floating window hel = rt.NSButton.alloc().initWithFrame_ (((10.0, 10.0), (80.0, 80.0))) win.contentView().addSubview_ (hel) hel.setBezelStyle_( 4 ) hel.setTitle_( 'Hello!' ) beep = rt.NSSound.alloc() beep.initWithContentsOfFile_byReference_( '/System/Library/Sounds/tink.aiff', 1 ) hel.setSound_( beep ) bye = rt.NSButton.alloc().initWithFrame_ (((100.0, 10.0), (80.0, 80.0))) win.contentView().addSubview_ (bye) bye.setBezelStyle_( 4 ) bye.setTarget_ (NSApp) bye.setAction_ ('stop:') bye.setEnabled_ ( 1 ) bye.setTitle_( 'Goobye!' ) adios = rt.NSSound.alloc() adios.initWithContentsOfFile_byReference_( '/System/Library/Sounds/Basso.aiff', 1 ) bye.setSound_( adios ) win.display()
return +number_wrap(_num_to_python(numA))
return number_wrap(+_num_to_python(numA))
def __pos__CFNumber(numA): return +number_wrap(_num_to_python(numA))
Thread.__init__(target=self.doWork)
Thread.__init__(self)
def __init__(self): """Create a worker thread. Start it by calling the start() method.""" self.queue = Queue() Thread.__init__(target=self.doWork)
self.setStatusTextFieldMessage_(None) self.methodDescriptionTextView.setString_(methodDescription)
if selectedRow == self.methodsTable.selectedRow(): self.setStatusTextFieldMessage_(None) self.methodDescriptionTextView.setString_(methodDescription)
def work(): self.setStatusTextFieldMessage_("Retrieving signature for method %s..." % selectedMethod) methodDescription = getattr(self._server, self._methodPrefix + "methodHelp")(selectedMethod) if not methodDescription: methodDescription = "No description available." self._methodDescriptions[selectedMethod] = methodDescription self.setStatusTextFieldMessage_(None) self.methodDescriptionTextView.setString_(methodDescription) self.stopWorking()
methodDescription = self._methodDescriptions[selectedMethod]
def work(): self.setStatusTextFieldMessage_("Retrieving signature for method %s..." % selectedMethod) methodDescription = getattr(self._server, self._methodPrefix + "methodHelp")(selectedMethod) if not methodDescription: methodDescription = "No description available." self._methodDescriptions[selectedMethod] = methodDescription self.setStatusTextFieldMessage_(None) self.methodDescriptionTextView.setString_(methodDescription) self.stopWorking()
self.methodDescriptionTextView.setString_(methodDescription)
methodDescription = self._methodDescriptions[selectedMethod] self.methodDescriptionTextView.setString_(methodDescription)
def work(): self.setStatusTextFieldMessage_("Retrieving signature for method %s..." % selectedMethod) methodDescription = getattr(self._server, self._methodPrefix + "methodHelp")(selectedMethod) if not methodDescription: methodDescription = "No description available." self._methodDescriptions[selectedMethod] = methodDescription self.setStatusTextFieldMessage_(None) self.methodDescriptionTextView.setString_(methodDescription) self.stopWorking()
OSX_VERSION = LooseVersion(os.popen('/usr/bin/sw_vers -productVersion').read().strip())
OSX_VERSION = LooseVersion(tools.sw_vers())
def write_preflight_rm(path, files): fobj = file(path, 'w') fobj.write(PREFLIGHT_RM % dict(files=map(os.path.normpath, files))) fobj.close() os.chmod(path, 0775)
if not hasattr(plist, "CFBundleIdentifier"):
if self.bundle_id: plist.CFBundleIdentifier = self.bundle_id elif not hasattr(plist, "CFBundleIdentifier"):
def setup(self): # XXX rethink self.name munging, this is brittle. self.name, ext = os.path.splitext(self.name) if not ext: ext = ".bundle" bundleextension = ext # misc (derived) attributes self.bundlepath = pathjoin(self.builddir, self.name + bundleextension)
os.environ["PYTHONPATH"] = resdir if %(standalone)s: os.environ["PYTHONHOME"] = resdir
if %(standalone)s or %(semi_standalone)s: os.environ["PYTHONPATH"] = resdir if %(standalone)s: os.environ["PYTHONHOME"] = resdir else: pypath = os.getenv("PYTHONPATH", "") if pypath: pypath = ":" + pypath os.environ["PYTHONPATH"] = resdir + pypath
def __load(): import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path)
self.executable = sys.executable
if self.python: self.executable = self.python else: self.executable = sys.executable
def setup(self): if ((self.standalone or self.semi_standalone) and self.mainprogram is None): raise BundleBuilderError, ("must specify 'mainprogram' when " "building a standalone application.") if self.mainprogram is None and self.executable is None: raise BundleBuilderError, ("must specify either or both of " "'executable' and 'mainprogram'")
"lib=", "python=", "semi-standalone")
"lib=", "python=", "semi-standalone", "bundle-id=")
def main(builder=None): if builder is None: builder = AppBuilder(verbosity=1) shortopts = "b:n:r:f:e:m:c:p:lx:i:hvqa" longopts = ("builddir=", "name=", "resource=", "file=", "executable=", "mainprogram=", "creator=", "nib=", "plist=", "link", "link-exec", "help", "verbose", "quiet", "argv", "standalone", "exclude=", "include=", "package=", "strip", "iconfile=", "lib=", "python=", "semi-standalone") try: options, args = getopt.getopt(sys.argv[1:], shortopts, longopts) except getopt.error: usage() for opt, arg in options: if opt in ('-b', '--builddir'): builder.builddir = arg elif opt in ('-n', '--name'): builder.name = arg elif opt in ('-r', '--resource'): builder.resources.append(os.path.normpath(arg)) elif opt in ('-f', '--file'): srcdst = arg.split(':') if len(srcdst) != 2: usage("-f or --file argument must be two paths, " "separated by a colon") builder.files.append(srcdst) elif opt in ('-e', '--executable'): builder.executable = arg elif opt in ('-m', '--mainprogram'): builder.mainprogram = arg elif opt in ('-a', '--argv'): builder.argv_emulation = 1 elif opt in ('-c', '--creator'): builder.creator = arg elif opt == '--iconfile': builder.iconfile = arg elif opt == "--lib": builder.libs.append(os.path.normpath(arg)) elif opt == "--nib": builder.nibname = arg elif opt in ('-p', '--plist'): builder.plist = Plist.fromFile(arg) elif opt in ('-l', '--link'): builder.symlink = 1 elif opt == '--link-exec': builder.symlink_exec = 1 elif opt in ('-h', '--help'): usage() elif opt in ('-v', '--verbose'): builder.verbosity += 1 elif opt in ('-q', '--quiet'): builder.verbosity -= 1 elif opt == '--standalone': builder.standalone = 1 elif opt == '--semi-standalone': builder.semi_standalone = 1 elif opt == '--python': builder.python = arg elif opt in ('-x', '--exclude'): builder.excludeModules.append(arg) elif opt in ('-i', '--include'): builder.includeModules.append(arg) elif opt == '--package': builder.includePackages.append(arg) elif opt == '--strip': builder.strip = 1 if len(args) != 1: usage("Must specify one command ('build', 'report' or 'help')") command = args[0] if command == "build": builder.setup() builder.build() elif command == "report": builder.setup() builder.report() elif command == "help": usage() else: usage("Unknown command '%s'" % command)
selection = self.outlineTreeController.election()
selection = self.outlineTreeController.selection()
def indentNote_(self, sender): selectionPath = self.outlineTreeController.selectionIndexPath() if not selectionPath: NSBeep() return
ssibling = children.objectAtIndex_(index - 1)
sibling = children.objectAtIndex_(index - 1)
def indentNote_(self, sender): selectionPath = self.outlineTreeController.selectionIndexPath() if not selectionPath: NSBeep() return
if gs_root is None:
if gs_root is not None:
def package_version(): fp = open('Modules/objc/pyobjc.h', 'r') for ln in fp.readlines(): if ln.startswith('#define OBJC_VERSION'): fp.close() return ln.split()[-1][1:-1] raise ValueError, "Version not found"
def selectClass_(self, event):
def outlineViewSelectionDidChange_(self, notification):
def selectClass_(self, event): rowNr = self.classTable.selectedRow() if rowNr == -1: self.clearClassInfo() else: item = self.classTable.itemAtRow_(rowNr) self.setClassInfo(unwrap_object(item))
] + LINK_OPT_STRIP + LIBFFI_LDFLAGS)
] + LIBFFI_LDFLAGS)
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, extensions return [], []
] + LINK_OPT_STRIP),
]),
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, extensions return [], []
def setUp(self): self.data = NSData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) self.mutableData = NSMutableData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) def testInitWithBytes_Length_(self): self.assertEquals(len(self.data), self.data.length(), "len() and -length didn't match.") self.assertEquals(len(self.data), len(rawBytes), "len(<data>) and len(<input>) didn't match.") self.assertEquals(len(self.mutableData), self.mutableData.length(), "Mutable: len() and -length didn't match.") self.assertEquals(len(self.mutableData), len(rawBytes), "Mutable: len(<data>) and len(<input>) didn't match.")
def assertDataContents(self, d1, d2, rawData): self.assertEquals(len(d1), d1.length(), "d1: len() and -length didn't match.") self.assertEquals(len(d1), len(rawData), "d1: len(<data>) and len(<input>) didn't match.") self.assertEquals(len(d2), d2.length(), "d2: len() and -length didn't match.") self.assertEquals(len(d2), len(rawData), "d2: len(<data>) and len(<input>) didn't match.") def testDataWithBytes_length_(self): """Test +dataWithBytes:length:""" data = NSData.dataWithBytes_length_(rawBytes, len(rawBytes)) mutableData = NSMutableData.dataWithBytes_length_(rawBytes, len(rawBytes)) self.assertDataContents(data, mutableData, rawBytes) def testInitWithBytes_length_(self): """Test -initWithBytes:length:""" data = NSData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) mutableData = NSMutableData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) self.assertDataContents(data, mutableData, rawBytes)
def setUp(self): self.data = NSData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) self.mutableData = NSMutableData.alloc().initWithBytes_length_(rawBytes, len(rawBytes))
bytes = self.data.bytes()
data = NSData.alloc().initWithBytes_length_(rawBytes, len(rawBytes)) bytes = data.bytes()
def testBytes(self): bytes = self.data.bytes() self.assertEquals(len(bytes), len(rawBytes), "bytes() and rawBytes not equal length.") for i in range(0,len(bytes)): self.assertEquals(rawBytes[i], bytes[i], "byte %s of bytes and rawBytes are not equal." % i)
mutableBytes = self.mutableData.mutableBytes()
mutableData = NSMutableData.dataWithBytes_length_(rawBytes, len(rawBytes)) mutableBytes = mutableData.mutableBytes()
def testMutableBytes(self): mutableBytes = self.mutableData.mutableBytes() for i in range(0, len(mutableBytes)): mutableBytes[i] = otherBytes[i] mutableBytes[1:8] = otherBytes[1:8]
except TypeError: pass
except TypeError, r: if str(r).find('right operand length must match slice length') is not 0: raise def testVariousDataLengths(self): """Test data of different lengths. Data of different lengths may be stored in different subclasses within the class cluster. """ testFactor = [1, 10, 1000, 10000, 10000000] for aFactor in testFactor: bigRawBytes = "1234567890" * aFactor mutableData = NSMutableData.dataWithBytes_length_(bigRawBytes, len(bigRawBytes)) data = NSData.dataWithBytes_length_(bigRawBytes, len(bigRawBytes))
def testMutableBytes(self): mutableBytes = self.mutableData.mutableBytes() for i in range(0, len(mutableBytes)): mutableBytes[i] = otherBytes[i] mutableBytes[1:8] = otherBytes[1:8]
self.assertDataContents(data, mutableData, bigRawBytes) mutableBytes = mutableData.mutableBytes() bytes = data.bytes() self.assertEquals(len(bytes), data.length()) self.assertEquals(len(mutableBytes), mutableData.length()) self.assertEquals(bytes, mutableBytes)
def testMutableBytes(self): mutableBytes = self.mutableData.mutableBytes() for i in range(0, len(mutableBytes)): mutableBytes[i] = otherBytes[i] mutableBytes[1:8] = otherBytes[1:8]
print "canInitWithRequest_"
def canInitWithRequest_(klass, request): print "canInitWithRequest_" if request.URL().scheme() == PYDOCSCHEME: return True return False
canInitWithRequest_ = objc.selector( canInitWithRequest_, signature=NSURLProtocol.canInitWithRequest_.signature, isClassMethod=True, )
def canInitWithRequest_(klass, request): print "canInitWithRequest_" if request.URL().scheme() == PYDOCSCHEME: return True return False
print "canonical", request.URL().standardizedURL().path()
def canonicalRequestForRequest_(klass, request): print "canonical", request.URL().standardizedURL().path() return request
canonicalRequestForRequest_= objc.selector( canonicalRequestForRequest_, signature=NSURLProtocol.canonicalRequestForRequest_.signature, isClassMethod=True, )
def canonicalRequestForRequest_(klass, request): print "canonical", request.URL().standardizedURL().path() return request
print "start"
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exception, e: print repr(e), str(e) client.URLProtocol_didFailWithError_( self, NSError.errorWithDomain_code_userInfo_( NSURLErrorDomain, NSURLErrorResourceUnavailable, None, ), ) else: response = NSURLResponse.alloc().initWithURL_MIMEType_expectedContentLength_textEncodingName_( request.URL(), u'text/html', len(data), u'utf-8', ) client.URLProtocol_didReceiveResponse_cacheStoragePolicy_( self, response, NSURLCacheStorageNotAllowed, ) client.URLProtocol_didLoadData_( self, NSData.dataWithBytes_length_(data, len(data)), ) client.URLProtocolDidFinishLoading_(self)
print 'urlpath', urlpath
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exception, e: print repr(e), str(e) client.URLProtocol_didFailWithError_( self, NSError.errorWithDomain_code_userInfo_( NSURLErrorDomain, NSURLErrorResourceUnavailable, None, ), ) else: response = NSURLResponse.alloc().initWithURL_MIMEType_expectedContentLength_textEncodingName_( request.URL(), u'text/html', len(data), u'utf-8', ) client.URLProtocol_didReceiveResponse_cacheStoragePolicy_( self, response, NSURLCacheStorageNotAllowed, ) client.URLProtocol_didLoadData_( self, NSData.dataWithBytes_length_(data, len(data)), ) client.URLProtocolDidFinishLoading_(self)
print 'modpath', modpath
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exception, e: print repr(e), str(e) client.URLProtocol_didFailWithError_( self, NSError.errorWithDomain_code_userInfo_( NSURLErrorDomain, NSURLErrorResourceUnavailable, None, ), ) else: response = NSURLResponse.alloc().initWithURL_MIMEType_expectedContentLength_textEncodingName_( request.URL(), u'text/html', len(data), u'utf-8', ) client.URLProtocol_didReceiveResponse_cacheStoragePolicy_( self, response, NSURLCacheStorageNotAllowed, ) client.URLProtocol_didLoadData_( self, NSData.dataWithBytes_length_(data, len(data)), ) client.URLProtocolDidFinishLoading_(self)
print repr(e), str(e)
def startLoading(self): print "start" client = self.client() request = self.request() urlpath = request.URL().standardizedURL().path() print 'urlpath', urlpath modpath = urlpath.replace(u'/', u'.' ).lstrip(u'.' ).replace(u'.html', u'') print 'modpath', modpath try: data = gethtmldoc(modpath.encode('utf-8')) except Exception, e: print repr(e), str(e) client.URLProtocol_didFailWithError_( self, NSError.errorWithDomain_code_userInfo_( NSURLErrorDomain, NSURLErrorResourceUnavailable, None, ), ) else: response = NSURLResponse.alloc().initWithURL_MIMEType_expectedContentLength_textEncodingName_( request.URL(), u'text/html', len(data), u'utf-8', ) client.URLProtocol_didReceiveResponse_cacheStoragePolicy_( self, response, NSURLCacheStorageNotAllowed, ) client.URLProtocol_didLoadData_( self, NSData.dataWithBytes_length_(data, len(data)), ) client.URLProtocolDidFinishLoading_(self)
print "stop"
pass
def stopLoading(self): print "stop"
is_framework = os.path.dirname(os.path.dirname(sys.prefix)).endswith('.framework') if is_framework and self.scheme_map['scripts'].startswith(sys.prefix): self.scheme_map['scripts'] = '/usr/local/bin'
scripts = self.scheme_map.get('scripts') if scripts: is_framework = os.path.dirname(os.path.dirname(sys.prefix)).endswith('.framework') if is_framework and scripts.startswith(sys.prefix): self.scheme_map['scripts'] = '/usr/local/bin'
def finalize_options (self): self.set_undefined_options('bdist', ('bdist_base', 'bdist_base')) if self.pkg_base is None: self.pkg_base = os.path.join(self.bdist_base, 'mpkg')
rest2HTML(None, '.', ['Install.txt', 'ReadMe.txt', 'Examples/00ReadMe.txt', 'Installer Package/ReadMe.txt'])
rest2HTML(None, '.', ['Install.txt', 'ReadMe.txt', 'Examples/00ReadMe.txt', 'Installer Package/ReadMe.txt', 'ProjectBuilder Extras/Project Templates/00README.txt'], ) os.rename('ProjectBuilder Extras/Project Templates/00README.html', 'Doc/ProjectBuilder-Templates.html')
def escquotes(val): return val.replace("'", "'\"'\"'")
def getattr(self, attr):
def __getattr__(self, attr):
def getattr(self, attr): return getattr(self.__pyobjc_object__, attr)
return (*pid != nil);
if (PyErr_Occurred()) { return 0; } return 1;
typedef void* PYOBJC_VOIDPTR;
result = { 'meth': lambda : not getattr(ctests, name) }
def test_CheckNSInvoke(self): try: ctests.CheckNSInvoke() except AssertionError: return raise AssertionError, "NSInvocation works!" return test_CheckNSInvoke
def make_test(name): """ Create a method for use in a unittest, the exec is needed to get the proper function name """ result = { 'meth': getattr(ctests, name) } if sys.platform == 'darwin' and name == 'CheckNSInvoke': # There is a bug in Apple's implementation of NSInvocation # surpress the test failure until Apple fixes the class. # Don't change the C-code, the same function is used to disable # parts of the unittests that trigger the bug. result = { 'meth': lambda : not getattr(ctests, name) } exec """\
fp.write('\tif (tmp == NULL) { PyObjCErr_ToObjC(); return nil; }\n')
fp.write('\tif (tmp == NULL) { PyObjCErr_ToObjCWithGILState(&state); return nil; }\n')
fp.write('#ifdef HAVE_BOOL\n')
fp.write('\tif (PyErr_Occurred()) { PyObjCErr_ToObjC(); return nil; }\n')
fp.write('\tif (PyErr_Occurred()) { PyObjCErr_ToObjCWithGILState(&state); return nil; }\n') fp.write('\tPyGILState_Release(state);\n')
fp.write('#ifdef HAVE_BOOL\n')
return WSTConnectionWindowController.alloc().init().autorelease()
return WSTConnectionWindowController.alloc().init()
def connectionWindowController(self): return WSTConnectionWindowController.alloc().init().autorelease()
class ClassesDataSource (NibClassBuilder.AutoBaseClass, NSOutlineViewDataSource, NSTableDataSource): __slots__ = ('_classList', '_classTree', '_methodInfo')
class ClassesDataSource (NibClassBuilder.AutoBaseClass): __slots__ = ('_classList', '_classTree', '_methodInfo', '_classInfo')
def classBundle(cls): framework = NSBundle.bundleForClass_(cls).bundlePath() if framework.startswith(SYSFRAMEWORKS_DIR): framework = framework[len(SYSFRAMEWORKS_DIR):] if framework.endswith('.framework'): framework = framework[:-len('.framework')] return framework
item = wrap_object[super]
item = wrap_object(super)
def showClass(self, cls): # First expand the tree (to make item visible) super = cls.__bases__[0] if super == objc_object: return
item = wrap_object[cls]
item = wrap_object(cls)
def selectClass(self, cls): self.showClass(cls)
Extension("objc._objc", sourceFiles,
Extension("objc._objc", sourceFiles + LIBFFI_SOURCEFILES,
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, extensions return [], []
], extra_link_args=[ '-g', '-framework', 'Foundation' ])
] + LIBFFI_CFLAGS, extra_link_args=[ '-g', '-framework', 'Foundation', ] + LINK_OPT_STRIP + LIBFFI_LDFLAGS)
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, extensions return [], []
]),
] + LINK_OPT_STRIP),
def IfFrameWork(name, packages, extensions): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ if os.path.exists(os.path.join('/System/Library/Frameworks/', name)): return packages, extensions if os.path.exists(os.path.join('/Library/Frameworks/', name)): return packages, extensions return [], []
req_ver = [ 2, 2] if sys.version_info[0] < req_ver[0] or ( sys.version_info[0] == req_ver[0] and sys.version_info[1] < req_ver[1]):
req_ver = (2, 2) if sys.version_info < req_ver:
def subprocess(taskName, cmd, validRes=None): print "Performing task: %s" % (taskName,) fd = os.popen(cmd, 'r') for ln in fd.xreadlines(): sys.stdout.write(ln) res = fd.close() if res is not validRes: sys.stderr.write("Task '%s' failed [%d]\n"%(taskName, res)) sys.exit(1)
if ' ' in os.path.realpath(LIBFFI_SOURCES): print >>sys.stderr, "LIBFFI can not build correctly in a path that contains spaces." print >>sys.stderr, "This limitation includes the entire path (all parents, etc.)" print >>sys.stderr, "Move the PyObjC and libffi source to a path without spaces and build again." sys.exit(1)
def subprocess(taskName, cmd, validRes=None): print "Performing task: %s" % (taskName,) fd = os.popen(cmd, 'r') for ln in fd.xreadlines(): sys.stdout.write(ln) res = fd.close() if res is not validRes: sys.stderr.write("Task '%s' failed [%d]\n"%(taskName, res)) sys.exit(1)
writer.writeln()
def _printClass(self, writer, clsInfo): nibs = clsInfo.nibs if len(nibs) > 1: nibs[-2] = nibs[-2] + " and " + nibs[-1] del nibs[-1] nibs = ", ".join(nibs) writer.writeln("# class defined in %s" % nibs) writer.writeln("class %s(AutoBaseClass):" % clsInfo.name) writer.indent() writer.writeln("# the actual base class is %s" % clsInfo.super) outlets = clsInfo.outlets actions = clsInfo.actions if outlets: writer.writeln("# The following outlets are added to the class:") outlets.sort() for o in outlets: writer.writeln("# %s" % o) #writer.writeln("%s = ivar('%s')" % (o, o)) writer.writeln() if not actions: writer.writeln("pass") writer.writeln() else: writer.writeln() if actions: actions.sort() for a in actions: writer.writeln("def %s(self, sender):" % a) writer.indent() writer.writeln("pass") writer.dedent() writer.writeln() writer.writeln() writer.dedent()
print `container.storedObject()`, `type(container.storedObject())`
def testNSDecimalNumber(self): container = OC_TestIdentity.alloc().init()
elif funcName.startswith('removeObjectFrom') and funcName.endswith('AtIndex_'): return selector(func, signature='v@:i')
def accessor(func): """ Return an Objective-C method object that is conformant with key-value coding and key-value observing. """ if not isinstance(func, type(accessor)): raise ValueError, '%s is not a function'%(func,) argCount = func.func_code.co_argcount funcName = func.func_name if argCount == 3: if funcName.startswith('insertObject_in') and funcName.endswith('AtIndex_'): return selector(func, signature='v@:@i') elif funcName.startswith('removeObjectFrom') and funcName.endswith('AtIndex_'): return selector(func, signature='v@:i') elif funcName.startswith('replaceObjectIn') and funcName.endswith('AtIndex_withObject_'): return selector(func, signature='v@:i@') elif funcName.startswith('validate') and funcName.endswith('_error_'): return selector(func, signature='c@:N^@o^@') raise ValueError, "Too many arguments to function '%s'. Cannot create selector." % foo.func_name elif argCount == 2: if funcName.startswith('objectIn') and funcName.endswith('AtIndex_'): return selector(func, signature='@@:i') elif funcName.startswith('get') and funcName.endswith('_range_'): return selector(func, signature='@@:{_NSRange=ii}') return selector(func, signature="v@:@") elif argCount == 1: if func.func_name.startswith('countOf'): return selector(func, signature="i@:") return selector(func, signature="@@:") elif argCount == 0: raise ValueError, "Too few arguments to function '%s'. Cannot create selector." % foo.func_name else: raise ValueError, "Too many arguments to function '%s'. Cannot create selector." % foo.func_name
scripts = [ 'Scripts/nibclassbuilder', ],
def package_version(): fp = open('Modules/objc/pyobjc.h', 'r') for ln in fp.readlines(): if ln.startswith('#define OBJC_VERSION'): fp.close() return ln.split()[-1][1:-1] raise ValueError, "Version not found"
self.NSObjectInstance = objc.runtime.NSObject.alloc()
self.NSObjectInstance = objc.runtime.NSObject.alloc().init()
def setUp(self): self.NSObjectInstance = objc.runtime.NSObject.alloc()
author = "bbum, RonaldO, SteveM, many others stretching back through the reachtes of time...",
author = "bbum, RonaldO, SteveM, LeleG, many others stretching back through the reaches of time...",
def package_version(): fp = open('Modules/objc/pyobjc.h', 'r') for ln in fp.readlines(): if ln.startswith('#define OBJC_VERSION'): fp.close() return ln.split()[-1][1:-1] raise ValueError, "Version not found"
def debug(fn): rval = maybeutf(fn) print fn, rval return rval return debug
return maybeutf
def maybeutf(fn): header = file(fn).read(4) if header.startswith(codecs.BOM_UTF8): return 'utf_8' elif header.startswith(codecs.BOM_UTF16_BE): return 'utf_16_be' elif header.startswith(codecs.BOM_UTF16_LE): return 'utf_16_le' # some hacks to guess BOM-less UTF-16 text elif header[0::2] == '\x00\x00' and header[1::2] != '\x00\x00': return 'utf_16_be' elif header[1::2] == '\x00\x00' and header[0::2] != '\x00\x00': return 'utf_16_le' # anything else is undetermined, can't match # utf-8 against <?xm because it's the same in # all of the latin/romanish codecs firstline = file(fn).readline() if firstline.startswith('<?xml version="1.0" encoding="UTF-8"?>'): return 'utf_8' if firstline.startswith('// !$*UTF8*$!'): return 'utf_8' return encoding
print "typedef int (*superfunc)();"
print "typedef int (*superfunc)(int);"
print "typedef int (*superfunc)();"
def doTemplateInfo(aFile, options): if not options.doReverse: basename, extension = os.path.splitext(aFile) encoding = ENCODINGS.get(extension, lambda fn:None)(aFile) doFileSubstitution(aFile, encoding, FORWARDTRANSLATOR)
def doTemplateInfo(aFile, options, translator): basename, extension = os.path.splitext(aFile) encoding = ENCODINGS.get(extension, lambda fn:None)(aFile) doFileSubstitution(aFile, encoding, translator)
def doTemplateInfo(aFile, options): if not options.doReverse: basename, extension = os.path.splitext(aFile) encoding = ENCODINGS.get(extension, lambda fn:None)(aFile) doFileSubstitution(aFile, encoding, FORWARDTRANSLATOR)
specialCommand(path, options)
specialCommand(path, options, translator)
def doSubstitutions(dirName, aName, options): if options.doReverse: translator = REVERSETRANSLATOR else: translator = FORWARDTRANSLATOR path = os.path.join(dirName, aName) if os.path.isdir(path): return specialCommand = SPECIALFILES.get(aName) if specialCommand is not None: specialCommand(path, options) return basename, extension = os.path.splitext(path) encoding = ENCODINGS.get(extension, lambda fn:None)(path) if encoding is None: error("*WARN* Skipping unknown file with uknown type: %s", path) else: info('Processing %s....', aName) doFileSubstitution(path, encoding, translator) if options.makeWorking and (extension in WORKINGCOPYFILES): info('Making working copy of %s...', path) tail = aName.split("_", 1)[1] targetFile = os.path.join(dirName, "xcPROJECTNAMExc_%s" % (tail,)) inFile = codecs.EncodedFile(file(path, "rb"), encoding) outFile = codecs.EncodedFile(file(targetFile, 'wb'), encoding) if extension in CTYPEFILES: outFile.write(SUBSTITUTIONMESSAGE % dict(name = aName)) for line in inFile: outFile.write(line) inFile.close() outFile.close()
doFileSubstitution(path, encoding, translator) if options.makeWorking and (extension in WORKINGCOPYFILES): info('Making working copy of %s...', path) tail = aName.split("_", 1)[1] targetFile = os.path.join(dirName, "xcPROJECTNAMExc_%s" % (tail,)) inFile = codecs.EncodedFile(file(path, "rb"), encoding) outFile = codecs.EncodedFile(file(targetFile, 'wb'), encoding) if extension in CTYPEFILES: outFile.write(SUBSTITUTIONMESSAGE % dict(name = aName)) for line in inFile: outFile.write(line) inFile.close() outFile.close()
if options.makeWorking and (extension in WORKINGCOPYFILES) and not options.doReverse and aName.split("_", 1)[0] == 'xcPROJECTNAMExc': deletePath(path) else: doFileSubstitution(path, encoding, translator) if options.makeWorking and (extension in WORKINGCOPYFILES) and options.doReverse: tail = aName.split("_", 1)[1] targetFile = os.path.join(dirName, "xcPROJECTNAMExc_%s" % (tail,)) info('Making working copy of %s to %s...', path, targetFile) inFile = codecs.EncodedFile(file(path, "rb"), encoding) outFile = codecs.EncodedFile(file(targetFile, 'wb'), encoding) if extension in CTYPEFILES: outFile.write(SUBSTITUTIONMESSAGE % dict(name = aName)) for line in inFile: outFile.write(line) inFile.close() outFile.close()
def doSubstitutions(dirName, aName, options): if options.doReverse: translator = REVERSETRANSLATOR else: translator = FORWARDTRANSLATOR path = os.path.join(dirName, aName) if os.path.isdir(path): return specialCommand = SPECIALFILES.get(aName) if specialCommand is not None: specialCommand(path, options) return basename, extension = os.path.splitext(path) encoding = ENCODINGS.get(extension, lambda fn:None)(path) if encoding is None: error("*WARN* Skipping unknown file with uknown type: %s", path) else: info('Processing %s....', aName) doFileSubstitution(path, encoding, translator) if options.makeWorking and (extension in WORKINGCOPYFILES): info('Making working copy of %s...', path) tail = aName.split("_", 1)[1] targetFile = os.path.join(dirName, "xcPROJECTNAMExc_%s" % (tail,)) inFile = codecs.EncodedFile(file(path, "rb"), encoding) outFile = codecs.EncodedFile(file(targetFile, 'wb'), encoding) if extension in CTYPEFILES: outFile.write(SUBSTITUTIONMESSAGE % dict(name = aName)) for line in inFile: outFile.write(line) inFile.close() outFile.close()
lines = bytes.split(u'\n')
lines = bytes.splitlines(True)
def doFileSubstitution(aFile, encoding, translator): _tempFile = tempfile.TemporaryFile() # do the translation debug('encoding is: %s', encoding) inFile = codecs.getreader(encoding)(file(aFile, "rb")) outFile = codecs.getwriter(encoding)(_tempFile) try: for line in inFile: tline = translator(line) outFile.write(tline) except NotImplementedError: BUFFER = 16384 bytes = inFile.read(BUFFER) while bytes: lines = bytes.split(u'\n') bytes = lines.pop() for line in lines: tline = translator(line) outFile.write(tline) newbytes = inFile.read(BUFFER) bytes += newbytes if not newbytes and bytes: bytes += u'\n' inFile.close() # do the copy _tempFile.seek(0) copyFile = file(aFile, "wb") shutil.copyfileobj(_tempFile, copyFile) copyFile.close() _tempFile.close()
info("Removing '%s'...", dest) shutil.rmtree(dest)
deletePath(dest)
def main(): parser = build_parser() options, args = parser.parse_args() if not args: parser.print_help() return if len(args) != 2: parser.error("Must specify both a source and destination") return if options.verbose: hdlr = logging.StreamHandler() fmt = logging.Formatter('%(message)s') hdlr.setFormatter(fmt) logger = logging.getLogger() logger.addHandler(hdlr) logger.setLevel(logging.INFO) else: logging.basicConfig() source, dest = map(os.path.normpath, args) if source == dest: parser.error("Source and destination may not be the same.") return if os.path.exists(dest): if options.killDest: info("Removing '%s'...", dest) shutil.rmtree(dest) else: parser.error("Destination already exists. -k to destroy or use different destination.") return info("Copying from '%s' to '%s'....", source, dest) shutil.copytree(source, dest) simplePathWalker(dest, killNasties, options) simplePathWalker(dest, doSubstitutions, options)
self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.isInstance(PyObjC_TestClassAndInstanceInstanceOverride), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.alloc().init().isInstance(), objc.NO)
self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.pyobjc_classMethods.isInstance(), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.alloc().init().pyobjc_instanceMethods.isInstance(), objc.NO)
def testClassAndInstanceInstanceOverrideWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.isInstance(PyObjC_TestClassAndInstanceInstanceOverride), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceInstanceOverride.alloc().init().isInstance(), objc.NO)
self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.isInstance(PyObjC_TestClassAndInstanceClassOverride), objc.YES) self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.pyobjc_classMethods.isInstance(), objc.YES) self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.alloc().init().pyobjc_instanceMethods.isInstance(), objc.YES)
def testClassAndInstanceClassOverrideWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.isInstance(PyObjC_TestClassAndInstanceClassOverride), objc.YES) self.assertEquals(PyObjC_TestClassAndInstanceClassOverride.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstanceSubclass.isInstance(PyObjC_TestClassAndInstanceSubclass), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceSubclass.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstanceSubclass.pyobjc_classMethods.isInstance(), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceSubclass.alloc().init().pyobjc_instanceMethods.isInstance(), objc.YES)
def testClassAndInstanceSubclassWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstanceSubclass.isInstance(PyObjC_TestClassAndInstanceSubclass), objc.NO) self.assertEquals(PyObjC_TestClassAndInstanceSubclass.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstance.isInstance(PyObjC_TestClassAndInstance), objc.NO) self.assertEquals(PyObjC_TestClassAndInstance.alloc().init().isInstance(), objc.YES)
self.assertEquals(PyObjC_TestClassAndInstance.pyobjc_classMethods.isInstance(), objc.NO) self.assertEquals(PyObjC_TestClassAndInstance.alloc().init().pyobjc_instanceMethods.isInstance(), objc.YES)
def testClassAndInstanceWorkaround(self): self.assertEquals(PyObjC_TestClassAndInstance.isInstance(PyObjC_TestClassAndInstance), objc.NO) self.assertEquals(PyObjC_TestClassAndInstance.alloc().init().isInstance(), objc.YES)
"-O0", "-g",
def IfFrameWork(name, packages, extensions, headername=None): """ Return the packages and extensions if the framework exists, or two empty lists if not. """ for pth in ('/System/Library/Frameworks', '/Library/Frameworks'): basedir = os.path.join(pth, name) if os.path.exists(basedir): if (headername is None) or os.path.exists(os.path.join(basedir, "Headers", headername)): return packages, extensions return [], []
>>> MyEnumerator <objective-c class MyEnumerator at 0x350fb0>
... def __del__(self):
NSApp.setDelegate_( AppDelegate.alloc().init() )
delegate = AppDelegate.alloc().init() NSApp.setDelegate_(delegate)
def main(): NSApp = NSApplication.sharedApplication() NSApp.setDelegate_( AppDelegate.alloc().init() ) win = NSWindow.alloc() frame = ((200.0, 300.0), (250.0, 100.0)) win.initWithContentRect_styleMask_backing_defer_ (frame, 15, 2, 0) win.setTitle_ ('HelloWorld') win.setLevel_ (3) # floating window hel = NSButton.alloc().initWithFrame_ (((10.0, 10.0), (80.0, 80.0))) win.contentView().addSubview_ (hel) hel.setBezelStyle_( 4 ) hel.setTitle_( 'Hello!' ) hel.setTarget_( NSApp.delegate() ) hel.setAction_( "sayHello:" ) beep = NSSound.alloc() beep.initWithContentsOfFile_byReference_( '/System/Library/Sounds/Tink.Aiff', 1 ) hel.setSound_( beep ) bye = NSButton.alloc().initWithFrame_ (((100.0, 10.0), (80.0, 80.0))) win.contentView().addSubview_ (bye) bye.setBezelStyle_( 4 ) bye.setTarget_ (NSApp) bye.setAction_ ('stop:') bye.setEnabled_ ( 1 ) bye.setTitle_( 'Goodbye!' ) adios = NSSound.alloc() adios.initWithContentsOfFile_byReference_( '/System/Library/Sounds/Basso.aiff', 1 ) bye.setSound_( adios ) win.display() win.orderFrontRegardless() ## but this one does NSApp.run()
class TestTypeStr(unittest.TestCase):
class PyOCTestTypeStr(unittest.TestCase):
def makeCFloat(value): """ C floats and doubles have a different representation, this function returns the result of converting a python float (== C double) to a C float and back. """ return struct.unpack('f',struct.pack('f', value))[0]
class TestSimpleReturns(unittest.TestCase):
class PyOCTestSimpleReturns(unittest.TestCase):
def testAll(self):
class TestSimpleArguments(unittest.TestCase):
class PyOCTestSimpleArguments(unittest.TestCase):
def testStruct2(self): obj = OC_TestClass1.new()
class TestByReferenceArguments(unittest.TestCase):
class PyOCTestByReferenceArguments(unittest.TestCase):
def testStruct2(self): self.assertEquals(self.obj.dummy2Arg_(((1,2,3,4),)), ((8,6,4,2),))
class TestDecimalNumber (unittest.TestCase):
if isinstance(NSDecimalNumber.decimalNumberWithString_(u'1.00'), NSDecimalNumber): class TestDecimalNumber (unittest.TestCase):
def testPropertyList2(self): d = NSMutableDictionary.dictionary()
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00")
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00") self.assert_(isinstance(o, NSDecimalNumber))
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00")
self.assert_(isinstance(o, NSDecimalNumber))
else: class TestDecimalNumber (unittest.TestCase): def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00") self.assert_(isinstance(o, NSDecimal))
def testProxy (self): o = NSDecimalNumber.decimalNumberWithString_(u"1.00")
'%(varname)s',
'&%(varname)s',
def is_id(typestr): # Remove protocol 'declarations' (id <NSObject, NSString>) typestr = PROT_MATCHER.sub('', typestr).strip() if typestr == 'id': return 1 elif typestr[-1] != '*': return 0 try: objc.lookup_class(typestr[:-1]) return 1 except: return 0
fp.write('\t{ "%(funcname)s", (PyCFunction)objc_%(funcname)s, METH_VARARGS, "%(funcproto)s" }, \\\n'%{'funcname':f[0], 'funcproto':f[1]})
fp.write('\t{ "%(funcname)s", (PyCFunction)objc_%(funcname)s, METH_VARARGS|METH_KEYWORDS, "%(funcproto)s" }, \\\n'%{'funcname':f[0], 'funcproto':f[1]})
def process_list(fp, lst): ok_count = 0 total_count = 0 funcs=[] fp.write(HDR) for l in lst: l = l.strip() if not l: continue if l[0] == '#': continue total_count += 1 try: sys.stderr.write("Converting '%s' ..."%l.strip()) sys.stderr.flush() funcs.append((process_function(fp, l), l)) sys.stderr.write("done\n") sys.stderr.flush() ok_count += 1 except ValueError, msg: sys.stderr.write("failed: %s\n"%msg) sys.stderr.flush() fp.write("\n") if not funcs: fp.write("#define METHOD_TABLE_ENTRIES\n") else: fp.write("#define METHOD_TABLE_ENTRIES \\\n") for f in funcs: fp.write('\t{ "%(funcname)s", (PyCFunction)objc_%(funcname)s, METH_VARARGS, "%(funcproto)s" }, \\\n'%{'funcname':f[0], 'funcproto':f[1]}) fp.write("\t/* END */\n") sys.stderr.write("Converted %d of %d functions\n"%(ok_count, total_count))
executable=${execdir}/%(executable)s
executable="${execdir}/%(executable)s"
def __load(): import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path)
main=${resdir}/%(mainprogram)s PYTHONPATH=$resdir
main="${resdir}/%(mainprogram)s" PYTHONPATH="$resdir"
def __load(): import imp, sys, os for p in sys.path: path = os.path.join(p, "%(filename)s") if os.path.exists(path): break else: assert 0, "file not found: %(filename)s" mod = imp.load_dynamic("%(name)s", path)
) CONVENIENCE_METHODS['removeObject:'] = ( ('remove', lambda self, elem: self.removeObject_(container_wrap(elem))),
def popitem_setObject_forKey_(self): try: k = self[iter(self).next()] except StopIteration: raise KeyError, "popitem on an empty %s" % (type(self).__name__,) else: return (k, self[k])
module = __import__(modName)
try: module = __import__(modName) except ImportError, msg: print "SKIP %s: %s"%(modName, msg) continue
def importExternalTestCases(pathPattern="test_*.py", root=".", package=None): """ Import all unittests in the PyObjC tree starting at 'root' """ testFiles = recursiveGlob(root, pathPattern) testModules = map(lambda x:x[len(root)+1:-3].replace('/', '.'), testFiles) if package is not None: testModules = [(package + '.' + m) for m in testModules] suites = [] for modName in testModules: module = __import__(modName) if '.' in modName: for elem in modName.split('.')[1:]: module = getattr(module, elem) s = unittest.defaultTestLoader.loadTestsFromModule(module) suites.append(s) return unittest.TestSuite(suites)
if not os.path.isdir(self.build_dir): self.warn("'%s' does not exist -- cannot test" % self.build_dir) return
def test (self): if not os.path.isdir(self.build_dir): self.warn("'%s' does not exist -- cannot test" % self.build_dir) return
print 'checking', theURL, cachePolicy, timeoutInterval
def initWithURL_cachePolicy_timeoutInterval_(self, theURL, cachePolicy, timeoutInterval): print 'checking', theURL, cachePolicy, timeoutInterval try: theURL = idnSnitch.checkURL_(theURL) except Exception, e: import traceback traceback.print_exc() NSLog(u"%s: %s" % (e.__class__.__name__, e)) print 'checked' self.retain() res = oldIMP(self, theURL, cachePolicy, timeoutInterval) print 'got res' return res
print 'checked'
def initWithURL_cachePolicy_timeoutInterval_(self, theURL, cachePolicy, timeoutInterval): print 'checking', theURL, cachePolicy, timeoutInterval try: theURL = idnSnitch.checkURL_(theURL) except Exception, e: import traceback traceback.print_exc() NSLog(u"%s: %s" % (e.__class__.__name__, e)) print 'checked' self.retain() res = oldIMP(self, theURL, cachePolicy, timeoutInterval) print 'got res' return res
print 'got res'
def initWithURL_cachePolicy_timeoutInterval_(self, theURL, cachePolicy, timeoutInterval): print 'checking', theURL, cachePolicy, timeoutInterval try: theURL = idnSnitch.checkURL_(theURL) except Exception, e: import traceback traceback.print_exc() NSLog(u"%s: %s" % (e.__class__.__name__, e)) print 'checked' self.retain() res = oldIMP(self, theURL, cachePolicy, timeoutInterval) print 'got res' return res
print 'checkURL', self, anURL
def checkURL_(self, anURL): print 'checkURL', self, anURL if anURL is None: return anURL host = anURL.host() if host is None: return anURL if encodings.idna.uace_prefix in host: uni = u'.'.join([encodings.idna.ToUnicode(part) for part in host.split(u'.')]) shouldDeny = self.HOSTS.get(uni) if shouldDeny is None: res = [] self.performSelectorOnMainThread_withObject_waitUntilDone_( 'runDialog:', ( res, ( u'IDN URL Detected', MESSAGE % (uni, uni.encode('unicode_escape'), anURL), u'Allow', u'Deny', None, ), ), True, ) shouldDeny = res.pop() self.HOSTS[uni] = shouldDeny if shouldDeny: return NSURL.URLWithString_(u'about:blank') return anURL
print "*** Restored handlers and resignaling." % signum
print "*** Restored handlers and resignaling."
def dumpHandler(signum, frame): resetFatalSignals() print "*** Handling fatal signal '%d'." % signum traceback.print_stack(frame) print "*** Restored handlers and resignaling." % signum os.kill(os.getpid(), signum)
self.assertEquals("'rtfx'", Foundation.NSFileTypeForHFSTypeCode(fourchar))
if sys.byteorder == 'little': self.assertEquals("'xftr'", Foundation.NSFileTypeForHFSTypeCode(fourchar)) else: self.assertEquals("'rtfx'", Foundation.NSFileTypeForHFSTypeCode(fourchar))
def testNSFileTypeForHFSTypeCode(self): self.assertEquals("'rtfx'", Foundation.NSFileTypeForHFSTypeCode('rtfx'))
- Attribute or accessor 'key'
- Accessor or attribute 'key' - Accessor or attribute 'isKey'
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these exist, raise KeyError """ if isinstance(obj, (objc.objc_object, objc.objc_class)): try: return obj.valueForKey_(key) except ValueError, msg: # This is not entirely correct, should check if this # is the right kind of ValueError before translating raise KeyError, str(msg) try: m = getattr(obj, "get" + key.capitalize()) except AttributeError: pass else: return m() try: m = getattr(obj, "get_" + key) except AttributeError: pass else: return m() try: m = getattr(obj, key) if isinstance(m, types.MethodType): if m.im_self is obj: return m() else: return m elif isinstance(m, types.BuiltinMethodType): # Can't access the bound self of methods of builtin classes :-( return m() elif isinstance(m, objc.selector): if m.self is obj: return m() else: return m else: return m except AttributeError: pass try: m = getattr(obj, "_" + key) if isinstance(m, types.MethodType): return m() else: return m except AttributeError: pass raise KeyError, "Key %s does not exist"%(key,)
m = getattr(obj, "get" + key.capitalize())
m = getattr(obj, "get" + keyCaps(key))
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these exist, raise KeyError """ if isinstance(obj, (objc.objc_object, objc.objc_class)): try: return obj.valueForKey_(key) except ValueError, msg: # This is not entirely correct, should check if this # is the right kind of ValueError before translating raise KeyError, str(msg) try: m = getattr(obj, "get" + key.capitalize()) except AttributeError: pass else: return m() try: m = getattr(obj, "get_" + key) except AttributeError: pass else: return m() try: m = getattr(obj, key) if isinstance(m, types.MethodType): if m.im_self is obj: return m() else: return m elif isinstance(m, types.BuiltinMethodType): # Can't access the bound self of methods of builtin classes :-( return m() elif isinstance(m, objc.selector): if m.self is obj: return m() else: return m else: return m except AttributeError: pass try: m = getattr(obj, "_" + key) if isinstance(m, types.MethodType): return m() else: return m except AttributeError: pass raise KeyError, "Key %s does not exist"%(key,)
try: m = getattr(obj, key) if isinstance(m, types.MethodType): if m.im_self is obj: return m() else: return m
for keyName in (key, "is" + keyCaps(key)): try: m = getattr(obj, keyName) except AttributeError: continue if isinstance(m, types.MethodType) and m.im_self is obj: return m()
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these exist, raise KeyError """ if isinstance(obj, (objc.objc_object, objc.objc_class)): try: return obj.valueForKey_(key) except ValueError, msg: # This is not entirely correct, should check if this # is the right kind of ValueError before translating raise KeyError, str(msg) try: m = getattr(obj, "get" + key.capitalize()) except AttributeError: pass else: return m() try: m = getattr(obj, "get_" + key) except AttributeError: pass else: return m() try: m = getattr(obj, key) if isinstance(m, types.MethodType): if m.im_self is obj: return m() else: return m elif isinstance(m, types.BuiltinMethodType): # Can't access the bound self of methods of builtin classes :-( return m() elif isinstance(m, objc.selector): if m.self is obj: return m() else: return m else: return m except AttributeError: pass try: m = getattr(obj, "_" + key) if isinstance(m, types.MethodType): return m() else: return m except AttributeError: pass raise KeyError, "Key %s does not exist"%(key,)
elif isinstance(m, objc.selector): if m.self is obj: return m() else: return m
elif isinstance(m, objc.selector) and m.self is obj: return m()
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these exist, raise KeyError """ if isinstance(obj, (objc.objc_object, objc.objc_class)): try: return obj.valueForKey_(key) except ValueError, msg: # This is not entirely correct, should check if this # is the right kind of ValueError before translating raise KeyError, str(msg) try: m = getattr(obj, "get" + key.capitalize()) except AttributeError: pass else: return m() try: m = getattr(obj, "get_" + key) except AttributeError: pass else: return m() try: m = getattr(obj, key) if isinstance(m, types.MethodType): if m.im_self is obj: return m() else: return m elif isinstance(m, types.BuiltinMethodType): # Can't access the bound self of methods of builtin classes :-( return m() elif isinstance(m, objc.selector): if m.self is obj: return m() else: return m else: return m except AttributeError: pass try: m = getattr(obj, "_" + key) if isinstance(m, types.MethodType): return m() else: return m except AttributeError: pass raise KeyError, "Key %s does not exist"%(key,)
except AttributeError: pass try: m = getattr(obj, "_" + key) if isinstance(m, types.MethodType): return m() else: return m except AttributeError: pass raise KeyError, "Key %s does not exist"%(key,)
try: return getattr(obj, "_" + key) except AttributeError: raise KeyError, "Key %s does not exist" % (key,)
def getKey(obj, key): """ Get the attribute referenced by 'key'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accesors at tried (in this order): - Accessor 'getKey' - Accesoor 'get_key' - Attribute or accessor 'key' - Attribute '_key' If none of these exist, raise KeyError """ if isinstance(obj, (objc.objc_object, objc.objc_class)): try: return obj.valueForKey_(key) except ValueError, msg: # This is not entirely correct, should check if this # is the right kind of ValueError before translating raise KeyError, str(msg) try: m = getattr(obj, "get" + key.capitalize()) except AttributeError: pass else: return m() try: m = getattr(obj, "get_" + key) except AttributeError: pass else: return m() try: m = getattr(obj, key) if isinstance(m, types.MethodType): if m.im_self is obj: return m() else: return m elif isinstance(m, types.BuiltinMethodType): # Can't access the bound self of methods of builtin classes :-( return m() elif isinstance(m, objc.selector): if m.self is obj: return m() else: return m else: return m except AttributeError: pass try: m = getattr(obj, "_" + key) if isinstance(m, types.MethodType): return m() else: return m except AttributeError: pass raise KeyError, "Key %s does not exist"%(key,)
return getattr(obj, SETVALUEFORKEY)(value, key)
getattr(obj, SETVALUEFORKEY)(value, key) return
def setKey(obj, key, value): """ Set the attribute referenced by 'key' to 'value'. The key is used to build the name of an attribute, or attribute accessor method. The following attributes and accessors are tried (in this order): - Accessor 'setKey' - Accessor 'set_key' - Attribute '_key' - Attribute 'key' Raises KeyError if the key doesn't exist. """ if isinstance(obj, (objc.objc_object, objc.objc_class)): try: return getattr(obj, SETVALUEFORKEY)(value, key) except ValueError, msg: raise KeyError, str(msg) try: m = getattr(obj, 'set' + key.capitalize()) except AttributeError: pass else: m(value) return try: m = getattr(obj, 'set_' + key) except AttributeError: pass else: m(value) return try: o = getattr(obj, "_" + key) except AttributeError: pass else: setattr(obj, "_" + key, value) return try: setattr(obj, key, value) except AttributeError: raise KeyError, "Key %s does not exist"%(key,)