Пример #1
0
 def NSview(self, ns_view):
     '''Set this window's view (C{NSView...}).
     '''
     if not isNone(ns_view):
         isObjCInstanceOf(ns_view, NSScrollView, NSView, name='ns_view')
         self.NS.setContentView_(ns_view)
     self._NSview = ns_view
Пример #2
0
def ns2Window(ns):
    '''Get the L{Window} instance for an ObjC C{NSWindow} or
       C{NSNotification} instance.

       @param ns: The ObjC instance (C{NS...}).

       @return: The window instance (L{Window}).

       @raise AttributeError: Unexpected I{ns} type.

       @raise RuntimeError: L{Window} mismatch.

       @raise TypeError: Invalid I{ns} type.
    '''
    if isObjCInstanceOf(ns, NSWindow):
        u = ns.uniqueID()
    elif isObjCInstanceOf(ns, NSConcreteNotification, NSNotification, ns='ns'):
        u = ns.object().uniqueID()
    try:
        w = _Globals.Windows[u]
        if w._NSuniqID == u:
            return w
        t = '%r of %r' % (w._NSuniqID, w)
    except KeyError:
        t = None
    raise RuntimeError('%s %s %r vs %s' % (ns, '.uniqueID', u, t))
Пример #3
0
def nsBoolean2bool(ns, dflt=missing):  # XXX an NSBoolean method?
    '''Create a Python C{bool} from an C{NSBoolean}.

       @param ns: The C{NSBoolean} (L{ObjCInstance}).
       @keyword dflt: Default for a missing, unobtainable value (C{missing}).

       @return: The bool (C{bool}) of I{dlft}.

       @raise TypeError: Unexpected C{NumberType}.
    '''
    # XXX need allow c_void_p for nested booleans in lists, sets, etc.?
    isObjCInstanceOf(ns, NSNumber, c_void_p, name='ns')

    return cfNumber2bool(ns, dflt=dflt)
Пример #4
0
def nsData2bytes(ns, dflt=b''):  # XXX an NSData method?
    '''Create Python C{bytes} from C{NSData}.

       @param ns: The C{NSData} (L{ObjCInstance}).
       @keyword dflt: Default for empty C{NSData} (C{bytes}).

       @return: The bytes (C{bytes}) or I{dflt}.
    '''
    isObjCInstanceOf(ns, NSData, name='ns')
    n = ns.length()
    if n:
        buf = (c_byte * n)()
        ns.getBytes_length_(byref(buf), n)
        return b''.join(iterbytes(buf[:n]))
    return dflt
Пример #5
0
    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
Пример #6
0
 def PMview(self, ns_view):
     '''Set this window's print view (C{NSView...}).
     '''
     if ns_view and isObjCInstanceOf(ns_view, NSImageView, NSTableView,
                                     NSTextView, NSView):
         self._PMview = ns_view
     else:
         self._PMview = None
Пример #7
0
def nsString2str(ns, dflt=None):  # XXX an NS*String method
    '''Create a Python C{str} or C{unicode} from an C{NS[Mutable]Str[ing]}.

       @param ns: The C{NS[Mutable]Str[ing]} (L{ObjCInstance}).

       @return: The string (C{str} or C{unicode}) or I{dflt}.
    '''
    # XXX need c_void_p for nested strings in lists, sets, etc.?
    if not isinstanceOf(ns, NSStr, c_void_p):
        isObjCInstanceOf(ns,
                         NSConstantString,
                         NSMutableString,
                         NSString,
                         c_void_p,
                         name='ns')

    return cfString2str(ns, dflt=dflt)
Пример #8
0
 def __init__(self, ns_list=[]):
     '''New L{List} from a C{list}, L{List}, L{Tuple} or C{NSMutableArray}.
     '''
     if isinstance(ns_list, list):
         self.NS = list2NS(ns_list)
     elif isinstance(ns_list, (List, Tuple)):
         self.NS = ns_list.NS.mutableCopy()  # PYCHOK safe
     elif isObjCInstanceOf(ns_list, NSMutableArray, name='ns_list'):
         self.NS = ns_list
Пример #9
0
 def vertical(self):
     '''Get the C{vertical} version of this font (L{Font} or C{None}).
     '''
     if self.isVertical:
         return self
     f = self.NS.vertical()
     if f and isObjCInstanceOf(f, NSFont):
         return Font(f)
     return None
