def __init__(self, name='Custom', ID='', width=612, height=792, margins=None, printer=None): '''New L{PaperCustom} from paper attributes. @raise TypeError: Invalid I{margins} or I{printer}. ''' h = float(height) w = float(width) z = 'x'.join(map(zfstr, (w, h))) if name: n = str(name) i = str(ID) or '%s %s' % (name, z) else: n = z i = str(ID) or z if margins is None: m = PaperMargins() elif isinstanceOf(margins, PaperMargins, name='margins'): m = PaperMargins(margins) if printer is None: p = get_printer() elif isinstanceOf(printer, Printer, name='printer'): p = printer pm = PMPaper_t() self._libPCcall(libPC.PMPaperCreateCustom, p, NSStr(n), NSStr(i), w, h, m, byref(pm)) Paper.__init__(self, pm)
def app(self, app): '''Set the app. ''' if app not in (None,): from apps import App isinstanceOf(app, App, name='app') self._app = app
def append(self, menu): '''Add a menu to this app's menu bar. @param menu: The menu to add (L{Menu}). @note: The first menu item of the bar menu is provided by default. ''' isinstanceOf(menu, Menu, name='menu') if self._menubar is None: # create the menu bar, once b = MenuBar(app=self) m = Menu(title=self.title) m.append( # note key modifier cmd=True is the default Item('Full ' + 'Screen', key='f', ctrl=True), # Ctrl-Cmd-F, Esc to exit ItemSeparator(), Item('Hide ' + self.title, self.menuHide_, key='h'), # Cmd-H Item('Hide Others', self.menuOther_, key='h', alt=True), # Alt-Cmd-H ItemSeparator(), Item('Quit ' + self.title, self.menuTerminate_, key='q'), # Cmd-Q ) b.append(m) b.main(app=self) self._menubar = b self._menubar.append(menu)
def get_selectornameof(sel): '''Get the name of an ObjC selector. @param sel: The selector (L{SEL_t}). @return: The selector name (C{str}) if found, C{""} otherwise. ''' isinstanceOf(sel, SEL_t, name='sel') return bytes2str(libobjc.sel_getName(sel)) or ''
def NS(self, ns): '''Set the ObjC instance (C{NS...}). ''' if not isNone(ns): # see also .nstypes.nsOf isinstanceOf(ns, ObjCInstance, c_struct_t, ObjC_t, name='ns') elif isinstanceOf(self.NS, ObjCInstance): # self.NS.release() pass self._NS = ns
def __eq__(self, other): isinstanceOf(other, _Types.List, Tuple, list, tuple, name='other') if len(self) == len(other): for s, o in zip(self, other): if o != s: break else: return True return False
def init(self, window): '''Initialize the allocated C{NSWindowDelegate}. @note: I{MUST} be called as C{.alloc().init(...)}. ''' isinstanceOf(window, Window, name='window') # self = ObjCInstance(send_message('NSObject', 'alloc')) self = ObjCInstance(send_super_init(self)) self.window = window return self
def init(self, app): '''Initialize the allocated C{NSApplicationDelegate}. @note: I{MUST} be called as C{.alloc().init(...)}. ''' isinstanceOf(app, App, name='app') # self = ObjCInstance(send_message('NSObject', 'alloc')) self = ObjCInstance(send_super_init(self)) self.app = app return self
def get_superclass(clas): '''Get the ObjC super-class of an ObjC class. @param clas: The class (L{Class_t}). @return: The super-class (L{Class_t}), None otherwise. ''' isinstanceOf(clas, Class_t, name='clas') try: supr = _super_cache[clas.value] except KeyError: supr = libobjc.class_getSuperclass(clas) or None _super_cache[clas.value] = supr return supr
def __init__(self, name_ns_pm=None): '''New L{Printer} from a printer name (C{str}), C{NSPrinter} or C{PMPrinter}. @raise TypeError: Invalid I{name_ns_pm}. @raise PrintError: No printer with name I{name_ns_pm}. ''' if not name_ns_pm: # generic printer _PM_Type0.__init__(self, PMPrinter_t()) self._libPCcall(libPC.PMCreateGenericPrinter) pm = self.PM ns = _nsPrinter('Generic', pm) elif isinstance(name_ns_pm, _Strs): for p in get_printers(): if p.name == name_ns_pm: pm = p.PM ns = _nsPrinter(p.name, pm) break else: raise PrintError('no such %s: %r' % (Printer.__name__, name_ns_pm)) elif isinstanceOf(name_ns_pm, PMPrinter_t): pm = name_ns_pm ns = _nsPrinter(cfString2str(libPC.PMPrinterGetName(pm)), pm) elif isObjCInstanceOf(name_ns_pm, NSPrinter, name='name_ns_pm'): ns = name_ns_pm # special method name due to leading underscore pm = send_message(ns, '_printer', restype=PMPrinter_t) _PM_Type0.__init__(self, pm) self._NS = ns # _RO
def nsLog(ns_fmt, *ns_args): '''Formatted ObjC write to the console. @param ns_fmt: A printf-like format string (L{NSStr}). @param ns_args: Optional arguments to format (C{all positional}). @note: The I{ns_fmt} and all I{ns_args} must be C{NS...} ObjC instances. ''' if isinstanceOf(ns_fmt, NSStr, name='ns_fmt'): for n, ns in enumerate(ns_args): if not isinstance(ns, (ObjCInstance, c_void_p)): n = 'ns_arg[%s]' % (n, ) # raise error if not isinstanceOf(ns, ObjCInstance, name=n): break else: # XXX all ns_fmt %-types should be %@? libFoundation.NSLog(ns_fmt, *ns_args) # variadic, printf-like
def point(self, point): if isinstance(point, (tuple, list)): if len(point) != 2: raise ValueError('invalid %s: %r' % ('point', point)) self.NS = NSPoint_t(*point) elif isinstance(point, Point): self.NS = point.NS elif isinstanceOf(point, NSPoint_t, name='point'): self.NS = point
def update(self, *other, **kwds): '''Update, like C{dict.update}, except I{other} must be a C{dict}, L{Dict} or L{FrozenDict}. @raise TypeError: Invalid type of I{other}. @see: <http://Docs.Python.org/3/library/stdtypes.html#dict.update> ''' other, kwds = _dict_kwds(other, kwds, 'other') if other: if isinstanceOf(other, Dict, FrozenDict): self.NS.addEntriesFromDictionary_(other.NS) elif isObjCInstanceOf(other, NSMutableDictionary, NSDictionary): self.NS.addEntriesFromDictionary_(other) elif isinstanceOf(other, dict, name='other'): for k, v in other.items(): self[k] = v # self.__setitem__ for k, v in kwds.items(): self[k] = v # self.__setitem__
def nsLogf(fmt, *args): '''Formatted write to the console. @param fmt: A printf-like format string (C{str}). @param args: Optional arguments to format (C{all positional}). ''' if isinstanceOf(fmt, _ByteStrs, name='fmt'): if args: fmt %= args libFoundation.NSLog(NSStr(fmt)) # variadic, printf-like
def _printers(printers): '''(INTERNAL) Printer generator. ''' if not printers: printers = (get_printer(),) elif not libPC: get_libPC() for p in printers: if isinstanceOf(p, Printer, name='printers'): yield p
def localname(self, printer=None): '''Get the paper's localized name for a printer (C{str}). @raise TypeError: Invalid I{printer}. ''' if not printer: pm = get_printer().PM elif isinstanceOf(printer, Printer, name='printer'): pm = printer.PM return self._2str(libPC.PMPaperCreateLocalizedName, pm)
def set2NS(py): '''Create an C{NSMutableSet} instance from a Python C{set}. @param py: The value (C{set}). @return: The ObjC instance (C{NSMutableSet}). @raise RuntimeError: If C{len} vs C{count} assertion failed. ''' if isinstanceOf(py, set, name='py'): return _set2NS(py)
def generator2NS(py): '''Create an C{NSArray} instance from a Python C{generator}. @param py: The value (C{generator}). @return: The ObjC instance (C{NSArray}). @raise RuntimeError: If C{len} vs C{count} assertion failed. ''' if isinstanceOf(py, _Generator, name='py'): return tuple2NS(tuple(py))
def float2NS(py): '''Create an C{NSNumber} instance from a Python C{float} or C{int}. @param py: The value (C{float} or C{int}). @return: The ObjC instance (C{NSDouble}). @raise TypeError: If C{py} not a C{float} or C{int}. ''' if isinstanceOf(py, float, *_Ints, name='py'): return NSDouble(float(py))
def size(self, size): '''Set the size (L{Size}, C{list}, C{tuple} or C{NSSize_t}). ''' if isinstance(size, (tuple, list)): if len(size) != 2: raise ValueError('invalid %s: %r' % ('size', size)) self.NS = NSSize_t(*size) elif isinstance(size, Size): self.NS = size.NS elif isinstanceOf(size, NSSize_t, name='size'): self.NS = size
def tuple2NS(py): '''Create an immutable C{NSArray} instance from a Python C{tuple}. @param py: The value (C{tuple}). @return: The ObjC instance (C{NSArray}). @raise RuntimeError: If C{len} vs C{count} assertion failed. ''' if isinstanceOf(py, tuple, list, name='py'): return _len2NS(py, NSArray.alloc().initWithArray_(_list2NS(py)), libCF.CFArrayGetCount)
def _nsPrinter(name, pm): '''(INTERNAL) New C{NSPrinter} instance. ''' if isinstanceOf(pm, PMPrinter_t, name='pm'): # NSStr(name) ns = send_message('NSPrinter', 'alloc', restype=Id_t) # _initWithName:printer:(Id_t, Id_t, SEL_t, Id_t, LP_Struct_t) # requires special selector handling due to leading underscore ns = send_message(ns, '_initWithName:printer:', NSStr(name), pm, restype=Id_t, argtypes=[Id_t, PMPrinter_t]) else: ns = None return ns
def frozenset2NS(py): '''Create an (immutable) C{NSSet} instance from a Python C{frozenset}. @param py: The value (C{frozenset}). @return: The ObjC instance (C{NSSet}). @raise RuntimeError: If C{len} vs C{count} assertion failed. ''' if isinstanceOf(py, frozenset, set, name='py'): return _len2NS(py, NSSet.alloc().initWithSet_(_set2NS(py)), libCF.CFSetGetCount)
def rect(self, rect): '''Set the rect (L{Rect}, C{list}, C{tuple} or C{NSRect[4]_t}). ''' if isinstance(rect, (tuple, list)): if len(rect) == 2: # assume (w, h) rect = (self._x, self._y) + tuple(rect) elif len(rect) != 4: raise ValueError('invalid %s: %r' % ('rect', rect)) self.NS = NSRect4_t(*rect) elif isinstance(rect, Rect): self.NS = rect.NS elif isinstanceOf(rect, NSRect_t, name='rect'): self.NS = rect
def __new__(cls, ns_str=''): '''New L{Str} from C{str}, L{Str} or C{NSStr[ing]}. ''' if isinstance(ns_str, Str): return ns_str elif isinstance(ns_str, _Strs): ns, py = str2NS(ns_str), ns_str elif isinstanceOf(ns_str, NSStr, name='ns_str'): ns, py = ns_str, nsString2str(ns_str) self = super(Str, cls).__new__(cls, py) self._NS = ns # _RO return self
def size2(self, bstr): '''Get the size of a string. @param bstr: The string (C{str}, C{bytes} or L{Str}). @return: 2-Tuple (width, height) in (C{float} or C{int}). ''' if isinstance(bstr, Str): ns = bstr.NS elif isinstance(bstr, _ByteStrs): ns = release(NSStr(bstr)) elif isinstanceOf(bstr, NSStr, name='bstr'): ns = bstr return flint(self.NS.widthOfString_(ns)), self.height
def get_classname(clas, dflt=missing): '''Get the name of an ObjC class. @param clas: The class (L{Class_t}). @return: The class name (C{str}). @raise ValueError: Invalid I{clas}, iff no I{dflt} provided. ''' if clas and isinstanceOf(clas, Class_t, name='clas'): return bytes2str(libobjc.class_getName(clas)) if dflt is missing: raise ValueError('no such %s: %r' % ('Class', clas)) return dflt
def bytes2NS(py): '''Create an C{NSData} instance from Python C{bytes}. @param py: The value (C{bytes}). @return: The ObjC instance (C{NSData}). @raise RuntimeError: If C{len} vs C{count} assertion failed. ''' def _NSData_length(ns): # XXX lambda ns: ns.length() return ns.length() if isinstanceOf(py, *_ByteStrs, name='py'): return _len2NS(py, NSData.dataWithBytes_length_(py, len(py)), _NSData_length)
def int2NS(py): '''Create an C{NSNumber} instance from a Python C{int} or C{long}. @param py: The value (C{int} or C{long}). @return: The ObjC instance (C{NSInt}, C{NSLong}, or C{NSLongLong}). @raise TypeError: If C{py} not an C{int} or C{long}. ''' if isinstanceOf(py, _Ints, name='py'): if abs(py) < 1 << 31: return NSInt(py) elif abs(py) < 1 << 63: return NSLong(py) else: return NSLongLong(py)
def __init__(self, margins_pm=None, bottom=0, left=0, right=0, top=0): '''New L{PaperMargins} from margin attributes. @raise TypeError: Invalid I{margins_pm}. ''' if not margins_pm: self.bottom = float(bottom) self.left = float(left) self.right = float(right) self.top = float(top) elif isinstanceOf(margins_pm, PaperMargins, PMRect_t, name='margins_pm'): self.bottom = float(margins_pm.bottom) self.left = float(margins_pm.left) self.right = float(margins_pm.right) self.top = float(margins_pm.top) self._PM = self