def asWebArchive(self): """ Convert the MHT archive to a webarchive. """ rootType, rootText = self.parts[self.root] pageResource = WebResource.alloc().initWithData_URL_MIMEType_textEncodingName_frameName_( NSData.dataWithBytes_length_(rootText.replace(b"\\", b"/"), len(rootText)), NSURL.URLWithString_(self.fixupURL(self.root)), NSString.stringWithString_(rootType), None, None) resources = [] for url in self.parts: if url == self.root: continue tp, data = self.parts[url] resources.append(WebResource.alloc().initWithData_URL_MIMEType_textEncodingName_frameName_( NSData.dataWithBytes_length_(data, len(data)), NSURL.URLWithString_(self.fixupURL(url)), NSString.stringWithString_(tp), None, None)) return WebArchive.alloc().initWithMainResource_subresources_subframeArchives_( pageResource, resources, None)
def asWebArchive(self): """ Convert the MHT archive to a webarchive. """ rootType, rootText = self.parts[self.root] pageResource = WebResource.alloc( ).initWithData_URL_MIMEType_textEncodingName_frameName_( NSData.dataWithBytes_length_(rootText.replace(b"\\", b"/"), len(rootText)), NSURL.URLWithString_(self.fixupURL(self.root)), NSString.stringWithString_(rootType), None, None, ) resources = [] for url in self.parts: if url == self.root: continue tp, data = self.parts[url] resources.append(WebResource.alloc( ).initWithData_URL_MIMEType_textEncodingName_frameName_( NSData.dataWithBytes_length_(data, len(data)), NSURL.URLWithString_(self.fixupURL(url)), NSString.stringWithString_(tp), None, None, )) return WebArchive.alloc( ).initWithMainResource_subresources_subframeArchives_( pageResource, resources, None)
def get_attributedBody(text): string = NSMutableAttributedString.alloc() string = string.initWithString_attributes_( text, {u'__kIMMessagePartAttributeName': NSNumber.numberWithInt_(0)}) return unicode(NSString.alloc().initWithData_encoding_( NSArchiver.archivedDataWithRootObject_(string), 1))
def guesses(checker, string, _range): from Cocoa import NSString, NSRange _string = NSString.stringWithString_(string) _words = checker.guessesForWordRange_inString_language_inSpellDocumentWithTag_(_range, _string, None, 0) n = len(_words) words = u', '.join(_words) # logger.info('Guesses: ' + words) return n, words
def guesses(checker, string, _range): from Cocoa import NSString, NSRange _string = NSString.stringWithString_(string) _words = checker.guessesForWordRange_inString_language_inSpellDocumentWithTag_(_range, _string, None, 0) n = len(_words) words = u', '.join(_words) logger.info('Guesses: %s', words) return n, words
def check_spelling(checker, string, start=0): from Cocoa import NSString _string = NSString.stringWithString_(string) _range, _count = checker.checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount_(_string, start, None, False, 0, None) # logger.debug('Check spelling: %s range: %s count: %d' % (string.encode('utf-8'), _range, _count)) if _range.length == 0: return True, _count, None, None else: word = string[_range.location:_range.location+_range.length] # logger.info('Misspelled word: ' + word.encode('utf-8')) return False, _count, _range, word
def main(*args): if not args: args = ("dict",) setup() try: for arg in args: url = NSURL.URLWithString_(u"pydoc:///%s" % (arg,)) print(NSString.stringWithContentsOfURL_(url)) finally: teardown()
def check_spelling(checker, string, start=0): from Cocoa import NSString _string = NSString.stringWithString_(string) _range, _count = checker.checkSpellingOfString_startingAt_language_wrap_inSpellDocumentWithTag_wordCount_(_string, start, None, False, 0, None) logger.debug('Check spelling: %s range: %s count: %d', string.encode('utf-8'), _range, _count) if _range.length == 0: return True, _count, None, None else: word = string[_range.location:_range.location+_range.length] logger.info('Misspelled word: %s', word.encode('utf-8')) return False, _count, _range, word
def main(*args): if not args: args = ("dict", ) setup() try: for arg in args: url = NSURL.URLWithString_("pydoc:///%s" % (arg, )) print(NSString.stringWithContentsOfURL_(url)) finally: teardown()
def get_path(alias_path="~/bin/"): # first resolve tildes path = NSString.stringByExpandingTildeInPath(alias_path) url = NSURL.URLWithString_(path) #data, err = NSURL.bookmarkDataWithContentsOfURL_error_(url, None) #url = NSURL.alloc().initByResolvingBookmarkData_options_relativeToUrl_bookmarkDataIsStale_error(path) print url #data =NSURL.URLByResolvingBookmakrData_options_relativeToUrl_bookmarkDataIsStale_Error( # path, None, None, None, None) return path
def main(): #Command line interface for easier testing. argv = sys.argv[1:] if not argv: print 'Usage: Send_To_RTM <query>' return 1 argv = " ".join(argv) #Running this plugin via terminal automatically enables Debug mode print argv global debug debug = True global xml_resp xml_resp = '~/Desktop/resp.xml' xml_resp = NSString.stringByExpandingTildeInPath(xml_resp) Task_Action.Perform(Task_Action(), argv)
def nsstr(value): return NSString.alloc().initWithString_(value)
def remove_word(checker, word): from Cocoa import NSString _word = NSString.stringWithString_(word) if checker.hasLearnedWord_(_word): logger.info('Unlearning word: %s', word) checker.unlearnWord_(_word)
def ignore_word(checker, word): from Cocoa import NSString _word = NSString.stringWithString_(word) logger.info('Ignoring word: %s', word) checker.ignoreWord_inSpellDocumentWithTag_(_word, 0)
def add_word(checker, word): from Cocoa import NSString _word = NSString.stringWithString_(word) if not checker.hasLearnedWord_(_word): logger.info('Learning word: %s', word) checker.learnWord_(_word)
def screenshot(self, path, region = None): #https://pythonhosted.org/pyobjc/examples/Quartz/Core%20Graphics/CGRotation/index.html try: # record how long it takes to take screenshot start = time.time() # Set to capture entire screen, including multiple monitors if region is None: region = CG.CGRectInfinite # Create CGImage, composite image of windows in region image = CG.CGWindowListCreateImage( region, CG.kCGWindowListOptionOnScreenOnly, CG.kCGNullWindowID, CG.kCGWindowImageDefault ) scr = NSScreen.screens() xmin = 0 ymin = 0 for s in scr: if s.frame().origin.x < xmin: xmin = s.frame().origin.x if s.frame().origin.y < ymin: ymin = s.frame().origin.y nativeHeight = CGImageGetHeight(image)*1.0 nativeWidth = CGImageGetWidth(image)*1.0 nativeRatio = nativeWidth/nativeHeight prefHeight = NSUserDefaultsController.sharedUserDefaultsController().values().valueForKey_('imageSize') height = int(prefHeight/scr[0].frame().size.height*nativeHeight) width = int(nativeRatio * height) heightScaleFactor = height/nativeHeight widthScaleFactor = width/nativeWidth mouseLoc = NSEvent.mouseLocation() x = int(mouseLoc.x) y = int(mouseLoc.y) w = 16 h = 24 scale_x = int((x-xmin) * widthScaleFactor) scale_y = int((y-h+5-ymin) * heightScaleFactor) scale_w = w*widthScaleFactor scale_h = h*heightScaleFactor #Allocate image data and create context for drawing image imageData = LaunchServices.objc.allocateBuffer(int(4 * width * height)) bitmapContext = Quartz.CGBitmapContextCreate( imageData, # image data we just allocated... width, height, 8, # 8 bits per component 4 * width, # bytes per pixel times number of pixels wide Quartz.CGImageGetColorSpace(image), # use the same colorspace as the original image Quartz.kCGImageAlphaPremultipliedFirst # use premultiplied alpha ) #Draw image on context at new scale rect = CG.CGRectMake(0.0,0.0,width,height) Quartz.CGContextDrawImage(bitmapContext, rect, image) # Add Mouse cursor to the screenshot cursorPath = "../Resources/cursor.png" cursorPathStr = NSString.stringByExpandingTildeInPath(cursorPath) cursorURL = NSURL.fileURLWithPath_(cursorPathStr) # Create a CGImageSource object from 'url'. cursorImageSource = Quartz.CGImageSourceCreateWithURL(cursorURL, None) # Create a CGImage object from the first image in the file. Image # indexes are 0 based. cursorOverlay = Quartz.CGImageSourceCreateImageAtIndex(cursorImageSource, 0, None) Quartz.CGContextDrawImage(bitmapContext, CG.CGRectMake(scale_x, scale_y, scale_w, scale_h), cursorOverlay) #Recreate image from context imageOut = Quartz.CGBitmapContextCreateImage(bitmapContext) #Image properties dictionary dpi = 72 # FIXME: Should query this from somewhere, e.g for retina display properties = { Quartz.kCGImagePropertyDPIWidth: dpi, Quartz.kCGImagePropertyDPIHeight: dpi, Quartz.kCGImageDestinationLossyCompressionQuality: 0.6, } #Convert path to url for saving image pathWithCursor = path[0:-4] + "_" + str(x) + "_" + str(y) + '.jpg' pathStr = NSString.stringByExpandingTildeInPath(pathWithCursor) url = NSURL.fileURLWithPath_(pathStr) #Set image destination (where it will be saved) dest = Quartz.CGImageDestinationCreateWithURL( url, LaunchServices.kUTTypeJPEG, # file type 1, # 1 image in file None ) # Add the image to the destination, with certain properties Quartz.CGImageDestinationAddImage(dest, imageOut, properties) # finalize the CGImageDestination object. Quartz.CGImageDestinationFinalize(dest) #For testing how long it takes to take screenshot stop = time.time() print 'took ' + str(height) + 'px image in ' + str(stop-start)[:5] + ' seconds' except KeyboardInterrupt: print "Keyboard interrupt" AppHelper.stopEventLoop() except errno.ENOSPC: NSLog("No space left on storage device. Turning off Selfspy recording.") self.delegate.toggleLogging_(self) except: NSLog("couldn't save image")
#These are imported by QSB. Don't change these. import sys import thread import AppKit import Foundation #The debug variable. Set to True for debug messages in the command line, printout of the resp.xml on the desktop debug = False #Define some main variables. Don't change these. api_url='http://api.rememberthemilk.com/services/rest/?' auth_url='http://www.rememberthemilk.com/services/auth/?' api_key='60a9369798aa92cc5cc291b2280422f1' api_secret='6fdf8ca0e501715f' the_plist='~/Library/Preferences/com.rememberthemilk.RTM-QSB.plist' the_plist=NSString.stringByExpandingTildeInPath(the_plist) if debug: xml_resp = '~/Desktop/resp.xml' xml_resp = NSString.stringByExpandingTildeInPath(xml_resp) auth=1 the_token=0 try: import Vermilion # pylint: disable-msg=C6204 import VermilionNotify except ImportError: class Vermilion(object): """A mock implementation of the Vermilion class.
def screenshot(self, path, region = None): #https://pythonhosted.org/pyobjc/examples/Quartz/Core%20Graphics/CGRotation/index.html try: # record how long it takes to take screenshot start = time.time() scr = NSScreen.screens() # Trying to capture mouse cursor # Quartz.CGDisplayShowCursor(Quartz.CGMainDisplayID()) # Quartz.CGAssociateMouseAndMouseCursorPosition(True) # Set to capture entire screen, including multiple monitors if region is None: region = CG.CGRectInfinite # Create CGImage, composite image of windows in region image = None image = CG.CGWindowListCreateImage( region, CG.kCGWindowListOptionOnScreenOnly, CG.kCGNullWindowID, CG.kCGWindowImageDefault ) xmin = 0 ymin = 0 for s in scr: if s.frame().origin.x < xmin: xmin = s.frame().origin.x if s.frame().origin.y < ymin: ymin = s.frame().origin.y nativeHeight = CGImageGetHeight(image)*1.0 nativeWidth = CGImageGetWidth(image)*1.0 nativeRatio = nativeWidth/nativeHeight prefHeight = NSUserDefaultsController.sharedUserDefaultsController().values().valueForKey_('imageSize') height = int(prefHeight) #int(prefHeight/scr[0].frame().size.height*nativeHeight) width = int(nativeRatio * height) # Computes the scale factor between the user resolution and the native screen resolution resolutionScaleFactor = scr[0].frame().size.height / nativeHeight # Computes the scale factor between the image size in the preferences and the user resolution prefScaleFactor = height / scr[0].frame().size.height mouseLoc = NSEvent.mouseLocation() x = int(mouseLoc.x) y = int(mouseLoc.y) w = 16 h = 24 scale_x = int((x-xmin) * prefScaleFactor) scale_y = int((y-h+5-ymin) * prefScaleFactor) #int((y-h+5-ymin) * heightScaleFactor) scale_w = w*prefScaleFactor scale_h = h*prefScaleFactor #Allocate image data and create context for drawing image imageData = None imageData = LaunchServices.objc.allocateBuffer(int(100)) imageData = LaunchServices.objc.allocateBuffer(int(4 * width * height)) bitmapContext = None bitmapContext = Quartz.CGBitmapContextCreate( imageData, # image data we just allocated... width, height, 8, # 8 bits per component 4 * width, # bytes per pixel times number of pixels wide Quartz.CGImageGetColorSpace(image), # use the same colorspace as the original image Quartz.kCGImageAlphaPremultipliedFirst # use premultiplied alpha ) #Draw image on context at new scale rect = CG.CGRectMake(0.0,0.0,width,height) Quartz.CGContextDrawImage(bitmapContext, rect, image) # Add Mouse cursor to the screenshot cursorPath = "../Resources/cursor.png" cursorPathStr = NSString.stringByExpandingTildeInPath(cursorPath) cursorURL = NSURL.fileURLWithPath_(cursorPathStr) # Create a CGImageSource object from 'url'. cursorImageSource = None cursorImageSource = Quartz.CGImageSourceCreateWithURL(cursorURL, None) # Create a CGImage object from the first image in the file. Image # indexes are 0 based. cursorOverlay = None cursorOverlay = Quartz.CGImageSourceCreateImageAtIndex(cursorImageSource, 0, None) Quartz.CGContextDrawImage(bitmapContext, CG.CGRectMake(scale_x, scale_y, scale_w, scale_h), cursorOverlay) #Recreate image from context imageOut = Quartz.CGBitmapContextCreateImage(bitmapContext) #Image properties dictionary dpi = 72 # FIXME: Should query this from somewhere, e.g for retina display properties = { Quartz.kCGImagePropertyDPIWidth: dpi, Quartz.kCGImagePropertyDPIHeight: dpi, Quartz.kCGImageDestinationLossyCompressionQuality: 0.6, } # Getting id of current window and application try: activeAppName = self.workspace.activeApplication()['NSApplicationName'] except: activeAppName = "" print "failed NSApplicationName" active_app_id = self.getProcessIDFromName(activeAppName) options = kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) for window in windowList: # window_name = str(window.get('kCGWindowName', u'').encode('ascii', 'replace')) window_name = self.getWindowName(window) owner = window['kCGWindowOwnerName'] if (activeAppName == owner and window_name != ''): break active_window_id = self.getWindowIDFromName(window_name) # Done with getting id of current window and application #Convert path to url for saving image pathWithCursor = path[0:-4] + "_" + str(x) + "_" + str(y) if (active_app_id != None and active_app_id != '') : pathWithCursor = pathWithCursor + "_app" + str(active_app_id) if (active_window_id != None and active_window_id != '') : pathWithCursor = pathWithCursor + "_win" + str(active_window_id) pathWithCursor = pathWithCursor + '.jpg' # print pathWithCursor pathStr = NSString.stringByExpandingTildeInPath(pathWithCursor) url = NSURL.fileURLWithPath_(pathStr) #Set image destination (where it will be saved) dest = Quartz.CGImageDestinationCreateWithURL( url, LaunchServices.kUTTypeJPEG, # file type 1, # 1 image in file None ) # Add the image to the destination, with certain properties Quartz.CGImageDestinationAddImage(dest, imageOut, properties) # finalize the CGImageDestination object. Quartz.CGImageDestinationFinalize(dest) #For testing how long it takes to take screenshot stop = time.time() # print 'took ' + str(height) + 'px image in ' + str(stop-start)[:5] + ' seconds' except KeyboardInterrupt: print "Keyboard interrupt" AppHelper.stopEventLoop() except errno.ENOSPC: NSLog("No space left on storage device. Turning off Selfspy recording.") self.delegate.toggleLogging_(self) except: NSLog("couldn't save image")