Example #1
0
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']
Example #2
0
    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
Example #3
0
    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))
Example #4
0
def screen_from_point(point):
    screens = NSScreen.screens()
    for screen in screens:
        if NSPointInRect(point, screen.frame()):
            return screen

    return NSScreen.mainScreen()
Example #5
0
 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
Example #6
0
 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()
Example #7
0
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
Example #8
0
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")
Example #9
0
File: gui.py Project: ljmljz/xpra
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
Example #10
0
 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)
Example #11
0
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
Example #12
0
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)
Example #13
0
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
Example #14
0
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
Example #15
0
 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
Example #16
0
    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')
Example #17
0
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]
Example #18
0
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)
Example #19
0
 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)
Example #20
0
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
Example #21
0
    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()
Example #22
0
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
Example #23
0
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))
Example #24
0
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 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)
Example #26
0
    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
Example #27
0
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
Example #28
0
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 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)
Example #30
0
    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()
Example #31
0
 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 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))
Example #33
0
    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))
Example #34
0
    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 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]])
Example #36
0
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)
Example #37
0
	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)
Example #38
0
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)
Example #39
0
 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)
Example #40
0
 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 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)
Example #42
0
    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)
Example #43
0
    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")
Example #44
0
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 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
Example #47
0
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),
        )
Example #48
0
File: gui.py Project: dochench/xpra
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
Example #49
0
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
Example #50
0
 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
Example #51
0
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")
Example #52
0
    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
Example #53
0
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):
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)
Example #55
0
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 "\
Example #56
0
 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)
Example #57
0
 def _screen_size(cls):
     from AppKit import NSScreen
     return NSScreen.mainScreen().frame().size
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)