本文整理汇总了Python中Cocoa.NSEvent类的典型用法代码示例。如果您正苦于以下问题:Python NSEvent类的具体用法?Python NSEvent怎么用?Python NSEvent使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NSEvent类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: applicationDidFinishLaunching_
def applicationDidFinishLaunching_(self, notification):
NSLog("Application did finish launching...")
# Register preferance defaults for user-facing preferences
prefDictionary = {}
prefDictionary[u"screenshots"] = True
prefDictionary[u'imageSize'] = 720 # in px
prefDictionary[u"imageTimeMax"] = 60 # in s
prefDictionary[u"imageTimeMin"] = 100 # in ms
prefDictionary[u"experienceTime"] = 1800 # in s
prefDictionary[u"experienceLoop"] = True
prefDictionary[u"recording"] = True
NSUserDefaultsController.sharedUserDefaultsController().setInitialValues_(prefDictionary)
mask = (NSKeyDownMask
| NSKeyUpMask
| NSLeftMouseDownMask
| NSLeftMouseUpMask
| NSRightMouseDownMask
| NSRightMouseUpMask
| NSMouseMovedMask
| NSScrollWheelMask
| NSFlagsChangedMask)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, sc.handler)
self.createStatusMenu()
# self.createStatusButton()
NSNotificationCenter.defaultCenter().postNotificationName_object_('checkLoops',self)
NSNotificationCenter.defaultCenter().postNotificationName_object_('noteRecordingState',self)
示例2: applicationDidFinishLaunching_
def applicationDidFinishLaunching_(self, notification):
mask = (NSKeyDownMask
| NSLeftMouseDownMask
| NSLeftMouseUpMask
| NSRightMouseDownMask
| NSRightMouseUpMask
| NSMouseMovedMask
| NSScrollWheelMask)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, sc.handler)
示例3: applicationDidFinishLaunching_
def applicationDidFinishLaunching_(self, notification):
#print "Sucessfully launched Obj-C application"
mask = (NSKeyDownMask
| NSLeftMouseDownMask
| NSRightMouseDownMask
| NSMouseMovedMask
| NSScrollWheelMask)
#| NSFlagsChangedMask)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, sc.handler)
示例4: handler
def handler(self, event):
try:
if event.type() == NSLeftMouseDown:
self.mouse_button_hook(1, True)
# elif event.type() == NSLeftMouseUp:
# self.mouse_button_hook(1, False)
elif event.type() == NSRightMouseDown:
self.mouse_button_hook(2, True)
# elif event.type() == NSRightMouseUp:
# self.mouse_button_hook(2, False)
elif event.type() == NSKeyDown:
self.key_hook(event.keyCode(), None, event.characters(), True, event.isARepeat())
elif event.type() == NSMouseMoved:
loc = NSEvent.mouseLocation()
self.mouse_move_hook(loc.x, loc.y)
if event.type() in [NSLeftMouseDown, NSRightMouseDown, NSMouseMoved]:
windowNumber = event.windowNumber()
windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly,
kCGNullWindowID)
for window in windowList:
if window['kCGWindowNumber'] == windowNumber:
self.focus.wm_name = window['kCGWindowName']
self.fucus.app_name = window['kCGWindowOwnerName']
break
except KeyboardInterrupt:
AppHelper.stopEventLoop()
示例5: move_handler
def move_handler(self, event):
recording = preferences.getValueForPreference('recording')
event_screenshots = preferences.getValueForPreference('eventScreenshots')
if event_screenshots:
self.sniffer.activity_tracker.take_screenshot()
if recording:
if event.type() == NSMouseMoved:
loc = NSEvent.mouseLocation()
# get all the image size information
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
x = int(loc.x) - xmin
y = int(loc.y) - ymin
# write JSON object to movelog file
text = '{"time": '+ str(cfg.NOW()) + ' , "location": [' + str(x) + ',' + str(y) + ']}'
utils_cocoa.write_to_file(text, cfg.MOVELOG)
示例6: click_handler
def click_handler(self, event):
recording = preferences.getValueForPreference('recording')
event_screenshots = preferences.getValueForPreference('eventScreenshots')
if event_screenshots:
self.sniffer.activity_tracker.take_screenshot()
if recording:
# check if the clipboard has updated
self.sniffer.clr.get_clipboard_contents()
# get data ready to write
loc = NSEvent.mouseLocation()
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
x = int(loc.x) - xmin
y = int(loc.y) - ymin
#get click type
click_type = "Unknown"
if event.type() == NSLeftMouseDown:
click_type = "Left"
elif event.type() == NSRightMouseDown:
click_type = "Right"
# write JSON object to clicklog file
text = '{"time": '+ str(cfg.NOW()) + ' , "button": "' + click_type + '", "location": [' + str(x) + ',' + str(y) + ']}'
utils_cocoa.write_to_file(text, cfg.CLICKLOG)
示例7: show_context
def show_context(self, options, x, y):
y = self.frame().size.height - y
menu = DropboxNSMenu.menuWithDropboxMenuDescriptor_(options)
if MAC_VERSION >= SNOW_LEOPARD:
menu.popUpMenuPositioningItem_atLocation_inView_(None, NSMakePoint(x, y), self)
return
fake_event = NSEvent.mouseEventWithType_location_modifierFlags_timestamp_windowNumber_context_eventNumber_clickCount_pressure_(NSLeftMouseDown, NSMakePoint(x, y), 0, 0, self.window().windowNumber(), None, 0, 0, 0)
NSMenu.popUpContextMenu_withEvent_forView_withFont_(menu, fake_event, self, NSFont.systemFontOfSize_(12.75))
示例8: handler
def handler(self, event):
try:
self.find_window()
loc = NSEvent.mouseLocation()
if event.type() == NSLeftMouseDown:
self.mouse_button_hook(1, loc.x, loc.y)
# elif event.type() == NSLeftMouseUp:
# self.mouse_button_hook(1, loc.x, loc.y)
elif event.type() == NSRightMouseDown:
self.mouse_button_hook(3, loc.x, loc.y,)
# elif event.type() == NSRightMouseUp:
# self.mouse_button_hook(2, loc.x, loc.y)
elif event.type() == NSScrollWheel:
if event.deltaY() > 0:
self.mouse_button_hook(4, loc.x, loc.y)
elif event.deltaY() < 0:
self.mouse_button_hook(5, loc.x, loc.y)
if event.deltaX() > 0:
self.mouse_button_hook(6, loc.x, loc.y)
elif event.deltaX() < 0:
self.mouse_button_hook(7, loc.x, loc.y)
# if event.deltaZ() > 0:
# self.mouse_button_hook(8, loc.x, loc.y)
# elif event.deltaZ() < 0:
# self.mouse_button_hook(9, loc.x, loc.y)
elif event.type() == NSKeyDown:
flags = event.modifierFlags()
modifiers = [] # OS X api doesn't care it if is left or right
if flags & NSControlKeyMask:
modifiers.append('Ctrl')
if flags & NSAlternateKeyMask:
modifiers.append('Alt')
if flags & NSCommandKeyMask:
modifiers.append('Cmd')
if flags & (NSShiftKeyMask | NSAlphaShiftKeyMask):
modifiers.append('Shift')
character = event.charactersIgnoringModifiers()
# these two get a special case because I am unsure of
# their unicode value
if event.keyCode() is 36:
character = "Enter"
elif event.keyCode() is 51:
character = "Backspace"
self.key_hook(event.keyCode(),
modifiers,
keycodes.get(character,
character),
event.isARepeat())
elif event.type() == NSMouseMoved:
self.mouse_move_hook(loc.x, loc.y)
except (Exception, KeyboardInterrupt):
AppHelper.stopEventLoop()
raise
示例9: takeExperienceScreenshot_
def takeExperienceScreenshot_(self, notification):
try:
mouseLoc = NSEvent.mouseLocation()
x = str(int(mouseLoc.x))
y = str(int(mouseLoc.y))
folder = os.path.join(cfg.CURRENT_DIR,"screenshots")
filename = datetime.now().strftime("%y%m%d-%H%M%S%f") + "_" + x + "_" + y + '-experience'
path = os.path.join(folder,""+filename+".jpg")
# -i makes the screenshot interactive
# -C captures the mouse cursor.
# -x removes the screenshot sound
if notification.object().takeFullScreenshot:
command = "screencapture -x -C '" + path + "'"
else:
command = "screencapture -i -x -C '" + path + "'"
# delete current full-screen screenshot for this experience
os.system("rm "+ notification.object().currentScreenshot )
os.system(command)
notification.object().currentScreenshot = path
if not notification.object().takeFullScreenshot:
path = os.path.expanduser(path)
experienceImage = NSImage.alloc().initByReferencingFile_(path)
width = experienceImage.size().width
height = experienceImage.size().height
ratio = width / height
if( width > 360 or height > 225 ):
if (ratio > 1.6):
width = 360
height = 360 / ratio
else:
width = 225 * ratio
height = 225
experienceImage.setScalesWhenResized_(True)
experienceImage.setSize_((width, height))
notification.object().screenshotDisplay.setImage_(experienceImage)
except errno.ENOSPC:
NSLog("No space left on storage device. Turning off Selfspy recording.")
self.delegate.toggleLogging_(self,self)
alert = NSAlert.alloc().init()
alert.addButtonWithTitle_("OK")
alert.setMessageText_("No space left on storage device. Turning off Selfspy recording.")
alert.setAlertStyle_(NSWarningAlertStyle)
alert.runModal()
except:
NSLog("Could not save image")
示例10: get_mouse_pos
def get_mouse_pos():
return Point(NSEvent.mouseLocation().x, NSEvent.mouseLocation().y)
示例11: screenshot
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
#.........这里部分代码省略.........
示例12: handler
def handler(self, event):
try:
recording = NSUserDefaultsController.sharedUserDefaultsController().values().valueForKey_('recording')
if(recording):
# get list of apps with regular activation
activeApps = self.workspace.runningApplications()
regularApps = []
for app in activeApps:
if app.activationPolicy() == 0:
regularApps.append(app)
# get a list of all named windows associated with regular apps
# including all tabs in Google Chrome
regularWindows = []
options = kCGWindowListOptionAll
windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID)
chromeChecked = False
safariChecked = False
for window in windowList:
window_name = str(window.get('kCGWindowName', u'').encode('ascii', 'replace'))
owner = window['kCGWindowOwnerName']
url = 'NO_URL'
geometry = window['kCGWindowBounds']
windows_to_ignore = ["Focus Proxy", "Clipboard"]
for app in regularApps:
if app.localizedName() == owner:
if (window_name and window_name not in windows_to_ignore):
if owner == 'Google Chrome' and not chromeChecked:
s = NSAppleScript.alloc().initWithSource_("tell application \"Google Chrome\" \n set tabs_info to {} \n set window_list to every window \n repeat with win in window_list \n set tab_list to tabs in win \n repeat with t in tab_list \n set the_title to the title of t \n set the_url to the URL of t \n set the_bounds to the bounds of win \n set t_info to {the_title, the_url, the_bounds} \n set end of tabs_info to t_info \n end repeat \n end repeat \n return tabs_info \n end tell")
tabs_info = s.executeAndReturnError_(None)
# Applescript returns list of lists including title and url in NSAppleEventDescriptors
# https://developer.apple.com/library/mac/Documentation/Cocoa/Reference/Foundation/Classes/NSAppleEventDescriptor_Class/index.html
numItems = tabs_info[0].numberOfItems()
for i in range(1, numItems+1):
window_name = str(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(1).stringValue().encode('ascii', 'replace'))
url = str(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(2 ).stringValue())
x1 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(1).stringValue())
y1 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(2).stringValue())
x2 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(3).stringValue())
y2 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(4).stringValue())
regularWindows.append({'process': 'Google Chrome', 'title': window_name, 'url': url, 'geometry': {'X':x1,'Y':y1,'Width':x2-x1,'Height':y2-y1} })
chromeChecked = True
elif owner == 'Safari' and not safariChecked:
s = NSAppleScript.alloc().initWithSource_("tell application \"Safari\" \n set tabs_info to {} \n set winlist to every window \n repeat with win in winlist \n set ok to true \n try \n set tablist to every tab of win \n on error errmsg \n set ok to false \n end try \n if ok then \n repeat with t in tablist \n set thetitle to the name of t \n set theurl to the URL of t \n set thebounds to the bounds of win \n set t_info to {thetitle, theurl, thebounds} \n set end of tabs_info to t_info \n end repeat \n end if \n end repeat \n return tabs_info \n end tell")
tabs_info = s.executeAndReturnError_(None)
print tabs_info
numItems = tabs_info[0].numberOfItems()
for i in range(1, numItems+1):
window_name = str(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(1).stringValue().encode('ascii', 'replace'))
url = str(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(2 ).stringValue())
x1 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(1).stringValue())
y1 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(2).stringValue())
x2 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(3).stringValue())
y2 = int(tabs_info[0].descriptorAtIndex_(i).descriptorAtIndex_(3).descriptorAtIndex_(4).stringValue())
regularWindows.append({'process': 'Safari', 'title': window_name, 'url': url, 'geometry': {'X':x1,'Y':y1,'Width':x2-x1,'Height':y2-y1} })
else:
regularWindows.append({'process': owner, 'title': window_name, 'url': url, 'geometry': geometry})
# get active app, window, url and geometry
# only track for regular apps
for app in regularApps:
if app.isActive():
for window in windowList:
if (window['kCGWindowNumber'] == event.windowNumber() or (not event.windowNumber() and window['kCGWindowOwnerName'] == app.localizedName())):
geometry = window['kCGWindowBounds']
# get browser_url
browser_url = 'NO_URL'
if (window.get('kCGWindowOwnerName') == 'Google Chrome'):
s = NSAppleScript.alloc().initWithSource_("tell application \"Google Chrome\" \n return URL of active tab of front window as string \n end tell")
browser_url = s.executeAndReturnError_(None)
if (window.get('kCGWindowOwnerName') == 'Safari'):
s = NSAppleScript.alloc().initWithSource_("tell application \"Safari\" \n set theURL to URL of current tab of window 1 \n end tell")
browser_url = s.executeAndReturnError_(None)
browser_url = str(browser_url[0])[33:-3]
# browser_url = urlparse(browser_url).hostname
if not browser_url:
browser_url = 'NO_URL'
# call screen hook
self.screen_hook(window['kCGWindowOwnerName'],
window.get('kCGWindowName', u'').encode('ascii', 'replace'),
geometry['X'],
geometry['Y'],
geometry['Width'],
geometry['Height'],
browser_url,
regularApps,
regularWindows)
break
break
loc = NSEvent.mouseLocation()
if event.type() == NSLeftMouseDown:
self.mouse_button_hook(1, loc.x, loc.y)
# elif event.type() == NSLeftMouseUp:
# self.mouse_button_hook(1, loc.x, loc.y)
elif event.type() == NSRightMouseDown:
self.mouse_button_hook(3, loc.x, loc.y)
#.........这里部分代码省略.........
示例13: applicationDidFinishLaunching_
def applicationDidFinishLaunching_(self, notification):
downMask = NSKeyDownMask
upMask = NSKeyUpMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(downMask, downHandler)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(upMask, upHandler)
示例14: applicationDidFinishLaunching_
def applicationDidFinishLaunching_(self, notification):
mask1 = NSKeyDownMask
mask2 = NSLeftMouseUpMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask1, handler)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask2, handler)
示例15: setupKeyCounterMac
def setupKeyCounterMac(self):
mask = NSKeyDownMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, self.macCountKey)
NSEvent.addLocalMonitorForEventsMatchingMask_handler_(mask, self.macCountKey)