Пример #10
0
def ns2App(ns):
    '''Get the L{App} instance from an C{NSApplication} or an
       C{NSNotification} instance.

       @param ns: The ObjC instance (C{NS...}).

       @return: The app instance (L{App}).

       @raise RuntimeError: L{App} mismatch.

       @raise TypeError: Invalid I{ns} type.
    '''
    if isObjCInstanceOf(ns, NSApplication):
        pass
    elif isObjCInstanceOf(ns, NSConcreteNotification, NSNotification, ns='ns'):
        ns = ns.object()
    if ns == _Globals.App.NS:
        return _Globals.App
    raise RuntimeError('%r vs %r' % (ns, _Globals.App.NS))
Пример #11
0
def nsURL2str(ns):
    '''Create a Python C{str} from C{NSURL} string.

       @param ns: The C{CFURL} (L{ObjCInstance}).

       @return: The URL as string (C{str}).
    '''
    if isObjCInstanceOf(ns, NSURL, name='ns'):
        # <http://NSHipster.com/nsurl>
        return nsString2str(ns.absoluteString())
Пример #12
0
def nsNull2none(ns):
    '''Return Python C{None} for an C{NS/CFNull} or C{nil}.

       @param ns: The C{NS...} (L{ObjCInstance}).

       @return: The singleton (C{None}).

       @raise ValueError: If I{ns} not C{isNone}.
    '''
    if isObjCInstanceOf(ns, NSNull, c_void_p, name='ns') or isNone(ns):
        return None
    return ValueError('%s not %s: %r' % ('ns', 'isNone', ns))
Пример #13
0
 def __init__(self, ns_set=[]):
     '''New L{Set} from a C{frozenset}, C{list}, C{set}, C{tuple},
        L{FrozenSet}, L{Set} or C{NSMutableSet}.
     '''
     if isinstance(ns_set, set):
         self._set = ns_set
     elif isinstance(ns_set, (frozenset, list, tuple)):
         self._set = set(ns_set)
     elif isinstance(ns_set, (Set, FrozenSet)):
         self._set = set(ns_set._set)
     elif isObjCInstanceOf(ns_set, NSMutableSet, name=Set.__name__):
         self._set = nsSet2set(ns_set)
Пример #14
0
    def __init__(self, *ns_dict, **kwds):
        '''New mutable L{Dict}, like C{dict.__init__}.
        '''
        ns_dict, kwds = _dict_kwds(ns_dict, kwds, Dict.__name__)
        if isinstance(ns_dict, dict):
            self.NS = NSMutableDictionary.alloc().init()
            self.update(ns_dict)
        elif isinstance(ns_dict, Dict):
            self.NS = ns_dict.NS
        elif isinstance(ns_dict, FrozenDict):
            self.NS = ns_dict.NS.mutableCopy()  # XXX flat copy only?
        elif isObjCInstanceOf(ns_dict, NSMutableDictionary, name=Dict.__name__):
            self.NS = ns_dict

        if kwds:
            self.update(kwds)
Пример #15
0
def nsArray2listuple(ns, ctype=Array_t):  # XXX an NS*Array method?
    '''Create a Python C{list} or C{tuple} from an C{NS[Mutable]Array}.

       @param ns: The C{NS[Mutable]Array} (L{ObjCInstance}).
       @keyword ctype: The array item type (C{ctypes}).

       @return: The array (C{list} or C{tuple}).
    '''
    # XXX order is critial, NSMutableArray before NSArray
    if isObjCInstanceOf(ns, NSMutableArray, NSArray,
                        name='ns') is NSMutableArray:
        t = list
    else:
        t = tuple
    n = libCF.CFArrayGetCount(ns)
    f = libCF.CFArrayGetValueAtIndex
    return t(_ns2ctype2py(f(ns, i), ctype) for i in range(n))
Пример #16
0
def nsSet2set(ns, ctype=Set_t):  # XXX NS*Set method?
    '''Create a Python C{set} or C{frozenset} from an C{NS[Mutable]Set}.

       @param ns: The C{NS[Mutable]Set} (L{ObjCInstance}).
       @keyword ctype: The set item type (C{ctypes}).

       @return: The set (C{set} or C{frozenset}).
    '''
    if isObjCInstanceOf(ns, NSMutableSet, NSSet, name='ns') is NSSet:
        s = frozenset
    else:
        s = set

    n = libCF.CFSetGetCount(ns)  # == nsSet.count()
    buf = (ctype * n)()
    libCF.CFSetGetValues(ns, byref(buf))
    return s(_ns2ctype2py(buf[i], ctype) for i in range(n))
Пример #17
0
    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__
