Beispiel #1
0
 def __setitem__(self, index, value):
     if isinstance(index, slice):
         indices = range(*index.indices(len(self)))
         for i, val in zip_longest(indices, value, fillvalue=missing):
             if missing in (i, val):  # XXX only if val is missing?
                 raise ValueError('%s len() mismatch %r vs %r' %
                                  (self, index, value))
             self.NS.replaceObjectAtIndex_withObject_(i, py2NS(val))
     else:
         self.NS.replaceObjectAtIndex_withObject_(_at(self, index),
                                                  py2NS(value))
Beispiel #2
0
    def index(self, value, identical=False):
        '''Find an item, like C{tuple./list.index}.

           @keyword idential: Use ObjC C{idential} as comparison (bool).
        '''
        if identical:
            i = self.NS.indexOfObjectIdenticalTo_(py2NS(value))
        else:
            i = self.NS.indexOfObject_(py2NS(value))
        if i == NSNotFound:
            raise ValueError('%s no such value: %r' % (self, value))
        return i
Beispiel #3
0
    def count(self, value, identical=False):
        '''Count the number of occurances of an item, like C{tuple./list.count}.

           @keyword idential: Use ObjC C{idential} as comparison (bool).
        '''
        v = py2NS(value)
        n = len(self)
        c = i = 0
        while i < n:
            if identical:
                i = self.NS.indexOfObjectIdenticalTo_inRange_(
                    v, NSRange_t(i, n - i))
            else:
                i = self.NS.indexOfObject_inRange_(v, NSRange_t(i, n - i))
            if i == NSNotFound:
                break
            i += 1
            c += 1
        return c
Beispiel #4
0
    def __init__(self, *ns_dict, **kwds):
        '''New immutable L{FrozenDict}, like C{dict.__init__}.
        '''
        ns_dict, kwds = _dict_kwds(ns_dict, kwds, FrozenDict.__name__)
        if isinstance(ns_dict, dict):
            if kwds:
                ns_dict = ns_dict.copy()
                ns_dict.update(kwds)
                kwds = {}
            self.NS = self._NS_Dictionary(py2NS(ns_dict))
        elif isinstance(ns_dict, FrozenDict):
            self.NS = ns_dict.NS
        elif isinstance(ns_dict, Dict):
            self.NS = ns_dict.NS._NS_copy(False)
        elif isImmutable(ns_dict, NSMutableDictionary,
                                  NSDictionary, name=FrozenDict.__name__):
            self.NS = ns_dict

        if kwds:
            ns = self._NS_copy(True)
            ns.update(kwds)
            self.NS = ns._NS_copy(False)
Beispiel #5
0
 def insert(self, index, value):
     '''Insert an item into this list, like C{list.insert}.
     '''
     self.NS.insertObject_atIndex_(py2NS(value), _at(self, index))
Beispiel #6
0
 def extend(self, values):
     '''Add one or more items to this list, like C{list.extend}.
     '''
     for v in values:
         self.NS.addObject_(py2NS(v))
Beispiel #7
0
 def append(self, value):
     '''Add an item to this list, like C{list.append}.
     '''
     self.NS.addObject_(py2NS(value))
Beispiel #8
0
 def __contains__(self, value):
     return self.NS.containsObject_(py2NS(value))
