def FindDimensions(this): Width = this.Width Height = this.Height if platform.system() == 'Linux': import subprocess Dimensions = subprocess.Popen( 'xrandr | grep "\*" | cut -d" " -f4', shell=True, stdout=subprocess.PIPE).communicate()[0].decode().split('\n')[ this.ScreenID - 1] Width, Height = Dimensions.split('x') elif platform.system() == 'Windows': from win32api import GetSystemMetrics Width = GetSystemMetrics(0) Height = GetSystemMetrics(1) elif platform.system() == 'Darwin': from AppKit import NSScreen Width = NSScreen.mainScreen().frame().size.width Height = NSScreen.mainScreen().frame().size.height this.Width = int(Width) this.Height = int(Height) this.Dimensions = (int(Width), int(Height))
def get_browser_bounds(): runningApp = NSWorkspace.sharedWorkspace().frontmostApplication() runningAppPid = runningApp.processIdentifier() windows = CGWindowListCopyWindowInfo( kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID) possibleWindows = [] for wnd in windows: if wnd['kCGWindowOwnerPID'] == runningAppPid: possibleWindows.append(wnd) fallback = False if len(possibleWindows) == 0: # fallback mode fallback = True elif len(possibleWindows) == 1: window = possibleWindows[0] else: fallback = True for wnd in possibleWindows: #if 'netflix' in wnd['kCGWindowName'].lower(): if int(wnd['kCGWindowLayer']) < 0: window = wnd fallback = False break if fallback: # return fallback return dict(Height=NSScreen.mainScreen().frame().size.height, Width=NSScreen.mainScreen().frame().size.width, X=0, Y=0) else: return window['kCGWindowBounds']
def __init__(self): super(SplshApp, self).__init__('Splsh') self.icon = 'img/icon.png' try: self.screen_width = int(NSScreen.mainScreen().frame().size.width) self.screen_height = int(NSScreen.mainScreen().frame().size.height) except: self.screen_width = 1024 self.screen_height = 768 self.menu = [ 'x'.join([str(self.screen_width), str(self.screen_height)]), None, rumps.MenuItem('Next', key='n'), None, rumps.MenuItem('Gray Mood'), rumps.MenuItem('Blur'), rumps.MenuItem('Clear Cache', key='c'), None, ] # Path to dir for downloaded images self.media_dir = 'media/' # Extra url parameters self.gray_mood = False self.blur = False
def __init__(self, top, right, bottom, left, height, width, offsetTop, offsetRight, offsetBottom, offsetLeft, step): self.lights = (top, right, bottom, left) self.area = (height, width) self.offset = (offsetTop, offsetRight, offsetBottom, offsetLeft) self.screenSizes = (NSScreen.mainScreen().frame().size.height, NSScreen.mainScreen().frame().size.width) self.step = step
def __init__(self, test): self.test = test self.width = NSScreen.mainScreen().frame().size.width self.height = NSScreen.mainScreen().frame().size.height self.captureDevice = cv2.VideoCapture(0) self.testImage = self.createTestImage() self.makeImgsDir() self.recordVideo()
def detect_screen_size(): if sys.platform == "darwin": scaling_factor = NSScreen.mainScreen().backingScaleFactor() return int(NSScreen.mainScreen().frame().size.width * scaling_factor), int(NSScreen.mainScreen().frame().size.height * scaling_factor), scaling_factor elif sys.platform == "win32": scaling_factor = 1.0 return int(GetSystemMetrics(0)), int(GetSystemMetrics(1)), scaling_factor else: raise OSError("Incompatible platform")
def run(self): self._logger.debug('MainAction::run') destination = os.path.realpath('wllpx.jpg') tempFilename = os.path.realpath('temp.jpg') media = self._instagramFeed.getNext() self._settingsController.set('CURRENT_MEDIA_ID', media.id) self._downloader.fromUrl(media.url, tempFilename) width, height = int(NSScreen.mainScreen().frame().size.width), int(NSScreen.mainScreen().frame().size.height) self._wallpaperGenerator.generate(width, height, tempFilename, destination) self._wallpaperController.setWallpaper(destination)
def getScreenDimensions(): """[Uses NSScreen to return current monitor dimensions] Returns: [tuple] -- [a tuple of two ints: screenWidth, screenHeight] """ screenWidth = int(NSScreen.mainScreen().frame().size.width) screenHeight = int(NSScreen.mainScreen().frame().size.height) # print('Screen Width:', screenWidth) # print('Screen Height:', screenHeight) return (screenWidth, screenHeight)
def reflow(self, window_manager = None, screen = NSScreen.mainScreen(), space_id = None): menubar_offset = 0 if self.ignore_menu else 22 windows = window_manager.get_managed_windows(screen, space_id) screen_frame = screen.frame() left = screen_frame[0][0] + self.border top = screen_frame[0][1] + self.border + menubar_offset right = screen_frame[1][0] - self.border bottom = screen_frame[1][1] - self.border - menubar_offset gutter_left = screen_frame[1][0] * self.ratio - self.gutter / 2 gutter_right = gutter_left + self.gutter slave_count = len(windows) - 1 logging.debug('Number of slave windows: %d.', slave_count) slave_height = ((bottom - top) - self.gutter * (slave_count - 1)) / slave_count logging.debug('Slave window height is %f.', slave_height) count = 0 offset = 0 for window in windows: if count == 0: window.frame = (left, top, gutter_left - left, bottom - top) else: window.position = (gutter_right, top + offset) window.size = (right - gutter_right, slave_height) offset += slave_height + self.gutter logging.debug('New window frame: %f, %f, %f, %f', window.position[0], window.position[1], window.size[0], window.size[1]) count += 1
def __init__(self, style='standard', zoomable=None, **kwds): # We ignore zoomable, since it's the same as resizable. self._style = style options = dict(_default_options_for_style[style]) for option in ['movable', 'closable', 'hidable', 'resizable']: if option in kwds: options[option] = kwds.pop(option) self._ns_style_mask = self._ns_window_style_mask(**options) if style == 'fullscreen': ns_rect = NSScreen.mainScreen().frame() else: ns_rect = NSRect(NSPoint(0, 0), NSSize(self._default_width, self._default_height)) ns_window = PyGUI_NSWindow.alloc() ns_window.initWithContentRect_styleMask_backing_defer_( ns_rect, self._ns_style_mask, AppKit.NSBackingStoreBuffered, True) ns_content = PyGUI_NS_ContentView.alloc() ns_content.initWithFrame_(NSRect(NSPoint(0, 0), NSSize(0, 0))) ns_content.pygui_component = self ns_window.setContentView_(ns_content) ns_window.setAcceptsMouseMovedEvents_(True) ns_window.setDelegate_(ns_window) ns_window.pygui_component = self self._ns_window = ns_window GWindow.__init__(self, style=style, closable=options['closable'], _ns_view=ns_window.contentView(), _ns_responder=ns_window, _ns_set_autoresizing_mask=False, **kwds)
def initialize_screen(screen_width=0, screen_height=0): if os.name == 'posix': from AppKit import NSScreen screen_width = NSScreen.mainScreen().frame().width screen_height = NSScreen.mainScreen().frame().height else: import ctypes pygame.display.init() if screen_width < 1 or screen_height < 1: user32 = ctypes.windll.user32 screen_width = user32.GetSystemMetrics(0) / 2 screen_height = user32.GetSystemMetrics(1) / 2 screen = pygame.display.set_mode([screen_width, screen_height], \ pygame.RESIZABLE) return [screen, screen_width, screen_height]
def get_desktop_size(): """ Get the current desktop resolution. No more than 2K. Return a tuple of pixels (width, height) """ from AppKit import NSScreen frame = NSScreen.mainScreen().frame() height = frame.size.height width = frame.size.width MAX_WIDTH = 2000 MAX_HEIGHT = 2000 if width > MAX_WIDTH or height > MAX_HEIGHT: if width > height: max = width ratio = max / MAX_WIDTH else: max = height ratio = max / MAX_HEIGHT width = width / ratio height = height / ratio return (int(width), int(height))
def get_desktop_size(): """ Get the current desktop resolution. No more than 2K. Return a tuple of pixels (width, height) """ from AppKit import NSScreen frame = NSScreen.mainScreen().frame() height = frame.size.height width = frame.size.width MAX_WIDTH = 2000 MAX_HEIGHT = 2000 if width > MAX_WIDTH or height > MAX_HEIGHT: if width > height: max = width ratio = max / MAX_WIDTH else: max = height ratio = max / MAX_HEIGHT width = width / ratio height = height / ratio return (int(width), int(height))
def check_files(files, output_path): height = NSScreen.mainScreen().frame().size.height with open(output_path, 'w') as out: for file in files: image_name, is_positive = check_image(file, height) template = "%s\t%s\n" out.write(template % (image_name, is_positive))
def __init__(self): #title of the box window self.title = 'Question Box' #box width self.width = 400 #box height self.height = 160 #box position in the screen default to be at the center self.left = (NSScreen.mainScreen().frame().size.width - self.width) // 2 self.top = (NSScreen.mainScreen().frame().size.height - self.height) // 2 #game status: quit or restart self.status = None #game type: the returned status when game ends self.types = None
def screen_from_point(point): screens = NSScreen.screens() for screen in screens: if NSPointInRect(point, screen.frame()): return screen return NSScreen.mainScreen()
def __init__(self, style = 'standard', zoomable = None, **kwds): # We ignore zoomable, since it's the same as resizable. self._style = style options = dict(_default_options_for_style[style]) for option in ['movable', 'closable', 'hidable', 'resizable']: if option in kwds: options[option] = kwds.pop(option) self._ns_style_mask = self._ns_window_style_mask(**options) if style == 'fullscreen': ns_rect = NSScreen.mainScreen().frame() else: ns_rect = NSRect(NSPoint(0, 0), NSSize(self._default_width, self._default_height)) ns_window = PyGUI_NSWindow.alloc() ns_window.initWithContentRect_styleMask_backing_defer_( ns_rect, self._ns_style_mask, AppKit.NSBackingStoreBuffered, True) ns_content = PyGUI_NS_ContentView.alloc() ns_content.initWithFrame_(NSRect(NSPoint(0, 0), NSSize(0, 0))) ns_content.pygui_component = self ns_window.setContentView_(ns_content) ns_window.setAcceptsMouseMovedEvents_(True) ns_window.setDelegate_(ns_window) ns_window.pygui_component = self self._ns_window = ns_window GWindow.__init__(self, style = style, closable = options['closable'], _ns_view = ns_window.contentView(), _ns_responder = ns_window, _ns_set_autoresizing_mask = False, **kwds)
def getScreenResolution(cls, index =-1): #------------------------------------------------------------------------------------------- if cls.isMac(): try: import AppKit from AppKit import NSScreen if index == -1: return int(NSScreen.mainScreen().frame().size.width), \ int(NSScreen.mainScreen().frame().size.height) i = 0 for screen in AppKit.NSScreen.screens(): if i != index: continue return screen.frame().size.width, screen.frame().size.height return None except Exception: pass result = cls._getOsxDisplayInfo() if result['code'] or not 'out' in result: return None if index < 0: index = 0 screenIndex = 0 for line in result['out'].split('\n'): line = line.strip().lower() if not line.startswith('resolution:'): continue if screenIndex != index: continue result = re.search(r'(?P<width>[0-9]{3,})[^0-9]+(?P<height>[0-9]{3,})', line) return int(result.group('width')), int(result.group('height')) return None #------------------------------------------------------------------------------------------- if cls.isWindows(): try: import ctypes except Exception: return None user32 = ctypes.windll.user32 return int(user32.GetSystemMetrics(0)), int(user32.GetSystemMetrics(1))
def isfullscreen(self): """return true if fullscreen""" if len(self.windows)==0: return False f=NSScreen.mainScreen().frame() m=([f.origin.x,f.origin.y,f.size.width,f.size.height]) w=self.windows[0].bounds return ([w[0],w[2],w[3]])==([m[0],m[2],m[3]])
def main_monitor_resolution(): """Get the main screen resolution. Any secondary screens will be ignored. Returns: Tuple of the width and height of the main screen. """ size = NSScreen.mainScreen().frame().size return (size.width, size.height)
def _stagger(self): key_win = application()._ns_key_window if key_win: (x, y), (w, h) = key_win._ns_window.frame() p = self._ns_window.cascadeTopLeftFromPoint_(NSPoint(x, y + h)) self._ns_window.setFrameTopLeftPoint_(p) else: (x, y), (w, h) = NSScreen.mainScreen().visibleFrame() ns_vis_topleft = NSPoint(x, y + h) self._ns_window.setFrameTopLeftPoint_(ns_vis_topleft)
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 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 _stagger(self): key_win = application()._ns_key_window if key_win: (x, y), (w, h) = key_win._ns_window.frame() p = self._ns_window.cascadeTopLeftFromPoint_(NSPoint(x, y + h)) self._ns_window.setFrameTopLeftPoint_(p) else: (x, y), (w, h) = NSScreen.mainScreen().visibleFrame() ns_vis_topleft = NSPoint(x, y + h) self._ns_window.setFrameTopLeftPoint_(ns_vis_topleft)
def reflow(self, window_manager = None, screen = NSScreen.mainScreen(), space_id = None): menubar_offset = 0 if self.ignore_menu else 22 windows = window_manager.get_managed_windows(screen, space_id) screen_frame = screen.frame() for window in windows: left = screen_frame[0][0] + self.border top = screen_frame[0][1] + self.border + menubar_offset right = screen_frame[1][0] - self.border bottom = screen_frame[1][1] - self.border - menubar_offset window.frame = (left, top, right - left, bottom - top)
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 get_screen_resolution(): """ Get the screen resolution """ if is_macosx(): from AppKit import NSScreen screen_size = NSScreen.mainScreen().frame().size return screen_size.width, screen_size.height elif is_win(): from win32api import GetSystemMetrics return GetSystemMetrics(0), GetSystemMetrics(1) elif is_linux(): from Xlib.display import Display resolution = Display().screen().root.get_geometry() return resolution.width, resolution.height else: return 1024, 768
def reflow(self, window_manager = None, screen = NSScreen.mainScreen(), space_id = None): menubar_offset = 0 if self.ignore_menu else 22 windows = window_manager.get_managed_windows(screen, space_id) screen_frame = screen.frame() left = screen_frame[0][0] + self.border top = screen_frame[0][1] + self.border + menubar_offset right = screen_frame[1][0] - self.border bottom = screen_frame[1][1] - self.border - menubar_offset gutter_left = (screen_frame[1][0] - self.gutter) / 2 gutter_right = gutter_left + self.gutter count = 0 for window in windows: if count % 2 == 0: window.frame = (left, top, gutter_left - left, bottom - top) else: window.frame = (gutter_right, top, right - gutter_right, bottom - top) count += 1
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 display(self): if self._panel is None: screen_size = NSScreen.mainScreen().frame().size center_point = screen_size.width / 2, screen_size.height / 2 self.rect = ((center_point[0] - 100, center_point[1] - 100), (400, 200)) self._panel = NSPanel.alloc() # self._panel.init() self._panel.initWithContentRect_styleMask_backing_defer_( self.rect, NSBorderlessWindowMask, self.buf, self.flag) self._panel.setTitle_("HelloWorld") self._panel.setFloatingPanel_(True) self._panel.setWorksWhenModal_(True) self._panel.setHidesOnDeactivate_(True) self._web_view = WKWebView.new() self._web_view.initWithFrame_configuration_( NSZeroRect, WKWebViewConfiguration.new()) self._web_view.setFrameSize_( self._panel.contentView().frame().size) self._web_view.loadHTMLString_baseURL_( '<html><body><p>{}</p></body></html>'.format(self.result), None) self._panel.contentView().addSubview_(self._web_view) else: self._panel.setHidesOnDeactivate_(False) # self._panel.update() self.timer = Timer(2, self.hide) self.timer.start() self._panel.setFrame_display_(self.rect, True) self._panel.update() self._panel.orderFrontRegardless()
# starting over...trying to control automation for recording. deleting rtimidi stuff import pygame import pygame.midi import pygame.mouse import pygame.font import os from AppKit import NSScreen import pyautogui #### ref #### # key ref: https://www.pygame.org/docs/ref/key.html winw = NSScreen.mainScreen().frame().size.width winh = NSScreen.mainScreen().frame().size.height mx = pyautogui.position()[0] my = pyautogui.position()[1] pygame.init() pygame.midi.init() pygame.font.init() dim = (200, int(winh)) # dimensions of window startpos = int(winw - dim[0]), 0 os.environ['SDL_VIDEO_WINDOW_POS'] = str(startpos[0]) + "," + str(startpos[1]) #### set up text #### font = pygame.font.SysFont('Courier', 24, bold=False) scrolldir_title = font.render('scroll:', True, (0, 0, 0)) scrollspd_title = font.render('speed:', True, (0, 0, 0))
#!/usr/bin/python # Prints current screen resolution. # See: https://stackoverflow.com/q/1281397/55075 from AppKit import NSScreen print("Current screen resolution: %dx%d" % (NSScreen.mainScreen().frame().size.width, NSScreen.mainScreen().frame().size.height))
def _screen_size(cls): from AppKit import NSScreen return NSScreen.mainScreen().frame().size
def show_backdrop(comm_queue, image_path): from AppKit import NSWindow, NSWindowCollectionBehaviorCanJoinAllSpaces, NSWindowCollectionBehaviorStationary, \ NSWindowCollectionBehaviorIgnoresCycle, NSBorderlessWindowMask, NSBackingStoreBuffered, NSColor, \ NSApplication, NSScreen, NSView, NSImage, NSImageView, NSZeroRect, NSCompositeCopy, NSApp, \ NSTimer, NSObject, NSEvent, NSApplicationDefined, NSMakePoint, NSBundle from Quartz import kCGDesktopWindowLevel from ctypes import CDLL, Structure, POINTER, c_uint32, byref from ctypes.util import find_library class ProcessSerialNumber(Structure): _fields_ = [('highLongOfPSN', c_uint32), ('lowLongOfPSN', c_uint32)] kCurrentProcess = 2 kProcessTransformToUIElementAppication = 4 ApplicationServices = CDLL(find_library('ApplicationServices')) TransformProcessType = ApplicationServices.TransformProcessType TransformProcessType.argtypes = [POINTER(ProcessSerialNumber), c_uint32] class MainController(NSObject): timer = None def kickRunLoop(self): event = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, \ NSMakePoint(0,0), 0, 0.0, 0, None, 0, 0, 0) NSApp.postEvent_atStart_(event, True) def checkProcess_(self, timer): if not comm_queue.empty(): # We Get Signal, Take Off Every Zig - er, time to shut down this forked process # Clear the queue while not comm_queue.empty(): ignore = comm_queue.get_nowait() NSApp.stop_(None) # After you stop the runloop, the app has to receive another event to determine the runloop stopped ... self.kickRunLoop() def run(self): # You could adjust the 1.0 here to how ever many seconds you wanted to wait between checks to terminate self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, self.checkProcess_, None, True) NSApp.run() class FullScreenWindow(NSWindow): def canBecomeKeyWindow(self): return False def canBecomeMainWindow(self): return False class LockView(NSView): def getTopOffset(self, height): return (self.bounds().size.height / 2) - height / 2 def getLeftOffset(self, width): return (self.bounds().size.width / 2) - width / 2 def drawRect_(self, rect): image = NSImage.alloc().initWithContentsOfFile_(image_path) rep = image.representations()[0] bg_width = rep.pixelsWide() bg_height = rep.pixelsHigh() image.drawInRect_fromRect_operation_fraction_(((self.getLeftOffset(bg_width), self.getTopOffset(bg_height)), (bg_width, bg_height)), NSZeroRect, NSCompositeCopy, 1.0) imageView = NSImageView.alloc().init() imageView.setImage_(image) self.addSubview_(imageView) bundle = NSBundle.mainBundle() info = bundle.localizedInfoDictionary() or bundle.infoDictionary() # Did you know you can override parts of infoDictionary (Info.plist, after loading) even though Apple says it's read-only? # This is enough to make an app faceless / without a Dock icon info['LSUIElement'] = '1' # Initialize our shared application instance app = NSApplication.sharedApplication() # ... This isn't really necessary, but it's nice to ensure that the application truly is UIElement type psn = ProcessSerialNumber(0, kCurrentProcess) ApplicationServices.TransformProcessType(psn, kProcessTransformToUIElementAppication) screen = NSScreen.mainScreen() myWindow = FullScreenWindow.alloc().initWithContentRect_styleMask_backing_defer_(screen.frame(), NSBorderlessWindowMask, NSBackingStoreBuffered, True) myView = LockView.alloc().initWithFrame_(screen.frame()) myWindow.setContentView_(myView) myWindow.setLevel_(kCGDesktopWindowLevel) myWindow.setCollectionBehavior_(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle) myWindow.setBackgroundColor_(NSColor.blackColor()) myWindow.makeKeyAndOrderFront_(myWindow) myWindow.display() controller = MainController.alloc().init() controller.run()
def real_y(cls, sc): main_frame = NSScreen.mainScreen().frame() sc_frame = sc.frame() return main_frame.size.height - (sc_frame.size.height+sc_frame.origin.y)
def __init__(self, posSize, title="", minSize=None, maxSize=None, textured=False, autosaveName=None, closable=True, miniaturizable=True, initiallyVisible=True, fullScreenMode=None, titleVisible=True, fullSizeContentView=False, screen=None): mask = self.nsWindowStyleMask if closable: mask = mask | NSClosableWindowMask if miniaturizable: mask = mask | NSMiniaturizableWindowMask if minSize or maxSize: mask = mask | NSResizableWindowMask if textured: mask = mask | NSTexturedBackgroundWindowMask if fullSizeContentView and osVersionCurrent >= osVersion10_10: mask = mask | NSFullSizeContentViewWindowMask # start the window ## too magical? if len(posSize) == 2: l = t = 100 w, h = posSize cascade = True else: l, t, w, h = posSize cascade = False if screen is None: screen = NSScreen.mainScreen() frame = _calcFrame(screen.visibleFrame(), ((l, t), (w, h))) self._window = self.nsWindowClass.alloc().initWithContentRect_styleMask_backing_defer_screen_( frame, mask, NSBackingStoreBuffered, False, screen) if autosaveName is not None: # This also sets the window frame if it was previously stored. # Make sure we do this before cascading. self._window.setFrameAutosaveName_(autosaveName) if cascade: self._cascade() if minSize is not None: self._window.setMinSize_(minSize) if maxSize is not None: self._window.setMaxSize_(maxSize) self._window.setTitle_(title) self._window.setLevel_(self.nsWindowLevel) self._window.setReleasedWhenClosed_(False) self._window.setDelegate_(self) self._bindings = {} self._initiallyVisible = initiallyVisible # full screen mode if osVersionCurrent >= osVersion10_7: if fullScreenMode is None: pass elif fullScreenMode == "primary": self._window.setCollectionBehavior_(NSWindowCollectionBehaviorFullScreenPrimary) elif fullScreenMode == "auxiliary": self._window.setCollectionBehavior_(NSWindowCollectionBehaviorFullScreenAuxiliary) # titlebar visibility if osVersionCurrent >= osVersion10_10: if not titleVisible: self._window.setTitleVisibility_(NSWindowTitleHidden) else: self._window.setTitleVisibility_(NSWindowTitleVisible) # full size content view if fullSizeContentView and osVersionCurrent >= osVersion10_10: self._window.setTitlebarAppearsTransparent_(True)
def main(): parser = argparse.ArgumentParser(description="Utility to print, set, or " + "check the path to image being used as " + "the desktop background image. By " + "default, prints the path to the " + "current desktop background image.") parser.add_argument( "-v", "--verbose", action="store_true", help="print verbose debugging information", default=False, ) group = parser.add_mutually_exclusive_group() group.add_argument( "-s", "--set-background-image", dest="newBackgroundImagePath", required=False, help="path to the new background image to set. A zero " + "exit code indicates no errors occurred.", default=None, ) group.add_argument( "-c", "--check-background-image", dest="checkBackgroundImagePath", required=False, help="check if the provided background image path " + "matches the provided path. A zero exit code " + "indicates the paths match.", default=None, ) args = parser.parse_args() # Using logging for verbose output if args.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.CRITICAL) logger = logging.getLogger("desktopImage") # Print what we're going to do if args.checkBackgroundImagePath is not None: logger.debug("checking provided desktop image %s matches current " "image" % args.checkBackgroundImagePath) elif args.newBackgroundImagePath is not None: logger.debug("setting image to %s " % args.newBackgroundImagePath) else: logger.debug("retrieving desktop image path") focussedScreen = NSScreen.mainScreen() if not focussedScreen: raise RuntimeError("mainScreen error") ws = NSWorkspace.sharedWorkspace() if not ws: raise RuntimeError("sharedWorkspace error") # If we're just checking the image path, check it and then return. # A successful exit code (0) indicates the paths match. if args.checkBackgroundImagePath is not None: # Get existing desktop image path and resolve it existingImageURL = getCurrentDesktopImageURL(focussedScreen, ws, logger) existingImagePath = existingImageURL.path() existingImagePathReal = os.path.realpath(existingImagePath) logger.debug("existing desktop image: %s" % existingImagePath) logger.debug("existing desktop image realpath: %s" % existingImagePath) # Resolve the path we're going to check checkImagePathReal = os.path.realpath(args.checkBackgroundImagePath) logger.debug("check desktop image: %s" % args.checkBackgroundImagePath) logger.debug("check desktop image realpath: %s" % checkImagePathReal) if existingImagePathReal == checkImagePathReal: print("desktop image path matches provided path") return True print("desktop image path does NOT match provided path") return False # Log the current desktop image if args.verbose: existingImageURL = getCurrentDesktopImageURL(focussedScreen, ws, logger) logger.debug("existing desktop image: %s" % existingImageURL.path()) # Set the desktop image if args.newBackgroundImagePath is not None: newImagePath = args.newBackgroundImagePath if not os.path.exists(newImagePath): logger.critical("%s does not exist" % newImagePath) return False if not os.access(newImagePath, os.R_OK): logger.critical("%s is not readable" % newImagePath) return False logger.debug("new desktop image to set: %s" % newImagePath) newImageURL = NSURL.fileURLWithPath_(newImagePath) logger.debug("new desktop image URL to set: %s" % newImageURL) status = False (status, error) = ws.setDesktopImageURL_forScreen_options_error_( newImageURL, focussedScreen, None, None) if not status: raise RuntimeError("setDesktopImageURL error") # Print the current desktop image imageURL = getCurrentDesktopImageURL(focussedScreen, ws, logger) imagePath = imageURL.path() imagePathReal = os.path.realpath(imagePath) logger.debug("updated desktop image URL: %s" % imageURL) logger.debug("updated desktop image path: %s" % imagePath) logger.debug("updated desktop image path (resolved): %s" % imagePathReal) print(imagePathReal) return True
def _screen_size(cls): from AppKit import NSScreen return NSScreen.mainScreen().frame().size
raise exc_type, exc_value, exc_tb def create_ns_application(): ns_app = _PyGui_NSApplication.sharedApplication() ns_app.setDelegate_(ns_app) Globals.ns_application = ns_app def dispatch_to_app(ns_app, *args): app = ns_app.pygui_app if app: app.dispatch(*args) Globals.ns_screen_height = NSScreen.mainScreen().frame().size.height create_ns_application() #------------------------------------------------------------------------------ # Disable this for now, since MachSignals.signal segfaults. :-( # #def _install_sigint_handler(): # print "_install_sigint_handler" ### # from Foundation import NSRunLoop # run_loop = NSRunLoop.currentRunLoop() # if not run_loop: # print "...No current run loop" ### # sys.exit(1) ### # MachSignals.signal(signal.SIGINT, _sigint_handler)
def screen_resolution(): s = NSScreen.mainScreen().frame() return {'width': s.size.width, 'height':s.size.height}
def raise_pending_exception(): exc_type, exc_value, exc_tb = Globals.pending_exception Globals.pending_exception = None raise exc_type, exc_value, exc_tb def create_ns_application(): ns_app = _PyGui_NSApplication.sharedApplication() ns_app.setDelegate_(ns_app) Globals.ns_application = ns_app def dispatch_to_app(ns_app, *args): app = ns_app.pygui_app if app: app.dispatch(*args) Globals.ns_screen_height = NSScreen.mainScreen().frame().size.height create_ns_application() #------------------------------------------------------------------------------ # Disable this for now, since MachSignals.signal segfaults. :-( # #def _install_sigint_handler(): # print "_install_sigint_handler" ### # from Foundation import NSRunLoop # run_loop = NSRunLoop.currentRunLoop() # if not run_loop: # print "...No current run loop" ### # sys.exit(1) ### # MachSignals.signal(signal.SIGINT, _sigint_handler)
def _osx_frame(self): '''What OSX reports as the screen frame.''' from AppKit import NSScreen return NSScreen.mainScreen().frame()
def screen_size(self): return NSScreen.mainScreen().frame().size.width, NSScreen.mainScreen().frame().size.height
def __init__(self): super().__init__() loadPrcFileData('', 'window-title ursina') loadPrcFileData('', 'notify-level-util error') loadPrcFileData('', 'textures-auto-power-2 #t') loadPrcFileData('', 'load-file-type p3assimp') # loadPrcFileData('', 'allow-portal-cull #t') # loadPrcFileData("", "framebuffer-multisample 1") # loadPrcFileData('', 'multisamples 2') # loadPrcFileData('', 'textures-power-2 none') # loadPrcFileData('', 'threading-model Cull/Draw') loadPrcFileData('', 'coordinate-system y-up-left') # fallback to one of these if opengl is not supported loadPrcFileData('', 'aux-display pandadx9') loadPrcFileData('', 'aux-display pandadx8') loadPrcFileData('', 'aux-display tinydisplay') self.vsync = True # can't be set during play self.show_ursina_splash = False self.title = application.asset_folder.name self.borderless = True # self.icon = 'textures/ursina.ico' os_name = platform.system() try: if os_name == 'Windows': # windows import ctypes user32 = ctypes.windll.user32 user32.SetProcessDPIAware() self.screen_resolution = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)) elif os_name == 'Linux': import Xlib import Xlib.display resolution = Xlib.display.Display().screen().root.get_geometry( ) self.screen_resolution = Vec2(resolution.width, resolution.height) elif os_name == 'Darwin': # mac from AppKit import NSScreen size = NSScreen.mainScreen().frame().size self.screen_resolution = [size.width, size.height] except: from screeninfo import get_monitors self.screen_resolution = [ get_monitors()[0].width, get_monitors()[0].height ] self.fullscreen_size = Vec2(*self.screen_resolution) self.windowed_size = self.fullscreen_size / 1.25 self.windowed_position = None # gets set when entering fullscreen so position will be correct when going back to windowed mode self.forced_aspect_ratio = None # example: window.forced_aspect_ratio = 16/9 self.size = self.windowed_size self.always_on_top = False self.top = Vec2(0, .5) self.bottom = Vec2(0, -.5) self.center = Vec2(0, 0)
def _osx_available(self): '''What OSX reports as available frame for applications.''' from AppKit import NSScreen return NSScreen.mainScreen().visibleFrame()
def __init__(self): self.maxX = int(NSScreen.mainScreen().frame().size.width) self.maxY = int(NSScreen.mainScreen().frame().size.height) self.moveBy(0,0)
def main(): # mouse object mouse = Controller() # screen size screenWidth, screenHeight = (NSScreen.mainScreen().frame().size.width, NSScreen.mainScreen().frame().size.height) # open camera cam = cv2.VideoCapture(0) # gesture pinching = False while cam.isOpened(): ret, img = cam.read() img = cv2.resize(img,(340,220)) img = cv2.flip(img, flipCode=1) # convert BGR to HSV imgHSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) # create the Mask mask = cv2.inRange(imgHSV,lowerBound,upperBound) # masks maskOpen = cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernelOpen) maskClose = cv2.morphologyEx(maskOpen,cv2.MORPH_CLOSE,kernelClose) # use masks to find finger(s) maskFinal = maskClose matches = cv2.findContours(maskFinal.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[1] if len(matches) == 2: if pinching: pinching = False mouse.release(Button.left) # blue rectangles on each finger x1,y1,w1,h1=cv2.boundingRect(matches[0]) x2,y2,w2,h2=cv2.boundingRect(matches[1]) cv2.rectangle(img,(x1,y1),(x1+w1,y1+h1),blue,2) cv2.rectangle(img,(x2,y2),(x2+w2,y2+h2),blue,2) # center of rectangles cx1, cy1 = coordinates(x1, y1, w1, h1) cx2, cy2 = coordinates(x2, y2, w2, h2) # midpoint between 2 fingers cx, cy = midpoint(cx1, cy1, cx2, cy2) # line connecting 2 fingers cv2.line(img, (cx1,cy1), (cx2,cy2), blue, 2) # circle at midpoint cv2.circle(img, (cx,cy), 2, red, 2) # move mouse based on circle coordinate moveMouse(cx, cy, screenWidth, screenHeight, camx, camy, mouse) elif(len(matches)==1): x,y,w,h=cv2.boundingRect(matches[0]) if not pinching: pinching = True mouse.press(Button.left) # blue rectangle on finger cv2.rectangle(img,(x,y),(x+w,y+h),blue,2) # center of rectangle cx, cy = coordinates(x,y,w,h) # circle around center cv2.circle(img,(cx,cy),int((w+h)/4),red,2) # move mouse based on circle coordinate moveMouse(cx, cy, screenWidth, screenHeight, camx, camy, mouse) # display camera preview cv2.imshow("Gesture Recognition Preview", img) # stop program when q is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break cam.release() cv2.destroyAllWindows()
from Foundation import NSColor, NSUserDefaults, NSMakeRange from AppKit import NSScreen # # # # # # # # # debugMode = False # Glyphs.clearLog() # # # # # # # # # try: reload(Customizables) except: pass excludedSubCategories = Customizables.excludedSubCategories screenHeight = NSScreen.mainScreen().frame().size.height ########################################################################## ########################################################################## ########################################################################## ########################################################################## class KernKraft(object): version = "1.8" # excludeCategories = [] def __init__(self, Glyphs, thisFont, mID):
# without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import os.path import Foundation from AppKit import NSScreen try: width, height = (int(NSScreen.mainScreen().frame().size.width), int(NSScreen.mainScreen().frame().size.height)) extension_attribute = u"{0:g}\u00D7{1:g}".format(width, height) print(extension_attribute) except: extension_attribute = "Unknown" extension_attribute_result = u"<result>{0}</result>".format(extension_attribute) print(extension_attribute_result)
def get_desktop(): size = NSScreen.mainScreen().frame().size return 0, 0, size.width, size.height
def fadeOut(self): global dismissing if dismissing: return dismissing = True NSAnimationContext.beginGrouping() NSAnimationContext.currentContext().setTimingFunction_(CAMediaTimingFunction.functionWithName_(kCAMediaTimingFunctionEaseInEaseOut)) NSAnimationContext.currentContext().setDuration_(0.2) self.animator().setAlphaValue_(0.0) NSAnimationContext.endGrouping() NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(0.21, app, "terminate:", None, False) app = NSApplication.sharedApplication() app.setActivationPolicy_(NSApplicationActivationPolicyAccessory) frame = NSScreen.mainScreen().frame() window = Window.alloc().initWithContentRect_styleMask_backing_defer_(frame, NSBorderlessWindowMask, NSBackingStoreBuffered, False) window.setLevel_(NSMainMenuWindowLevel+2) text = sys.argv[1].decode('utf-8') def attributed_text_at_size(text, size): paragraph_style = NSMutableParagraphStyle.new() paragraph_style.setAlignment_(NSCenterTextAlignment) attrs = { NSParagraphStyleAttributeName: paragraph_style, NSFontAttributeName: NSFont.boldSystemFontOfSize_(size), NSForegroundColorAttributeName: NSColor.whiteColor() } return NSAttributedString.alloc().initWithString_attributes_(text, attrs)
import pyglet from AppKit import NSScreen from pyglet.gl import * HEIGHT = int(NSScreen.mainScreen().frame().size.height) WIDTH = int(NSScreen.mainScreen().frame().size.width) matrix = [[0 for i in range(HEIGHT // 10)] for j in range(WIDTH // 10)] def fits(x, y): l = len(matrix), len(matrix[0]) return x >= 0 and y >= 0 and x < l[1] and y < l[0] def neighborhood(x, y): n = x, y - 1 ne = x + 1, y - 1 e = x + 1, y se = x + 1, y + 1 s = x, y + 1 sw = x - 1, y + 1 w = x, y - 1 nw = x - 1, y - 1 rose = n, ne, e, se, s, sw, w, nw res = [] for d in rose: if fits(*d): res.append(matrix[d[1]][d[0]]) return res
# PIECE = 4 colored squares that form a shape ## REQUIRED FIXES ## 1) if a piece is squeezed into a spot at the very last possible moment, it will move down import random, pygame, sys from pygame.locals import * import numpy as np import cv2 import imutils import time from collections import deque from datetime import datetime # ---- for mac users ---- from AppKit import NSScreen height = int(NSScreen.mainScreen().frame().size.height) width = int(NSScreen.mainScreen().frame().size.width) # --- for windows users ----- # from win32api import GetSystemMetrics # height = GetSystemMetrics(1) # width = GetSystemMetrics(0) cap = cv2.VideoCapture(0) greenLower = (29, 86, 6) greenUpper = (64, 255, 255) pts = deque(maxlen=12) direction = "ND" height = 320 width = 600 height = int(NSScreen.mainScreen().frame().size.height) width = int(NSScreen.mainScreen().frame().size.width)
#!/Users/ryancampbell/python/.venv/bitbar/bin/python3 from os import system import sys from AppKit import NSScreen toggleRegularRes = '/usr/local/bin/displayplacer "id:C487FFEE-9620-8F3A-8BC2-A1A07CAF4201 res:2560x1440 hz:60 color_depth:8 scaling:on origin:(0,0) degree:0"' toggleGameRes = '/usr/local/bin/displayplacer "id:C487FFEE-9620-8F3A-8BC2-A1A07CAF4201 res:1920x1080 hz:60 color_depth:8 scaling:on origin:(0,0) degree:0"' screenHeight = NSScreen.mainScreen().frame().size.height def toggle(): if screenHeight == 1440: system(toggleGameRes) else: system(toggleRegularRes) if len(sys.argv) == 1: print('{} | refresh=true terminal=false bash="/Users/ryancampbell/python/.venv/bitbar/bin/python" param1="/Users/ryancampbell/BitBar/resToggle.py" param2=toggle'.format(int(screenHeight))) else: toggle() ''' if len(sys.argv) == 1: print('{}x{} | refresh=true'.format(int(screenWidth), int(screenHeight))) print('---') print('2560 | terminal=false bash="/usr/local/bin/python3" param1="/Users/ryancampbell/BitBar/resToggle.py" param2=1440') print('1080 | terminal=false bash="/usr/local/bin/python3" param1="/Users/ryancampbell/BitBar/resToggle.py" param2=1080') elif sys.argv[1] == '1440': os.system(toggleRegularRes) elif sys.argv[1] == '1080':
def get(): from AppKit import NSScreen frame = NSScreen.mainScreen().frame() return (int(frame.size.width), int(frame.size.height))