Пример #18
0
    def show(self, ns_error, timeout=None):  # PYCHOK expected
        '''Show the error.

           @param ns_error: Error information (C{NSError}).
           @keyword timeout: Optional time limit (C{float}).

           @return: TBD.

           @raise TypeError: Invalid I{ns_error}.
        '''
        # <http://Developer.Apple.com/documentation/
        #       appkit/nsalert/1531823-alertwitherror>
        # <http://Developer.Apple.com/documentation/foundation/nserror>
        if isObjCInstanceOf(ns_error, NSError, name='ns_error'):
            ns = NSAlert.alloc().alertWithError_(ns_error)
            r = _runModal(ns, timeout)
            # ns.release()  # XXX may crash
        else:
            r = PanelButton.Error
        return r
Пример #19
0
def nsNumber2num(ns, dflt=missing):  # XXX an NSNumber method?
    '''Create a Python C{Decimal}, C{int} or C{float} from an C{NSNumber}.

       @param ns: The C{NSNumber} (L{ObjCInstance}).
       @keyword dflt: Default for missing, unobtainable value (C{missing}).

       @return: The number (C{Decimal}, C{int} or C{float}).

       @raise TypeError: Unexpected C{NumberType}.

       @raise ValueError: If I{ns} not an C{NSNumber}.
    '''
    # special case for NSDecimal, would become a float
    # since cfType of NSDecimal is kCFNumberDoubleType
    if isinstance(ns, NSDecimal):
        return ns.Decimal
    # XXX need c_void_p for nested numbers in lists, sets, etc.?
    if isObjCInstanceOf(ns, NSNumber, c_void_p, name='ns'):
        return cfNumber2num(ns, dflt=dflt)
    return ValueError('%s not %s: %r' % ('ns', 'NSNumber', ns))
Пример #20
0
    def printView(self, PMview, toPDF='', wait=True):
        '''Print an ObjC C{NSView} or C{PMview}.

           @param PMview: The ObjC view to print (C{NSView} or C{PMview}).
           @keyword toPDF: Save as PDF file name (C{str}).
           @keyword wait: Wait for print completion (C{bool}).

           @return: C{True} if printing succeeded, C{False} if
                    printing failed or C{None} if ignored.

           @raise PrintError: If I{toPDF} file exists.

           @raise TypeError: Invalid I{PMview}.
        '''
        if PMview and isObjCInstanceOf(PMview, NSImageView,
                                               NSTableView,
                                               NSTextView, name='PMview'):
            pi = NSMain.PrintInfo
            if not self.isDefault:
                pi = NSPrintInfo.alloc().initWithDictionary_(pi.dictionary())
                pi.setPrinter_(self.NS)  # NSPrinter

            if toPDF:
                if os.access(toPDF, os.F_OK):
                    raise PrintError('%s exists: %r' % ('PDF file', toPDF))
                # <http://Developer.Apple.com/documentation/appkit/
                #       nsprintoperation/1534130-pdfoperationwithview>
                po = NSPrintOperation.PDFOperationWithView_insideRect_toPath_printInfo_(
                                      PMview, PMview.frame(), NSStr(toPDF), pi)
            else:
                # <http://StackOverflow.com/questions/6452144/
                #       how-to-make-a-print-dialog-with-preview-for-printing-an-image-file>
                po = NSPrintOperation.printOperationWithView_printInfo_(PMview, pi)

            if not wait:
                po.setCanSpawnSeparateThread_(YES)
            return True if po.runOperation() else False
        else:
            return None
Пример #21
0
        def __new__(cls, ns_set=[]):
            '''New L{Set} from a C{frozenset}, C{list}, C{set}, C{tuple},
               L{Set} or C{NSMutableSet}.
            '''
            if isinstance(ns_set, Set):
                py = ns_set
#               ns = ns_set.NS
            elif isinstance(ns_set, set):
                py = ns_set
#               ns = set2NS(py)
            elif isinstance(ns_set, (frozenset, list, tuple)):
                py = set(ns_set)
#               ns = set2NS(py)
            elif isObjCInstanceOf(ns_set, NSMutableSet, name=Set.__name__):
                py = nsSet2set(ns_set)


#               ns = ns_set

            self = super(Set, cls).__new__(cls, py)
            #           self._NS = ns  # _RO
            return self
