def events(self): store = CalCalendarStore.defaultCalendarStore() # Pull all events starting now from all calendars in the CalendarStore allEventsPredicate = ( CalCalendarStore.eventPredicateWithStartDate_endDate_calendars_( NSDate.date(), NSDate.distantFuture(), store.calendars())) return store.eventsWithPredicate_(allEventsPredicate)
def showEventCreationDialog_(self, sender): # Set default values for the title and start/end date # Cocoa bindings will clear out the related fields in the sheet self._.calItemTitle = None self._.calItemStartDate = NSDate.date() self._.calItemEndDate = NSDate.dateWithTimeIntervalSinceNow_(3600) NSApp.beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_( self.eventCreationDialog, self.mainWindow, self, 'didEndSheet:returnCode:contextInfo:', None)
def send_notification(title, subtitle, info_text, delay=0, sound=False, userInfo={}): notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) notification.setUserInfo_(userInfo) if sound: notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def _nestedRunLoopReaderUntilEOLchars_(self, eolchars): """ This makes the baby jesus cry. I want co-routines. """ app = NSApplication.sharedApplication() window = self.textView.window() self.setCharacterIndexForInput_(self.lengthOfTextView()) # change the color.. eh self.textView.setTypingAttributes_({ NSFontAttributeName: self.font(), NSForegroundColorAttributeName: self.codeColor(), }) while True: event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.distantFuture(), NSDefaultRunLoopMode, True) if (event.type() == NSKeyDown) and (event.window() == window): eol = event.characters() if eol in eolchars: break app.sendEvent_(event) cl = self.currentLine() if eol == "\r": self.writeCode_("\n") return cl + eol
def _writeString_forOutput_(self, s, name): self.textView.textStorage().appendAttributedString_(getattr(self, name+'String_')(s)) window = self.textView.window() app = NSApplication.sharedApplication() st = time.time() now = time.time if self._autoscroll: self.textView.scrollRangeToVisible_((self.lengthOfTextView(), 0)) while app.isRunning() and now() - st < 0.01: event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSUIntegerMax, NSDate.dateWithTimeIntervalSinceNow_(0.01), NSDefaultRunLoopMode, True) if event is None: continue if (event.type() == NSKeyDown) and (event.window() == window): chr = event.charactersIgnoringModifiers() if chr == 'c' and (event.modifierFlags() & NSControlKeyMask): raise KeyboardInterrupt app.sendEvent_(event)
def _nestedRunLoopReaderUntilEOLchars_(self, eolchars): """ This makes the baby jesus cry. I want co-routines. """ app = NSApplication.sharedApplication() window = self.textView.window() self.setCharacterIndexForInput_(self.lengthOfTextView()) # change the color.. eh self.textView.setTypingAttributes_({ NSFontAttributeName:self.font(), NSForegroundColorAttributeName:self.codeColor(), }) while True: event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSUIntegerMax, NSDate.distantFuture(), NSDefaultRunLoopMode, True) if (event.type() == NSKeyDown) and (event.window() == window): eol = event.characters() if eol in eolchars: break app.sendEvent_(event) cl = self.currentLine() if eol == '\r': self.writeCode_('\n') return cl+eol
def create_main_surface(): pygame.init() surface = pygame.display.set_mode((320, 240)) SDL_QuartzWindow = objc.lookUpClass('SDL_QuartzWindow') class SDL_QuartzWindow(objc.Category(SDL_QuartzWindow)): def canBecomeKeyWindow(self): return True def canBecomeMainWindow(self): return True def acceptsFirstResponder(self): return True def becomeFirstResponder(self): return True def resignFirstResponder(self): return True global window_controller window_controller = WindowController() # run the run loop just once to finish setting up the window NSRunLoop.mainRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.date()) return surface
def _writeString_forOutput_(self, s, name): self.textView.textStorage().appendAttributedString_( getattr(self, name + "String_")(s)) window = self.textView.window() app = NSApplication.sharedApplication() st = time.time() now = time.time if self._autoscroll: self.textView.scrollRangeToVisible_((self.lengthOfTextView(), 0)) while app.isRunning() and now() - st < 0.01: event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.01), NSDefaultRunLoopMode, True, ) if event is None: continue if (event.type() == NSKeyDown) and (event.window() == window): chr = event.charactersIgnoringModifiers() if chr == "c" and (event.modifierFlags() & NSControlKeyMask): raise KeyboardInterrupt app.sendEvent_(event)
def create_main_surface(): pygame.init() surface = pygame.display.set_mode((320, 240)) try: SDL_QuartzWindow = objc.lookUpClass('SDL_QuartzWindow') except objc.nosuchclass_error: # SDL2 doesn't have this class or need the runtime patch pass else: class SDL_QuartzWindow(objc.Category(SDL_QuartzWindow)): def canBecomeKeyWindow(self): return True def canBecomeMainWindow(self): return True def acceptsFirstResponder(self): return True def becomeFirstResponder(self): return True def resignFirstResponder(self): return True global window_controller window_controller = WindowController() # run the run loop just once to finish setting up the window NSRunLoop.mainRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.date()) return surface
def createKnownNetwork(networkDict): print 'Creating KnownNetworks entry' # There were some MacBook Airs that shipped with 10.5 path = '/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist' # Set to root as the owner for good measure uid = 0 gid = 80 if os.path.exists(path): plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path) else: plist = NSMutableDictionary.alloc().init() plist['KnownNetworks'] = {} guid = networkDict['guid'] plist['KnownNetworks'][guid] = {} plist['KnownNetworks'][guid]['SSID_STR'] = networkDict['ssid'] plist['KnownNetworks'][guid]['Remembered channels'] = [networkDict['chan'],] plist['KnownNetworks'][guid]['SecurityType'] = networkDict['sect'] # If we are adding a non WPA2 Enterprise network add the keychain item if networkDict['type'] == 'WPA2': plist['KnownNetworks'][guid]['Unique Password ID'] = networkDict['keyc'] plist['KnownNetworks'][guid]['_timeStamp'] = NSDate.date() exportFile = path plist.writeToFile_atomically_(exportFile,True) try: os.chown(path,uid,gid) except: print 'Path not found %s' % path
def showTaskCreationDialog_(self, sender): # Set default values for the title, start date and priority # Cocoa bindings will clear out the related fields in the sheet self._.calItemTitle = None self._.calItemStartDate = NSDate.date() NSApp.beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_( self.taskCreationDialog, self.mainWindow, self, 'didEndSheet:returnCode:contextInfo:', None)
def fetch_events(request_from_server=False): global memory_cache logger.info('fetch_events: called') if memory_cache: logger.info('fetch_events: checking memory cache') else: logger.info('fetch_events: checking disk cache') memory_cache = cache.fetch(config.CALENDAR_CACHE_PATH) content = cache.content(memory_cache, config.CALENDAR_CACHE_LIFETIME, request_from_server) if content: return content store = CalCalendarStore.defaultCalendarStore() cals = [] for cal in store.calendars(): if cal.title() in config.CALENDAR_CALENDARS: cals.append(cal) logger.info(cal.title()) cst = tz.gettz('America/Chicago') today = datetime.now().date() start_dt = datetime(today.year, today.month, today.day, tzinfo=cst) end_dt = start_dt + timedelta(180) start_int = int(start_dt.strftime("%s")) end_int = int(end_dt.strftime("%s")) start = NSDate.dateWithTimeIntervalSince1970_(start_int) end = NSDate.dateWithTimeIntervalSince1970_(end_int) formatted_results = {} for cal in cals: events = [] pred = CalCalendarStore.eventPredicateWithStartDate_endDate_calendars_( start, end, [cal]) for event in store.eventsWithPredicate_(pred): s = event._.startDate.timeIntervalSince1970() e = event._.endDate.timeIntervalSince1970() events.append({'name': event._.title, 'start': s, 'end': e}) formatted_results[cal.title()] = events memory_cache = cache.save(formatted_results, config.CALENDAR_CACHE_PATH) return formatted_results
## # Copyright (c) 2010-2017 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## from __future__ import print_function import eventkitframework as EventKit from Cocoa import NSDate store = EventKit.EKEventStore.alloc().init() calendars = store.calendarsForEntityType_(0) print(calendars) raise SystemExit predicate = store.predicateForEventsWithStartDate_endDate_calendars_( NSDate.date(), NSDate.distantFuture(), [calendars[2]]) print(store.eventsMatchingPredicate_(predicate))
def main(): pl = OrderedDict() # Note: pl is an OrderedDict to control the order # of keys, and hence have some control on the structure # of the output file. # New keys should be added in alphabetical order. seconds = datetime.datetime(2004, 10, 26, 10, 33, 33, tzinfo=datetime.timezone(datetime.timedelta(0))).timestamp() pl[nsstr('aBigInt')] = 2 ** 63 - 44 pl[nsstr('aDate')] = NSDate.dateWithTimeIntervalSince1970_(seconds) pl[nsstr('aDict')] = d = OrderedDict() d[nsstr('aFalseValue')] = False d[nsstr('aTrueValue')] = True d[nsstr('aUnicodeValue')] = "M\xe4ssig, Ma\xdf" d[nsstr('anotherString')] = "<hello & 'hi' there!>" d[nsstr('deeperDict')] = dd = OrderedDict() dd[nsstr('a')] = 17 dd[nsstr('b')] = 32.5 dd[nsstr('c')] = a = NSMutableArray.alloc().init() a.append(1) a.append(2) a.append(nsstr('text')) pl[nsstr('aFloat')] = 0.5 pl[nsstr('aList')] = a = NSMutableArray.alloc().init() a.append(nsstr('A')) a.append(nsstr('B')) a.append(12) a.append(32.5) aa = NSMutableArray.alloc().init() a.append(aa) aa.append(1) aa.append(2) aa.append(3) pl[nsstr('aNegativeBigInt')] = -80000000000 pl[nsstr('aNegativeInt')] = -5 pl[nsstr('aString')] = nsstr('Doodah') pl[nsstr('anEmptyDict')] = NSMutableDictionary.alloc().init() pl[nsstr('anEmptyList')] = NSMutableArray.alloc().init() pl[nsstr('anInt')] = 728 pl[nsstr('nestedData')] = a = NSMutableArray.alloc().init() a.append(b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''') pl[nsstr('someData')] = b'<binary gunk>' pl[nsstr('someMoreData')] = b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''' pl[nsstr('\xc5benraa')] = nsstr("That was a unicode key.") print("TESTDATA={") for fmt_name, fmt_key in FORMATS: data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_( pl, fmt_key, 0, None) if data is None: print("Cannot serialize", fmt_name, error) else: print(" %s: binascii.a2b_base64(b'''\n %s'''),"%(fmt_name, _encode_base64(bytes(data)).decode('ascii')[:-1])) print("}") print()
def main(): pl = OrderedDict() # Note: pl is an OrderedDict to control the order # of keys, and hence have some control on the structure # of the output file. # New keys should be added in alphabetical order. seconds = datetime.datetime(2004, 10, 26, 10, 33, 33, tzinfo=datetime.timezone(datetime.timedelta(0))).timestamp() pl[nsstr('aBigInt')] = 2 ** 63 - 44 pl[nsstr('aBigInt2')] = NSNumber.numberWithUnsignedLongLong_(2 ** 63 + 44) pl[nsstr('aDate')] = NSDate.dateWithTimeIntervalSince1970_(seconds) pl[nsstr('aDict')] = d = OrderedDict() d[nsstr('aFalseValue')] = False d[nsstr('aTrueValue')] = True d[nsstr('aUnicodeValue')] = "M\xe4ssig, Ma\xdf" d[nsstr('anotherString')] = "<hello & 'hi' there!>" d[nsstr('deeperDict')] = dd = OrderedDict() dd[nsstr('a')] = 17 dd[nsstr('b')] = 32.5 dd[nsstr('c')] = a = NSMutableArray.alloc().init() a.append(1) a.append(2) a.append(nsstr('text')) pl[nsstr('aFloat')] = 0.5 pl[nsstr('aList')] = a = NSMutableArray.alloc().init() a.append(nsstr('A')) a.append(nsstr('B')) a.append(12) a.append(32.5) aa = NSMutableArray.alloc().init() a.append(aa) aa.append(1) aa.append(2) aa.append(3) pl[nsstr('aNegativeBigInt')] = -80000000000 pl[nsstr('aNegativeInt')] = -5 pl[nsstr('aString')] = nsstr('Doodah') pl[nsstr('anEmptyDict')] = NSMutableDictionary.alloc().init() pl[nsstr('anEmptyList')] = NSMutableArray.alloc().init() pl[nsstr('anInt')] = 728 pl[nsstr('nestedData')] = a = NSMutableArray.alloc().init() a.append(b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''') pl[nsstr('someData')] = b'<binary gunk>' pl[nsstr('someMoreData')] = b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''' pl[nsstr('\xc5benraa')] = nsstr("That was a unicode key.") print("TESTDATA={") for fmt_name, fmt_key in FORMATS: data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_( pl, fmt_key, 0, None) if data is None: print("Cannot serialize", fmt_name, error) else: print(" %s: binascii.a2b_base64(b'''\n %s'''),"%(fmt_name, _encode_base64(bytes(data)).decode('ascii')[:-1])) print("}") print()
f = open('vendor') try: url = vendors[f.readline().rstrip()] except Exception, e: url = vendors['google'] f.close() dests = filter(lambda x:x!=u"", query.split(';',1)) if len(dests)<2: clm = LocationManager.alloc().init_with_thread(NSThread.currentThread()) loop = NSRunLoop.currentRunLoop() loop.runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.distantFuture()) loc = clm.goodLocation if loc != None: latitude = unicode(loc.coordinate().latitude) longitude = unicode(loc.coordinate().longitude) clm.dealloc() if query.index(';') < 2: url = url.replace(u"{source}",latitude + u"," + longitude) url = url.replace(u"{destination}", dests[0]) else: url = url.replace(u"{destination}",latitude + u"," + longitude) url = url.replace(u"{source}", dests[0]) else: url = url.replace(u"{source}", dests[0])
def main(): pl = OrderedDict() seconds = datetime.datetime(2004, 10, 26, 10, 33, 33, tzinfo=datetime.timezone(datetime.timedelta(0))).timestamp() pl[nsstr('aDate')] = NSDate.dateWithTimeIntervalSince1970_(seconds) pl[nsstr('aDict')] = d = OrderedDict() d[nsstr('aFalseValue')] = False d[nsstr('aTrueValue')] = True d[nsstr('aUnicodeValue')] = "M\xe4ssig, Ma\xdf" d[nsstr('anotherString')] = "<hello & 'hi' there!>" d[nsstr('deeperDict')] = dd = OrderedDict() dd[nsstr('a')] = 17 dd[nsstr('b')] = 32.5 dd[nsstr('c')] = a = NSMutableArray.alloc().init() a.append(1) a.append(2) a.append(nsstr('text')) pl[nsstr('aFloat')] = 0.5 pl[nsstr('aList')] = a = NSMutableArray.alloc().init() a.append(nsstr('A')) a.append(nsstr('B')) a.append(12) a.append(32.5) aa = NSMutableArray.alloc().init() a.append(aa) aa.append(1) aa.append(2) aa.append(3) pl[nsstr('aString')] = nsstr('Doodah') pl[nsstr('anEmptyDict')] = NSMutableDictionary.alloc().init() pl[nsstr('anEmptyList')] = NSMutableArray.alloc().init() pl[nsstr('anInt')] = 728 pl[nsstr('nestedData')] = a = NSMutableArray.alloc().init() a.append(b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''') pl[nsstr('someData')] = b'<binary gunk>' pl[nsstr('someMoreData')] = b'''<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03<lots of binary gunk>\x00\x01\x02\x03''' pl[nsstr('\xc5benraa')] = nsstr("That was a unicode key.") print("TESTDATA={") for fmt_name, fmt_key in FORMATS: data, error = NSPropertyListSerialization.dataWithPropertyList_format_options_error_( pl, fmt_key, 0, None) if data is None: print("Cannot serialize", fmt_name, error) else: print(" %s: binascii.a2b_base64(b'''\n %s'''),"%(fmt_name, _encode_base64(bytes(data)).decode('ascii')[:-1])) print("}") print()
## # Copyright (c) 2010-2015 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## from __future__ import print_function import eventkitframework as EventKit from Cocoa import NSDate store = EventKit.EKEventStore.alloc().init() calendars = store.calendarsForEntityType_(0) print(calendars) raise SystemExit predicate = store.predicateForEventsWithStartDate_endDate_calendars_( NSDate.date(), NSDate.distantFuture(), [calendars[2]]) print(store.eventsMatchingPredicate_(predicate))