def get_workareas(): try: from AppKit import NSScreen #@UnresolvedImport except ImportError as e: log("cannot get workarea info without AppKit: %s", e) return [] workareas = [] screens = NSScreen.screens() for screen in screens: log("get_workareas() testing screen %s", screen) frame = screen.frame() visibleFrame = screen.visibleFrame() log(" frame=%s, visibleFrame=%s", frame, visibleFrame) try: #10.7 onwards: log(" backingScaleFactor=%s", screen.backingScaleFactor()) except: pass x = int(visibleFrame.origin.x - frame.origin.x) y = int((frame.size.height - visibleFrame.size.height) - (frame.origin.y - visibleFrame.origin.y)) w = int(visibleFrame.size.width) h = int(visibleFrame.size.height) workareas.append((x, y, w, h)) log("get_workareas()=%s", workareas) return workareas
def get_workareas(): try: from AppKit import NSScreen #@UnresolvedImport except ImportError as e: log("cannot get workarea info without AppKit: %s", e) return [] workareas = [] screens = NSScreen.screens() for screen in screens: log("get_workareas() testing screen %s", screen) frame = screen.frame() visibleFrame = screen.visibleFrame() log(" frame=%s, visibleFrame=%s", frame, visibleFrame) try: #10.7 onwards: log(" backingScaleFactor=%s", screen.backingScaleFactor()) except: pass x = int(visibleFrame.origin.x - frame.origin.x) y = int((frame.size.height - visibleFrame.size.height) - (visibleFrame.origin.y - frame.origin.y)) w = int(visibleFrame.size.width) h = int(visibleFrame.size.height) workareas.append((x, y, w, h)) log("get_workareas()=%s", workareas) return workareas
def set_background(image_file): from AppKit import NSWorkspace, NSScreen from Foundation import NSURL file_url = NSURL.fileURLWithPath_(image_file) ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def screen_from_point(point): screens = NSScreen.screens() for screen in screens: if NSPointInRect(point, screen.frame()): return screen return NSScreen.mainScreen()
def showWindow_(self, sender): width, height = 400, 300 minWidth, minHeight = 100, 100 maxWidth, maxHeight = 500, 500 # max size of window = size of largest screen: for screen in NSScreen.screens(): screenSize = screen.visibleFrame().size maxWidth = max(int(screenSize.width), maxWidth) maxHeight = max(int(screenSize.height), maxHeight) w = FloatingWindow((width, height), self.name, minSize=(minWidth, minHeight), maxSize=(maxWidth, maxHeight)) w.center() window = w.getNSWindow() window.setTitlebarAppearsTransparent_(1) window.setStandardWindowTitleButtonsAlphaValue_(0.00001) window.setBackgroundColor_(NSColor.whiteColor()) window.setAlphaValue_(0.9) window.setMovableByWindowBackground_(1) w.im = ImageView((10, 10, -10, -10), horizontalAlignment='center', verticalAlignment='center', scale='proportional') w.im.setImage(imagePath=self.iconPath) imview = w.im.getNSImageView() imview.setEditable_(True) imview.setFocusRingType_(NSFocusRingTypeNone) w.open() w.select()
def change_desktop_background(file, desk_id): """Function that applies the named file as wallaper for the specified monitor (desk_id)""" file_url = NSURL.fileURLWithPath_(file) screen = NSScreen.screens()[desk_id] ws = NSWorkspace.sharedWorkspace() ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def get_screen_with_mouse_index(): mouseLocation = NSEvent.mouseLocation() screens = NSScreen.screens() for i, screen in enumerate(screens): if NSMouseInRect(mouseLocation, screen.frame(), False): return i return 0
def set_desktop_background(desktop_picture_path): file_url = NSURL.fileURLWithPath_(desktop_picture_path) ws = NSWorkspace.sharedWorkspace() screens = NSScreen.screens() for screen in screens: ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def doit(direction=-1, resize=1): thwin = get_active_window() win_bounds = thwin.bounds() screens = NSScreen.screens() screenlist = coordinate_screens( [frame_to_bounds(s.frame()) for s in screens]) screenid = which_screen_contains_window(screenlist, win_bounds) screen_bounds = screenlist[screenid] screen_size = [ screen_bounds[n + 2] - screen_bounds[n] for n in range(len(screen_bounds)) if n < len(screen_bounds) - 2 ] window_size = [ win_bounds[n + 2] - win_bounds[n] for n in range(len(win_bounds)) if n < len(win_bounds) - 2 ] if resize == 1: dw = screen_size[0] / 2.0 else: dw = window_size[0] dh = screen_size[1] if direction < 0: ox, oy = screen_bounds[0:2] elif direction > 0: ox, oy = screen_bounds[0] + (screen_size[0] - dw), screen_bounds[1] else: dw = screen_size[0] ox, oy = screen_bounds[0:2] newbounds = [int(n) for n in ox, oy, ox + dw, oy + dh] thwin.bounds.set(newbounds)
def next_image(self, _): if not os.path.exists(self.media_dir): os.makedirs(self.media_dir) url = 'https://unsplash.it/' if self.gray_mood: url += 'g/' url += '{w}/{h}/?random' if self.blur: url += '&blur' url = url.format(w=self.screen_width, h=self.screen_height) file_name = self.media_dir + datetime.datetime.now().strftime("%H:%M:%S.%f") + '.jpg' try: self.icon = 'img/wait.png' urllib.urlretrieve(url, file_name) file_url = NSURL.fileURLWithPath_(file_name) # Get shared workspace ws = NSWorkspace.sharedWorkspace() # Iterate over all screens for screen in NSScreen.screens(): # Tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_url, screen, {}, None) self.icon = 'img/icon.png' except IOError: print('Service unavailable, check your internet connection.') rumps.alert(title='Connection Error', message='Service unavailable\n' 'Please, check your internet connection')
def __init__(self): super(RadioBar, self).__init__('RadioBar', icon='radio-icon-grey.png', template=None, quit_button=None) self.show_notifications = True self.show_notification_station_change = False self.show_nowplaying_menubar = True self.default_icon = 'radio-icon.png' # 'radio-icon.png' or 'radio-icon-green.png' self.default_icon_disabled = 'radio-icon-grey.png' self.default_color_list = [ 255, 255, 255, 1 ] # format: r,g,b,alpha // [29,185,84,1] = "Spotify green" // [0,0,0,1] = "White" self.default_color_list_disabled = [255, 255, 255, 0.4] # Truncate if the screen is smaller than 1440px wide self.truncate = NSScreen.screens()[0].frame().size.width <= 1440 self.active_station = None self.nowplaying = None self.player = vlc.MediaPlayer() self.stations = [] self.urls = {} self.get_stations() # prevent multiple calls from sleep/wake self.awake = True self.threads = [] remote_thread = RadioBarRemoteThread(self, '127.0.0.1', 65432) remote_thread.daemon = True self.threads.append(remote_thread) remote_thread.start()
def name(self): """ The name of this monitor. """ handle = self.handle for screen in NSScreen.screens(): if screen.deviceDescription()['NSScreenNumber'] == handle: return screen.localizedName() return u"macOS monitor"
def get_monitor_locations(): """Not tested.""" result = [] for screen in NSScreen.screens(): rect = NSScreen.frame(screen) x, y = rect.origin.x, rect.origin.y width, height = rect.size.width, rect.size.height result.append(tuple(map(int, (x, y, x + width, y + height)))) return result
def get_icc_info(): from AppKit import NSScreen #@UnresolvedImport ms = NSScreen.mainScreen() info = do_get_screen_icc_info(ms) screens = NSScreen.screens() for i, screen in enumerate(screens): si = do_get_screen_icc_info(screen) if si: info[i] = si return info
def setup(self): screens = NSScreen.screens() self.numScreens = len(screens) tops, bottoms, lefts, rights = [], [], [], [] for s in screens: self.parseScreen(s, tops, bottoms, lefts, rights) self.totalWidth = max(rights) - min(lefts) self.totalHeight = max(tops) - min(bottoms) self.cleanSides(self.verticalLines) self.cleanSides(self.horizontalLines)
def setBackgroundOSX(fullPath): # generate a fileURL for the desktop picture file_path = NSURL.fileURLWithPath_(fullPath) # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_path, screen, {}, None)
def set_wallpaper_image(imgs, mode='stretched'): """Set the given file as wallpaper.""" if not len(imgs): return default_image = imgs[0] file_url = NSURL.fileURLWithPath_(default_image) options = {} ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, options, None)
def get_main_screen_rect(): screen_frame = None try: if MAC_VERSION >= MAVERICKS: screen = NSScreen.mainScreen() else: screen = NSScreen.screens()[0] screen_frame = screen.frame() except Exception: unhandled_exc_handler() if screen_frame is None: TRACE("!! Couldn't get the screen information from the OS.") return screen_frame
def get_icc_info(): try: from AppKit import NSScreen #@UnresolvedImport except ImportError as e: log("cannot get icc info without AppKit: %s", e) return {} ms = NSScreen.mainScreen() info = do_get_screen_icc_info(ms) screens = NSScreen.screens() for i, screen in enumerate(screens): si = do_get_screen_icc_info(screen) if si: info[i] = si return info
def screen(self): # if on macOS if platform.system() == "Darwin": # TODO: Add a class function that handles this task for the different # operating systems automatically try: # find the NSScreen representing the Looking Glass for screen in NSScreen.screens(): if 'LKG' in screen.localizedName( ): # == self.configuration['serial']: # # move the window to the Looking Glass Screen and resize it # NSApp._.windows[-1].setFrame_display_(screen.visibleFrame(), True) # break return { 'w': int(screen.frame().size.width), 'h': int(screen.frame().size.height), 'x': int(screen.frame().origin.x), 'y': int(screen.frame().origin.y) } except: raise IOError("Can't find matching screen") # if on Linux elif platform.system() == "Linux": # Try to find the Looking Glass monitor monitors = subprocess.run(["xrandr", "--listactivemonitors"], capture_output=True, text=True).stdout for m in re.finditer( r'^ (?P<screen>[0-9]+): \S+ (?P<w>\d+)/\d+x(?P<h>\d+)/\d+\+(?P<x>\d+)\+(?P<y>\d+)\s+(?P<connector>\S+)', monitors, re.MULTILINE): m = { k: int(v) if v.isdecimal() else v for (k, v) in m.groupdict().items() } if (m['w'] == self.configuration['screenW'] and m['h'] == self.configuration['screenH']): # TODO: Double-check EDID return m else: raise IOError("Can't find matching screen")
def setFile(): # generate a fileURL for the desktop picture file_path = NSURL.fileURLWithPath_(base_dir + image_file.decode("utf-8")) # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_path, screen, ws.desktopImageOptionsForScreen_(screen), None) if error: print error
def main(): """ Find and apply the most appropriate desktop pic for this machine """ final_path = find_picture(str(sys.argv[4])) if not final_path: sys.exit(1) print('Picture Path - ', final_path) file_url = NSURL.fileURLWithPath_(final_path) options = {} ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, options, None)
def enumerate_monitors() -> T.Iterable[Monitor]: from AppKit import NSScreen screens = NSScreen.screens() for screen in screens: f = screen.frame if callable(f): f = f() yield Monitor( x=int(f.origin.x), y=int(f.origin.y), width=int(f.size.width), height=int(f.size.height), )
def get_workareas(): workareas = [] screens = NSScreen.screens() for screen in screens: log("get_workareas() testing screen %s", screen) frame = screen.frame() visibleFrame = screen.visibleFrame() log(" frame=%s, visibleFrame=%s", frame, visibleFrame) log(" backingScaleFactor=%s", screen.backingScaleFactor()) x = int(visibleFrame.origin.x - frame.origin.x) y = int((frame.size.height - visibleFrame.size.height) - (visibleFrame.origin.y - frame.origin.y)) w = int(visibleFrame.size.width) h = int(visibleFrame.size.height) workareas.append((x, y, w, h)) log("get_workareas()=%s", workareas) return workareas
def displays(self): screens = NSScreen.screens() connected = [] for screen in screens: screen = screen.frame() origin_y = screen.origin.y # Flip coordinate space because Apple is weird # https://developer.apple.com/documentation/coregraphics/cgrect if len(connected) > 0: origin_y = -screen.size.height - (origin_y - connected[0]["y"]) connected.append({ "x": int(screen.size.width), "y": int(screen.size.height), "offset_x": int(screen.origin.x), "offset_y": int(origin_y) }) return connected
def main(): width = 550 height = 550 print("Updating...") j = urllib2.urlopen("http://himawari8-dl.nict.go.jp/himawari8/img/D531106/latest.json") latest = strptime(json.load(j)["date"], "%Y-%m-%d %H:%M:%S") print("Latest version: {} GMT\n".format(strftime("%Y/%m/%d/%H:%M:%S", latest))) url_format = "http://himawari8.nict.go.jp/img/D531106/{}d/{}/{}_{}_{}.png" png = Image.new('RGB', (width*level, height*level)) print("Downloading tiles: 0/{} completed".format(level*level)) for x in range(level): for y in range(level): tile_w = urllib2.urlopen(url_format.format(level, width, strftime("%Y/%m/%d/%H%M%S", latest), x, y)) tiledata = tile_w.read() tile = Image.open(BytesIO(tiledata)) png.paste(tile, (width*x, height*y, width*(x+1), height*(y+1))) print("Downloading tiles: {}/{} completed".format(x*level + y + 1, level*level)) print("\nDownloaded\n") output_file = tempfile.NamedTemporaryFile().name + ".png" png.save(output_file, "PNG") file_url = NSURL.fileURLWithPath_(output_file) options = {'NSImageScaleProportionallyUpOrDown': True} # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_url, screen, options, None) if error: print error exit(-1) print("Done!\n")
def get_all_monitors(cls): # Get monitor information from AppKit. monitors = [] for screen in NSScreen.screens(): # Get the monitor handle. handle = screen.deviceDescription()['NSScreenNumber'] # Create a rectangle object representing the monitor's # dimensions and relative position. frame = screen.frame() dx = frame.size.width - frame.origin.x dy = frame.size.height - frame.origin.y rectangle = Rectangle(frame.origin.x, frame.origin.y, dx, dy) # Get a new or updated monitor object and add it to the list. monitors.append(cls.get_monitor(handle, rectangle)) return monitors
def displays(self): screens = NSScreen.screens() connected = [] for idx, screen in enumerate(screens): screen = screen.frame() origin_y = screen.origin.y # Flip coordinate space because Apple is weird # https://developer.apple.com/documentation/coregraphics/cgrect if len(connected) > 0: origin_y = -screen.size.height - (origin_y - connected[0]["y"]) connected.append({ "id": idx, "width": int(screen.size.width), "height": int(screen.size.height), "x": int(screen.origin.x), "y": int(origin_y) }) return connected
def apply_desktop_wallpaper(work_space, url): """Apply desktop wallpaper""" # make image options dictionary # we just make an empty one because the defaults are fine options = {} # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture result = work_space.setDesktopImageURL_forScreen_options_error_( url, screen, options, None) for item in result: if item is True: print("Wallpaper applied!") break
def showWindow_(self, sender): width, height = 400, 300 minWidth, minHeight = 100, 100 maxWidth, maxHeight = 500, 500 # max size of window = size of largest screen: for screen in NSScreen.screens(): screenSize = screen.visibleFrame().size maxWidth = max(int(screenSize.width), maxWidth) maxHeight = max(int(screenSize.height), maxHeight) window = NSPanel.new() window.setMinSize_(NSMakeSize(minWidth, minHeight)) window.setStyleMask_(NSTitledWindowMask | NSUtilityWindowMask | NSResizableWindowMask | NSClosableWindowMask) window.setTitlebarAppearsTransparent_(1) window.setStandardWindowTitleButtonsAlphaValue_(0.00001) window.setBackgroundColor_(NSColor.textBackgroundColor()) window.setAlphaValue_(0.9) window.setMovableByWindowBackground_(1) if Glyphs.defaults[ "NSWindow Frame com.dyb.floatingImageFrame"] is not None: window.setFrameUsingName_("com.dyb.floatingImageFrame") else: window.setFrame_display_(NSMakeRect(0, 0, width, height), True) window.center() window.setFrameAutosaveName_("com.dyb.floatingImageFrame") window.setLevel_(NSFloatingWindowLevel) imview = DYDraggingImageView.alloc().initWithFrame_( window.contentView().frame()) imview.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable) imview.setEditable_(True) imview.setFocusRingType_(NSFocusRingTypeNone) imview.setImage_(self.icon) window.contentView().addSubview_(imview) window.makeKeyAndOrderFront_(self)
def get_screensize(): try: if sys.platform in ['Windows', 'win32', 'cygwin']: from win32api import GetSystemMetrics import win32con width_px = GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN) height_px = GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN) return {'width': int(width_px), 'height': int(height_px)} elif sys.platform in ['Mac', 'darwin', 'os2', 'os2emx']: from AppKit import NSScreen screen = NSScreen.screens()[0] width_px = screen.frame().size.width height_px = screen.frame().size.height return {'width': int(width_px), 'height': int(height_px)} elif sys.platform in ['linux', 'linux2']: import Xlib.display resolution = Xlib.display.Display().screen().root.get_geometry() width_px = resolution.width height_px = resolution.height return {'width': int(width_px), 'height': int(height_px)} except NotImplementedError: sys.exit( "Platform not recognized. Supported platforms are Windows, MacOS, Linux" )
def getScreenInfo(): # Collect screen info into a dictinary screenInfo = [] mainScreenDescription = NSScreen.mainScreen().deviceDescription() for screen in NSScreen.screens(): # Screen info thisScreenDescription = screen.deviceDescription() frame = screen.frame() origin = (frame.origin.x, frame.origin.y) size = (frame.size.width, frame.size.height) # Find the orientation h = 1 if origin[0] > 0 else -1 if origin[0] < 0 else 0 v = 1 if origin[1] > 0 else -1 if origin[1] < 0 else 0 orientations = [(-1, 1), (0, 1), (1, 1), (-1, 0), (0, 0), (1, 0), (-1, -1), (0, -1), (1, -1)] orientationSymbols = [ "↖️", "⬆️", "↗️", "⬅️", "⏺", "➡️", "↙️", "⬇️", "↘️" ] o = orientationSymbols[orientations.index((h, v))] # Screen name and info thisScreenInfo = dict(name=None, origin=origin, size=size, isMain=False, orientation=o) if thisScreenDescription["NSScreenNumber"] == mainScreenDescription[ "NSScreenNumber"]: thisScreenInfo["name"] = "Main screen (%s × %s)" % (int( size[0]), int(size[1])) thisScreenInfo["isMain"] = True else: thisScreenInfo["name"] = "Other screen (%s × %s)" % (int( size[0]), int(size[1])) screenInfo.append(thisScreenInfo) return screenInfo
def isPointOnAScreen(point): screens = NSScreen.screens() count = screens.count() for i in range(count): if (NSPointInRect(point, screens[i].frame())): return screens[i] return None
parser = argparse.ArgumentParser(description='Sets the desktop picture on all screens') parser.add_argument('--path', help='The path of the image') args = vars(parser.parse_args()) #already loggedin so we can skip any kind of security getusername = os.getlogin() #desktop_path = subprocess.check_output(['xdg-user-dir', 'DOCUMENTS']) #name of the file to be used. Store in the same folder as the script I recommend a nice one of hasselhoff file_name = 'background.jpg' #the directory where stuff will be copied tp directory_path = '/Users/' + getusername + '/Documents/' shutil.copy2(file_name, directory_path) #need th final picture path picture_path = '/Users/' + getusername + '/Documents/' + file_name # generate a fileURL for the desktop picture file_url = NSURL.fileURLWithPath_(picture_path) # make image options dictionary # we just make an empty one because the defaults are fine options = {} # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_url, screen, options, None) if error: print error exit(-1)
# imports for timingSetup from __future__ import division # so that 1/3=0.333 instead of 1/3=0 from AppKit import NSScreen from psychopy import visual, data, core, event, monitors from psychopy.constants import * # things like STARTED, FINISHED import os from os.path import expanduser import cPickle as pickle import sys sys.dont_write_bytecode = True import vwmClasses ######### Monitor Settings ################## MonitorWidth = NSScreen.screens()[0].frame().size.width MonitorHeight = NSScreen.screens()[0].frame().size.height SubjDistance = 45 # distance from the screen in centimeters MonitorWidthCM = 27 # in cm # set up window mon = monitors.Monitor('') mon.setDistance(SubjDistance) # centimeters of between monitor and subject mon.setSizePix([MonitorWidth,MonitorHeight]) mon.setWidth(MonitorWidthCM) # width in pixels of the monitor win = visual.Window(size=(MonitorWidth, MonitorHeight), fullscr=True, screen=1, allowGUI=False, allowStencil=False, monitor=mon, units = 'deg', color=[0,0,0], colorSpace='rgb', blendMode='avg') # behav trial run for data saving behavRun = 'behav5' # make filenames based on date and terminal input date = data.getDateStr() homeDirectory = expanduser("~")
def on_start_recording(self, task): """Notification that we are about to start an operation that needs to be recorded""" if self.must_exit: return import psutil if task['log_data']: if not self.job['dtShaper']: if not self.job['shaper'].configure(self.job, task): self.task['error'] = "Error configuring traffic-shaping" self.cpu_start = psutil.cpu_times() self.recording = True ver = platform.uname() task['page_data']['osVersion'] = '{0} {1}'.format(ver[0], ver[2]) task['page_data']['os_version'] = '{0} {1}'.format(ver[0], ver[2]) if self.rosetta: try: task['page_data']['osPlatform'] = subprocess.check_output( ['arch', '-arm64', 'uname', '-mp'], universal_newlines=True).strip() except Exception: task['page_data']['osPlatform'] = '{0} {1}'.format( ver[4], ver[5]) else: task['page_data']['osPlatform'] = '{0} {1}'.format( ver[4], ver[5]) # Spawn tcpdump if self.tcpdump_enabled: self.profile_start('desktop.start_pcap') self.pcap_file = os.path.join(task['dir'], task['prefix']) + '.cap' interface = 'any' if self.job[ 'interface'] is None else self.job['interface'] if self.options.tcpdump: interface = self.options.tcpdump if platform.system() == 'Windows': tcpdump = os.path.join(self.support_path, 'windows', 'WinDump.exe') if interface == 'any': args = [ tcpdump, '-p', '-s', '0', '-w', self.pcap_file, 'tcp', 'or', 'udp' ] else: args = [ tcpdump, '-p', '-i', interface, '-s', '0', '-w', self.pcap_file, 'tcp', 'or', 'udp' ] logging.debug(' '.join(args)) self.tcpdump = subprocess.Popen( args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) else: args = [ 'sudo', 'tcpdump', '-p', '-i', interface, '-s', '0', '-w', self.pcap_file, 'tcp', 'or', 'udp' ] logging.debug(' '.join(args)) self.tcpdump = subprocess.Popen(args) # Wait for the capture file to start growing end_time = monotonic() + 5 started = False while not started and monotonic() < end_time: if os.path.isfile(self.pcap_file): started = True time.sleep(0.1) self.profile_end('desktop.start_pcap') # Start video capture if self.job['capture_display'] is not None and not self.job[ 'disable_video']: screen_width = 1920 screen_height = 1280 device_pixel_ratio = None self.profile_start('desktop.start_video') if task['navigated']: self.execute_js(SET_ORANGE) time.sleep(1) task['video_file'] = os.path.join( task['dir'], task['prefix']) + '_video.mp4' if platform.system() == 'Windows': from win32api import GetSystemMetrics #pylint: disable=import-error screen_width = GetSystemMetrics(0) screen_height = GetSystemMetrics(1) elif platform.system() == 'Darwin': try: from AppKit import NSScreen #pylint: disable=import-error screen = NSScreen.screens()[0] screen_width = int(screen.frame().size.width) screen_height = int(screen.frame().size.height) device_pixel_ratio = float(screen.backingScaleFactor()) except Exception: pass task['width'] = min(task['width'], screen_width) task['height'] = min(task['height'], screen_height) if platform.system() == 'Darwin': width = task['width'] height = task['height'] x = 0 y = 0 if 'capture_rect' in self.job: width = self.job['capture_rect']['width'] height = self.job['capture_rect']['height'] x = self.job['capture_rect']['x'] y = self.job['capture_rect']['y'] if device_pixel_ratio is not None: width = int(math.ceil(width * device_pixel_ratio)) height = int(math.ceil(height * device_pixel_ratio)) x = int(math.ceil(x * device_pixel_ratio)) y = int(math.ceil(y * device_pixel_ratio)) args = [ 'ffmpeg', '-f', 'avfoundation', '-i', str(self.job['capture_display']), '-r', str(self.job['fps']), '-filter:v', 'crop={0:d}:{1:d}:{2:d}:{3:d}'.format( width, height, x, y), '-codec:v', 'libx264rgb', '-crf', '0', '-preset', 'ultrafast', task['video_file'] ] elif platform.system() == 'Windows': args = [ 'ffmpeg', '-f', 'gdigrab', '-video_size', '{0:d}x{1:d}'.format(task['width'], task['height']), '-framerate', str(self.job['fps']), '-draw_mouse', '0', '-i', str(self.job['capture_display']), '-codec:v', 'libx264rgb', '-crf', '0', '-preset', 'ultrafast', task['video_file'] ] else: args = [ 'ffmpeg', '-f', 'x11grab', '-video_size', '{0:d}x{1:d}'.format(task['width'], task['height']), '-framerate', str(self.job['fps']), '-draw_mouse', '0', '-i', str(self.job['capture_display']), '-filter:v', 'showinfo', '-codec:v', 'libx264rgb', '-crf', '0', '-preset', 'ultrafast', task['video_file'] ] if platform.system() in ['Linux', 'Darwin']: args.insert(0, 'nice') args.insert(1, '-n') args.insert(2, '10') logging.debug(' '.join(args)) try: if platform.system() == 'Windows': self.ffmpeg = subprocess.Popen( args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP, stdin=subprocess.PIPE) else: self.ffmpeg = subprocess.Popen(args, stdin=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) # Wait up to 5 seconds for something to be captured end_time = monotonic() + 5 started = False initial_size = None while not started and monotonic() < end_time: try: if platform.system() == 'Windows': if os.path.isfile(task['video_file']): video_size = os.path.getsize( task['video_file']) if initial_size == None: initial_size = video_size logging.debug( "video: capture file size: %d", video_size) if video_size > initial_size or video_size > 10000: started = True else: logging.debug( "video: waiting for capture file") if not started: time.sleep(0.1) else: output = self.ffmpeg.stderr.readline().strip() if output: logging.debug("ffmpeg: %s", output) if re.search(r'\]\sn\:\s+0\s+pts\:\s+', output) is not None: logging.debug("Video started") started = True elif re.search( r'^frame=\s+\d+\s+fps=[\s\d\.]+', output) is not None: logging.debug("Video started") started = True except Exception: logging.exception( "Error waiting for video capture to start") self.video_capture_running = True # Start a background thread to pump the ffmpeg output if platform.system() != 'Windows': self.stop_ffmpeg = False self.ffmpeg_output_thread = threading.Thread( target=self.pump_ffmpeg_output) self.ffmpeg_output_thread.start() except Exception: logging.exception('Error starting video capture') self.profile_end('desktop.start_video') # start the background thread for monitoring CPU and bandwidth self.usage_queue = multiprocessing.JoinableQueue() self.thread = threading.Thread(target=self.background_thread) self.thread.daemon = True self.thread.start()
# Hide Dock icon since it will interfere with what we're doing here # See: http://stackoverflow.com/a/9220911/390044 # See: https://developer.apple.com/library/mac/#documentation/AppKit/Reference/NSRunningApplication_Class/Reference/Reference.html NSApplicationActivationPolicyRegular = 0 NSApplicationActivationPolicyAccessory = 1 NSApplicationActivationPolicyProhibited = 2 NSApplication.sharedApplication() NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited) # Get the mainScreen mf = NSScreen.mainScreen().frame() mY = mf.origin.y mH = mf.size.height # and all screens to process query screens = NSScreen.screens() def screenIdOf(screen): return str(screen.deviceDescription()["NSScreenNumber"]) def screenDimOf(screen): f = screen.frame() return "%dx%d" % (f.size.width, f.size.height) matchedScreens = [s for s in screens if screenIdOf(s) in displaysInQuestion] if len(matchedScreens) == 0: matchedScreens = [s for s in screens if screenDimOf(s) in displaysInQuestion] if len(matchedScreens) == 0: matchedScreens = [] for idx in displaysInQuestion: try: i = int(idx) matchedScreens += [screens[i]]
def screens(cls): return NSScreen.screens()
def get_screens(): return NSScreen.screens()
# Isolate the filename picture_name = picture_path.split('/')[-1] # Create a directory for it. Set second arg as directory if given. if options.base_dir: base_dir = options.base_dir if base_dir[-1] != '/': base_dir = base_dir + '/' else: base_dir = os.path.dirname( os.path.realpath(__file__)) + '/Pictures/Cabins/' if not os.path.exists(base_dir): os.makedirs(base_dir) # Download the file if you haven't already if not os.path.isfile(base_dir + picture_name): urllib.urlretrieve(picture_path, base_dir + picture_name) # generate a fileURL for the desktop picture file_url = NSURL.fileURLWithPath_(base_dir + picture_name) # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_url, screen, ws.desktopImageOptionsForScreen_(screen), None)
# TIMING / DURATION (seconds) display_time = 3 blank_time = 0.5 feedback_time = 0.5 # OTHER BLOCK OPTIONS response_key = {'left': 'left_key', 'right': 'right_key'} continue_key = ['space'] ''' Specify total number of trials in each block here; prac => practice; fml => formal''' num_trial_prac = 3 num_trial_fml = 32 # should be a multiple of 8 (8 -> number of conditions) # MONITOR mon_width = NSScreen.screens()[0].frame( ).size.width # please set the monitor width & height manually mon_height = NSScreen.screens()[0].frame( ).size.height # if you plan to run this program on Windows ######################################### CLASSES & FUNCTIONS ########################################## class Box: """The background box Attributes ---------- top_box, bottom_box -> box top_label ('Shape'), bottom_label ('Filling') -> label Methods
def change_desktop_background(file): file_url = NSURL.fileURLWithPath_(file) ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
import random import subprocess from AppKit import NSWorkspace, NSScreen from Foundation import NSURL def change_desktop_background(file, desk_id): """Function that applies the named file as wallaper for the specified monitor (desk_id)""" file_url = NSURL.fileURLWithPath_(file) screen = NSScreen.screens()[desk_id] ws = NSWorkspace.sharedWorkspace() ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None) #--- Determine number of monitors currently active. num_mon = len(NSScreen.screens()) mon_rng = range(0,num_mon) #--- Path to wallpaper files, with trailing path separator. Note that the path #--- could be different, and be specified individually for each entry in the #--- wallpaper dictionary below. wp_dir = os.environ.get('WALLPAPER') if wp_dir == None: print 'Error: Environment variable specifying path to wallpaper folder '\ 'not defined: $WALLPAPER' sys.exit() if not os.path.exists(wp_dir): print 'Error: Specified path for wallpaper folder does not exist: ',wp_dir sys.exit() parser = argparse.ArgumentParser(description="Set wallpaper on all or "\
def on_start_recording(self, task): """Notification that we are about to start an operation that needs to be recorded""" import psutil if self.device_pixel_ratio is None: self.device_pixel_ratio = 1.0 try: ratio = self.execute_js('window.devicePixelRatio') #pylint: disable=assignment-from-none if ratio is not None: self.device_pixel_ratio = max(1.0, float(ratio)) except Exception: pass if task['log_data']: if not self.job['shaper'].configure(self.job, task): self.task['error'] = "Error configuring traffic-shaping" self.cpu_start = psutil.cpu_times() self.recording = True ver = platform.uname() task['page_data']['osVersion'] = '{0} {1}'.format(ver[0], ver[2]) task['page_data']['os_version'] = '{0} {1}'.format(ver[0], ver[2]) # Spawn tcpdump if self.tcpdump_enabled: self.pcap_file = os.path.join(task['dir'], task['prefix']) + '.cap' interface = 'any' if self.job[ 'interface'] is None else self.job['interface'] if self.options.tcpdump: interface = self.options.tcpdump if platform.system() == 'Windows': tcpdump = os.path.join(self.support_path, 'windows', 'WinDump.exe') if interface == 'any': args = [tcpdump, '-p', '-s', '0', '-w', self.pcap_file] else: args = [ tcpdump, '-p', '-i', interface, '-s', '0', '-w', self.pcap_file ] logging.debug(' '.join(args)) self.tcpdump = subprocess.Popen( args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) else: args = [ 'sudo', 'tcpdump', '-p', '-i', interface, '-s', '0', '-w', self.pcap_file ] logging.debug(' '.join(args)) self.tcpdump = subprocess.Popen(args) # Wait for the capture file to start growing end_time = monotonic() + 5 started = False while not started and monotonic() < end_time: if os.path.isfile(self.pcap_file): started = True time.sleep(0.1) # Start video capture if self.job['capture_display'] is not None and not self.job[ 'disable_video']: if task['navigated']: self.execute_js(SET_ORANGE) time.sleep(1) task['video_file'] = os.path.join( task['dir'], task['prefix']) + '_video.mp4' if platform.system() == 'Windows': from win32api import GetSystemMetrics #pylint: disable=import-error self.screen_width = GetSystemMetrics(0) self.screen_height = GetSystemMetrics(1) elif platform.system() == 'Darwin': try: from AppKit import NSScreen #pylint: disable=import-error self.screen_width = int( NSScreen.screens()[0].frame().size.width) self.screen_height = int( NSScreen.screens()[0].frame().size.height) except Exception: pass task['width'] = min(task['width'], self.screen_width) task['height'] = min(task['height'], self.screen_height) if platform.system() == 'Darwin': width = int( math.ceil(task['width'] * self.device_pixel_ratio)) height = int( math.ceil(task['height'] * self.device_pixel_ratio)) args = [ 'ffmpeg', '-f', 'avfoundation', '-i', str(self.job['capture_display']), '-r', str(self.job['fps']), '-filter:v', 'crop={0:d}:{1:d}:0:0'.format(width, height), '-codec:v', 'libx264rgb', '-crf', '0', '-preset', 'ultrafast', task['video_file'] ] else: grab = 'gdigrab' if platform.system( ) == 'Windows' else 'x11grab' args = [ 'ffmpeg', '-f', grab, '-video_size', '{0:d}x{1:d}'.format(task['width'], task['height']), '-framerate', str(self.job['fps']), '-draw_mouse', '0', '-i', str(self.job['capture_display']), '-codec:v', 'libx264rgb', '-crf', '0', '-preset', 'ultrafast', task['video_file'] ] if platform.system() in ['Linux', 'Darwin']: args.insert(0, 'nice') args.insert(1, '-n') args.insert(2, '10') logging.debug(' '.join(args)) try: if platform.system() == 'Windows': self.ffmpeg = subprocess.Popen( args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) else: self.ffmpeg = subprocess.Popen(args) # Wait up to 5 seconds for something to be captured end_time = monotonic() + 5 started = False initial_size = None while not started and monotonic() < end_time: if os.path.isfile(task['video_file']): video_size = os.path.getsize(task['video_file']) if initial_size == None: initial_size = video_size logging.debug("Video file size: %d", video_size) if video_size > initial_size or video_size > 10000: started = True if not started: time.sleep(0.1) self.video_capture_running = True except Exception: logging.exception('Error starting video capture') # start the background thread for monitoring CPU and bandwidth self.usage_queue = multiprocessing.JoinableQueue() self.thread = threading.Thread(target=self.background_thread) self.thread.daemon = True self.thread.start() self.start_cpu_throttling()
def get(self): from AppKit import NSScreen return [(int(screen.frame().size.width), int(screen.frame().size.height)) for screen in NSScreen.screens()]