Пример #22
0
def ns2Type(ns):
    '''Convert an C{NS...} ObjC object to an instance of
       the corresponding Python Type and value.

       @param ns: The C{NS...} (L{ObjCInstance}).

       @return: The value (C{Python Type}).
    '''
    try:
        return ns.Type(ns)
    except AttributeError:
        pass

    # XXX order is critial, NSMutableArray first
    if isObjCInstanceOf(ns, NSMutableArray) is NSMutableArray:
        _Type = _Types.List
    elif isObjCInstanceOf(ns, NSArray) is NSArray:
        _Type = _Types.Tuple

    # XXX order is critial, NSMutableDictionary first
    elif isObjCInstanceOf(ns, NSMutableDictionary) is NSMutableDictionary:
        _Type = _Types.Dict
    elif isObjCInstanceOf(ns, NSDictionary) is NSDictionary:
        _Type = _Types.FrozenDict

    # XXX order is critial, NSMutableSet first
    elif isObjCInstanceOf(ns, NSMutableSet) is NSMutableSet:
        _Type = _Types.Set
    elif isObjCInstanceOf(ns, NSSet) is NSSet:
        _Type = _Types.FrozenSet

    elif isinstanceOf(ns, NSStr):
        _Type = _Types.Str

    else:
        # printf('ns2Type(%r) -> %s', ns.objc_class, type(ns2py(ns)))
        _Type = ns2py

    # save the Python Type or ns2py convertor at the NS/Class
    # to expedite future conversions of such class instances
    ns.objc_class._Type = _Type
    return _Type(ns)
Пример #23
0
    def __init__(self, family_or_font, size=0, traits=0, weight=5):
        '''New L{Font}.

           @param family_or_font: Generic font name (C{str}, L{Str}, L{NSStr})
                                  like "Times" or "Helvetica" or a L{Font},
                                  C{NSFont} or C{NSFontDescriptor} instance.
           @keyword size: Desired point size (C{int}), zero for any.
           @keyword traits: Desired font traits (C{str} or C{FontTrait}C{s mask}).
           @keyword weigth: Desired book weight (C{int}) in range 0..15, where
                            0=light, 5=regular, 9=bold and 15=heavy.

           @raise FontError: No such I{family_or_font}.

           @raise FontTraitError: Mutually exclusive I{traits}.

           @raise TypeError: Invalid I{family_or_font}.

           @raise ValueError: Invalid I{weight}.

           @note: The new L{Font} may not exhibit the desired I{traits}
                  and I{weight}.  The I{weight} is ignored if I{traits}
                  include C{FontTrait.Bold}, both I{traits} and I{weight}
                  are ignored if I{family_or_font} is C{NSFontDescriptor}.

           @see: Function L{fontsof} to obtain all available fonts of
                 a particular font family.
        '''
        if isinstance(family_or_font, Str):
            ns, py = family_or_font.NS, str(family_or_font)
        elif isinstance(family_or_font, _ByteStrs):
            ns, py = release(NSStr(family_or_font)), bytes2str(family_or_font)
        elif isinstance(family_or_font, NSStr):
            ns, py = family_or_font, nsString2str(family_or_font)
#       elif isObjCInstanceOf(family_or_font, NSFontDescriptor):
            # <http://Developer.Apple.com/documentation/appkit/nsfont/1525386-init>
            # ignore traits and weight
#           ns, py = NSFont.alloc().init_(family_or_font, size), None
        elif isObjCInstanceOf(family_or_font, NSFont, name='family_or_font'):
            ns, py = family_or_font, None
            if size == 0:
                size = ns.pointSize()
            if traits == 0:
                traits = NSMain.FontManager.traitsOfFont_(ns)
            if not (size == ns.pointSize() and
                    traits == NSMain.FontManager.traitsOfFont_(ns)):
                ns = ns.familyName()
                py = nsString2str(ns)

        if py is not None:
            # <http://Developer.Apple.com/documentation/appkit/
            #       nsfontmanager/1462332-fontwithfamily>
            self._traits = _traitsin(traits)
            self._weight = _weightin(weight)
            ns = NSMain.FontManager.fontWithFamily_traits_weight_size_(
                                 ns, self._traits, self._weight, size)
            if isNone(ns):
                self._family = py
                self._size   = flint(size)
                raise FontError('no such %s: %s' % ('font', self._argstr()))

        self._NS = ns  # _RO
        # <http://Developer.Apple.com/library/content/documentation/
        #  TextFonts/Conceptual/CocoaTextArchitecture/FontHandling/FontHandling.html>
        self._family = nsString2str(ns.familyName())
        self._height = flint(NSMain.LayoutManager.defaultLineHeightForFont_(ns) + 1)
        self._name   = nsString2str(ns.fontName())
        self._size   = flint(ns.pointSize())
        # traits not always reflect actual traits
        self._traits = NSMain.FontManager.traitsOfFont_(ns) or 0
        # update with the family traits, if any
        self._traits |= _traitsin(self._family, raiser=False)
        if ns.isFixedPitch() and not self.isMonoSpace:
            self._traits |= FontTrait.MonoSpace
        self._weight = NSMain.FontManager.weightOfFont_(ns)