Example #1
0
    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)
Example #2
0
 def app(self, app):
     '''Set the app.
     '''
     if app not in (None, ):
         from pycocoa.apps import App
         isinstanceOf(app, App, name='app')
     self._app = app
Example #3
0
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 _NN_
Example #4
0
 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
Example #5
0
 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 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
Example #7
0
    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
Example #8
0
    def init(self, cols, rows, id2i):
        '''Initialize the allocated C{NSTableViewDelegate}.

           @note: I{MUST} be called as C{.alloc().init(...)}.
        '''
        isinstanceOf(cols, list, tuple, name='cols')
        isinstanceOf(rows, list, tuple, name='rows')
        #       self = ObjCInstance(send_message('NSObject', 'alloc'))
        self = ObjCInstance(send_super_init(self))
        self.cols = cols  # column headers/titles
        self.rows = rows
        self.id2i = id2i  # map col.identifier to col number
        # self.id_s = NSStr(str(id(self)))
        return self
Example #9
0
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
Example #10
0
    def __init__(self, screen_frame=None, fraction=None, cascade=10):
        '''New, partial screen L{Frame}.

           @keyword screen: The screen to place the window on (C{int}) or
                            C{None} for the current one.  Use C{screen=0}
                            for the BuiltIn screen or C{screen=1} for the
                            first External monitor, etc.
           @keyword fraction: Size of the screen (C{float}).
           @keyword cascade: Shift from lower left corner (C{float} or C{int}).

           @raise TypeError: Invalid I{screen_frame}.

           @raise ValueError: Invalid I{fraction} value.
        '''
        if screen_frame is None:
            f = Screens.Main.frame
        elif isinstance(screen_frame, _Ints):
            f = Screens(screen_frame).frame
        elif isinstance(screen_frame, Screen):
            f = screen_frame.frame
        elif isinstanceOf(screen_frame, NSRect_t, Rect, name='screen_frame'):
            f = screen_frame

        if isinstance(fraction, (float, int)):
            if 0.1 < fraction < 1.0:
                z = f.size
                # use the lower left side of the screen
                w = int(z.width * fraction + 0.5)
                h = int(z.height * w / z.width)
                # avoid cascading window off-screen
                c = min(max(0, cascade), min(z.width, z.height))
                f = f.origin.x + c, f.origin.y + c, w, h
            elif fraction < 0 or fraction > 1:
                raise ValueError('invalid %s: %.2f' % ('fraction', fraction))
        self.rect = f
Example #11
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
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
Example #13
0
 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
Example #14
0
    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)
Example #15
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: <https://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
Example #17
0
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
Example #18
0
 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
Example #19
0
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))
Example #20
0
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)
Example #21
0
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))
Example #22
0
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)
Example #23
0
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)
Example #24
0
    def __init__(self, title='', table=None, frame=None):
        '''New L{TableWindow}.

           @keyword title: Window name or title (C{str}).
           @keyword table: Table data (L{Table}).
           @keyword frame: Optional window frame (L{Rect}).
        '''
        isinstanceOf(table, Table, name='table')
        self._table = table

        tbl = getattr(table, 'NS', None)
        isObjCInstanceOf(tbl, NSTableView, name='table')

        # <https://Developer.Apple.com/documentation/appkit/nswindow>
        n = tbl.dataSource().numberOfRowsInTableView_(tbl)
        # approximate height of the table content, also to
        # .setContentMaxSize_ of the window in self.limit
        h = tbl.rowHeight() * max(1, n * 1.1)
        # adjust frame to include all (or most) table rows
        f = tbl.frame() if frame is None else frame.NS
        if f.size.height < h:
            h = min(Screen().height, h)
            f.size = NSSize_t(f.size.width, h)
            tbl.setFrameSize_(f.size)

        super(TableWindow, self).__init__(title=title,
                                          frame=f,
                                          excl=WindowStyle.Miniaturizable,
                                          auto=True)  # XXX False?
        self.NSview = sv = NSScrollView.alloc().initWithFrame_(f)
        self.PMview = tbl  # printable view, scrollview isn't

        sv.setDocumentView_(tbl)
        sv.setHasVerticalScroller_(YES)

        self.cascade()
        self.limit(height=h)
        self.front(False)

        _Globals.Tables.append(self)
Example #25
0
 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 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)
Example #27
0
    def __new__(cls, ns_str=_NN_):
        '''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
Example #28
0
 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):
         self.NS = size
     else:  # NSConcreteValue, like screen.resolutions
         self.NS = nsValue2py(size)  # NSSize_t
Example #29
0
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
Example #30
0
    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