Beispiel #9
0
    def save_as(
            self,
            name='',
            filetype='',  # PYCHOK expected
            dir='',
            hidden=False,
            hidexts=False,
            label='',
            packages=False,
            prompt='',
            tags=(),
            dflt=None):
        '''Specify a file name in the panel.

           @keyword name: A suggested file name (C{str}), default "Untitled".
           @keyword filetype: The file type (C{str}).
           @keyword dir: The directory (C{str}).
           @keyword hidden: Show hidden files (C{bool}).
           @keyword hidexts: Hide file extensions (C{bool}).
           @keyword label: The name label (C{str}), default "Save As:".
           @keyword packages: Treat file packages as directories (C{bool}).
           @keyword prompt: The button label (C{str}), default "Save".
           @keyword tags: Suggested tag names (C{tuple} of C{str}-s).
           @keyword dflt: Return value, cancelled (C{None}).

           @return: The specified file name path (C{str}) or I{dflt}.
        '''
        ns = NSSavePanel.savePanel()
        #       ns.setTitleHidden_(bool(False))  # "does nothing now"

        if name:
            ns.setNameFieldStringValue_(release(NSStr(name)))

        if dir:
            if dir.lower().startswith('file:///'):
                ns.setDirectoryURL_(release(NSStr(dir)))
            else:
                ns.setDirectory_(release(NSStr(dir)))

        if filetype:
            ns.setRequiredFileType_(release(NSStr(filetype.lstrip('.'))))
            hidexts = False

        ns.setShowsHiddenFiles_(YES if hidden else NO)
        # ns.setCanSelectHiddenExtension_(bool(hidden))
        ns.setExtensionHidden_(YES if hidexts else NO)

        if label:
            ns.setNameFieldLabel_(release(NSStr(label)))

        ns.setTreatsFilePackagesAsDirectories_(YES if packages else NO)

        if prompt:
            ns.setPrompt_(release(NSStr(prompt)))

        if tags:
            ns.setTagNames_(py2NS(tags))
            ns.setShowsTagField_(True)
        else:
            ns.setShowsTagField_(False)

        while True:
            r = _runModal(ns)  # == runModalForDirectory_file_(None, None)
            if r == NSOKButton:
                r = nsString2str(ns.filename())  # == ns.URL().path()
                break
            elif r == NSCancelButton:
                r = dflt
                break
        # ns.release()  # XXX may crash on Cancel
        return r
Beispiel #10
0
    def pick(self,
             filetypes,
             aliases=False,
             dirs=False,
             files=True,
             hidden=False,
             hidexts=False,
             multiple=False,
             packages=False,
             prompt='',
             otherOK=False,
             dflt=None):
        '''Select a file from the panel.

           @param filetypes: The selectable file types (tuple of str-s).
           @keyword aliases: Allow selection of aliases (C{bool}).
           @keyword dirs: Allow selection of directories (C{bool}).
           @keyword hidden: Allow selection of hidden files (C{bool}).
           @keyword hidexts: Hide file extensions (C{bool}).
           @keyword multiple: Allow selection of multiple files (C{bool}).
           @keyword packages: Treat file packages as directories (C{bool}).
           @keyword prompt: The button label (C{str}), default "Open".
           @keyword otherOK: Allow selection of other file types (C{bool}).
           @keyword dflt: Return value, if cancelled, nothing selected (C{None}).

           @return: The selected file name path (C{str}) or I{dflt}.
        '''
        if multiple:  # setAllowsMultipleSelection_
            raise NotImplementedError('multiple %s' % (multiple, ))

        ns = NSOpenPanel.openPanel()
        #       ns.setTitleHidden_(NO)  # "does nothing now"

        ns.setResolvesAliases_(YES if aliases else NO)
        ns.setCanChooseDirectories_(YES if dirs else NO)
        ns.setCanChooseFiles_(YES if files else NO)
        ns.setShowsHiddenFiles_(YES if hidden else NO)
        # ns.setCanSelectHiddenExtension_(YES if hidden else NO)
        ns.setExtensionHidden_(YES if hidexts else NO)

        # ns.setRequiredFileType_(NSStr)
        if filetypes:  # an NSArray of file extension NSStr[ing]s without the '.'
            ns.setAllowedFileTypes_(py2NS(t.lstrip('.') for t in filetypes))

        ns.setAllowsOtherFileTypes_(YES if otherOK else NO)
        ns.setTreatsFilePackagesAsDirectories_(YES if packages else NO)

        if prompt:
            ns.setPrompt_(release(NSStr(prompt)))

        while True:
            # ns.orderFrontRegardless()  # only flashes
            # <http://Developer.Apple.com/documentation/
            #       appkit/nssavepanel/1525357-runmodal>
            if ns.runModal() == NSCancelButton:  # runModalForTypes_
                path = dflt  # nothing selected
                break


#           paths = ns.filenames()  # returns an NSArray
#           urls = ns.URLs()  # returns an NSArray
            path = nsString2str(ns.filename())  # == ns.URL().path()
            # mimick NSOpenPanel.setAllowedFileTypes_
            if path.lower().endswith(filetypes):
                break
        # ns.release()  # XXX crashes Cancel pick
        return path