def asleep_mac(): from Quartz import CGMainDisplayID # A hackish way to create a static local variable in Python if not hasattr(asleep_mac, "once"): asleep_mac.once = False # If we're on a Mac, use Quartz to read the current Display ID, and # store it. This only works if the user has launched the script # while logged into his account on the GUI. asleep_mac.display_id = CGMainDisplayID() try: # The pmset program can tell us if the display is on, off, or asleep output = subprocess.check_output(['pmset','-g','powerstate','AppleDisplay']) m = re.search('^AppleDisplay.*USEABLE', output, re.MULTILINE) if not m: # Display is turned off or asleep return True # If the Display ID has changed, then we've fast-switched to another # user, and so it's the same thing as being asleep. return asleep_mac.display_id != CGMainDisplayID() except Exception as e: if not asleep_mac.once: print "Warning: pmset not installed and/or broken" # Display the warning only once asleep_mac.once = True return False
def display_size(): if platform_is_osx(): from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID mainMonitor = CGDisplayBounds(CGMainDisplayID()) return int(mainMonitor.size.width), int(mainMonitor.size.height) if platform_is_win(): from win32api import GetSystemMetrics return int(GetSystemMetrics(0)), int(GetSystemMetrics(1)) if platform_is_linux(): # http://www.cyberciti.biz/faq/how-do-i-find-out-screen-resolution-of-my-linux-desktop/ # xdpyinfo | grep 'dimensions:' screen_width, screen_height = 0, 0 xdpyinfo = EasyProcess("xdpyinfo") xdpyinfo.enable_stdout_log = False if xdpyinfo.call().return_code != 0: raise ValueError("xdpyinfo error: %s" % xdpyinfo) for x in xdpyinfo.stdout.splitlines(): if "dimensions:" in x: screen_width, screen_height = map(int, x.strip().split()[1].split("x")) return screen_width, screen_height
def main(): controller = Leap.Controller() controller.enable_gesture(Leap.Gesture.TYPE_SCREEN_TAP) mainMonitor = CGDisplayBounds(CGMainDisplayID()) # err, ids, count = CGGetOnlineDisplayList(10,None,None) # WIDTH = 0 # HEIGHT = 0 # for id in ids: # monitor = CGDisplayBounds(id) # WIDTH += monitor.size.width # HEIGHT += monitor.size.height FPS = 50 FARLEFT = -300 FARRIGHT = 300 TOP = 500 BOTTOM = 100 BACKGROUND = -25 SCREENWIDTH = mainMonitor.size.width SCREENHEIGHT = mainMonitor.size.height last_time = time.time() touched = False while True: new_time = time.time() sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0 if sleep_time > 0: time.sleep(sleep_time) last_time = new_time frame = controller.frame() if not frame.hands.is_empty: hand = frame.hands[0] fingers = hand.fingers if not fingers.is_empty: num_fingers = 0 avg_pos = Leap.Vector() for finger in fingers: num_fingers += 1 avg_pos += finger.tip_position avg_pos /= len(fingers) posx = (SCREENWIDTH) / (FARRIGHT - FARLEFT) * (avg_pos[0] - FARLEFT) posy = (SCREENHEIGHT) / (BOTTOM - TOP) * (avg_pos[1] - TOP) # Limit to screen posx = 0 if posx < 0 else posx posx = SCREENWIDTH if posx > SCREENWIDTH else posx posy = 0 if posy < 0 else posy posy = SCREENHEIGHT if posy > SCREENHEIGHT else posy if num_fingers == 1: mousemove(posx, posy) if avg_pos[2] < BACKGROUND: if touched == False: mouseclick(posx, posy) touched = True else: touched = False
def init_session(self): self.captureSession = AVCaptureSession.alloc().init() self.captureSession.beginConfiguration() self.captureSession.setSessionPreset_(AVCaptureSessionPresetHigh) # add screen input display = CGMainDisplayID() captureScreenInput = AVCaptureScreenInput.alloc().initWithDisplayID_( display) self.captureSession.addInput_(captureScreenInput) self.movieOutput = AVCaptureMovieFileOutput.alloc().init() self.captureSession.addOutput_(self.movieOutput) self.captureSession.commitConfiguration()
def __init__(self): self.session = AVFoundation.AVCaptureSession.new() self.session.setSessionPreset_(AVFoundation.AVCaptureSessionPresetHigh) self.screen_input = AVFoundation.AVCaptureScreenInput.new().initWithDisplayID_( CGMainDisplayID() ) self.screen_input.setCapturesMouseClicks_(True) self.screen_input.setCapturesCursor_(True) if self.session.canAddInput_: self.session.addInput_(self.screen_input) self.movie_file_output = AVFoundation.AVCaptureMovieFileOutput.new() if self.session.canAddOutput_: self.session.addOutput_(self.movie_file_output)
def display_size(): if sys.platform == "darwin": from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID mainMonitor = CGDisplayBounds(CGMainDisplayID()) return (mainMonitor.size.width, mainMonitor.size.height) # http://www.cyberciti.biz/faq/how-do-i-find-out-screen-resolution-of-my-linux-desktop/ # xdpyinfo | grep 'dimensions:' screen_width, screen_height = None, None xdpyinfo = EasyProcess("xdpyinfo") xdpyinfo.enable_stdout_log = False for x in xdpyinfo.call().stdout.splitlines(): if "dimensions:" in x: screen_width, screen_height = map(int, x.strip().split()[1].split("x")) return screen_width, screen_height
def main(): controller = Leap.Controller() controller.enable_gesture(Leap.Gesture.TYPE_SCREEN_TAP) mainMonitor = CGDisplayBounds(CGMainDisplayID()) # err, ids, count = CGGetOnlineDisplayList(10,None,None) # WIDTH = 0 # HEIGHT = 0 # for id in ids: # monitor = CGDisplayBounds(id) # WIDTH += monitor.size.width # HEIGHT += monitor.size.height FPS = 50 FARLEFT = -300 FARRIGHT = 300 TOP = 500 BOTTOM = 100 BACKGROUND = -25 SCREENWIDTH = mainMonitor.size.width SCREENHEIGHT = mainMonitor.size.height last_time = time.time() touched = False while True: new_time = time.time() sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0 if sleep_time > 0: time.sleep(sleep_time) last_time = new_time frame = controller.frame() finger = frame.fingers.frontmost stabilizedPosition = finger.stabilized_tip_position interactionBox = frame.interaction_box normalizedPosition = interactionBox.normalize_point(stabilizedPosition) x = normalizedPosition.x * SCREENWIDTH y = SCREENHEIGHT - normalizedPosition.y * SCREENHEIGHT mousemove(x, y)
def get_device_active_displays(count=3): error, active_displays, number_of_active_displays = CGGetActiveDisplayList( count, None, None) if error: print( "There was a problem getting the active display list.\nError Message:", error, file=sys.stderr) sys.exit(-1) display_data = {} main_display_id = CGMainDisplayID() for count, display_id in enumerate(active_displays): if display_id == main_display_id: display_data["main"] = display_id continue elif count == 2: display_data["secondary"] = display_id continue display_data["other_{}".format(count)] = display_id return display_data
def macosx_update_check(): """Check for updates on Mac OS X. Returns zero on success. Discussion: Requires PyObjC bindings for Python. Works on Mac OS X 10.5 and later, only, unless the necessary PyObjC components can be installed manually on earlier systems. An alert is displayed if updates are available, and the user is given an option to ignore it or launch TeX Live Utility to handle the updates. Some sanity checks are present to ensure a login session that can display the alert. They may not be sufficient to avoid showing the alert over a full-screen window, unless an application has captured the display. """ assert sys.platform == "darwin", "incorrect platform" from CoreFoundation import CFUserNotificationDisplayNotice, CFUserNotificationDisplayAlert, CFBundleCreate, CFBundleCopyResourceURL, CFPreferencesCopyAppValue from CoreFoundation import kCFUserNotificationNoteAlertLevel, kCFUserNotificationAlternateResponse from Quartz import CGMainDisplayID, CGDisplayIsCaptured, CGSessionCopyCurrentDictionary from Quartz import kCGSessionOnConsoleKey, kCGSessionLoginDoneKey from LaunchServices import LSFindApplicationForInfo, LSOpenFromURLSpec from LaunchServices import kLSUnknownCreator, LSLaunchURLSpec from Foundation import NSURL, NSFoundationVersionNumber from math import floor # http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPMultipleUsers/BPMultipleUsers.html sessionInfo = CGSessionCopyCurrentDictionary() if sessionInfo == None: log_message("unable to get session dictionary") return 0 if sessionInfo[kCGSessionOnConsoleKey] is False: log_message("not running as console user; skipping update check") return 0 if sessionInfo[kCGSessionLoginDoneKey] is False: log_message("login incomplete; skipping update check") return 0 # check this first; no point in continuing if we can't show the alert # note: this doesn't help with Skim's full screen mode if CGDisplayIsCaptured(CGMainDisplayID()): log_message("main display not available for update alert") return 0 # TeX Live Utility bundle identifier bundle_id = "com.googlecode.mactlmgr.tlu" # if this hasn't been set, try the default path texbin_path = CFPreferencesCopyAppValue("TLMTexBinPathPreferenceKey", bundle_id) if texbin_path == None: if os.path.exists("/usr/texbin"): texbin_path = "/usr/texbin" elif os.path.exists("/Library/TeX/texbin"): texbin_path = "/Library/TeX/texbin" if texbin_path == None: log_message( "no tlmgr path set; TeX Live update check will not proceed") return 1 repository = CFPreferencesCopyAppValue("TLMFullServerURLPreferenceKey", bundle_id) update_count, actual_repository = check_for_updates(os.path.join( texbin_path, "tlmgr"), repository=repository) if update_count == 0: return 0 if floor(NSFoundationVersionNumber) > 833: bundle_id = "com.googlecode.mactlmgr.TLUNotifier" ret, tln_fsref, tln_url = LSFindApplicationForInfo( kLSUnknownCreator, bundle_id, None, None, None) # launch TLUNotifier, passing the URL as an odoc Apple Event if ret == 0 and tln_url: log_message("using notifier %s with URL %s" % (tln_url, actual_repository)) spec = LSLaunchURLSpec() spec.appURL = tln_url spec.itemURLs = [NSURL.URLWithString_(actual_repository) ] if actual_repository else None ret, launchedURL = LSOpenFromURLSpec(spec, None) if ret: log_message("unable to launch TLUNotifier at %s (%d)" % (tln_url, ret)) else: log_message("unable to find TLUNotifier") else: title = "TeX Live updates available" msg = "Updates for %d %s are available for TeX Live. Would you like to update with TeX Live Utility now, or at a later time?" % ( update_count, "packages" if update_count > 1 else "package") # see if we can find TeX Live Utility...hopefully LaunchServices is working today ret, tlu_fsref, tlu_url = LSFindApplicationForInfo( kLSUnknownCreator, bundle_id, None, None, None) bundle = CFBundleCreate(None, tlu_url) if ret == 0 else None icon_url = CFBundleCopyResourceURL(bundle, "TeXDistTool", "icns", None) if bundle else None # show a modal alert, with options to update now or later cancel, response = CFUserNotificationDisplayAlert( _ALERT_TIMEOUT, kCFUserNotificationNoteAlertLevel, icon_url, None, None, title, msg, "Later", "Update", None, None) if kCFUserNotificationAlternateResponse == response: # launch TeX Live Utility, passing the URL as an odoc Apple Event spec = LSLaunchURLSpec() spec.appURL = tlu_url spec.itemURLs = [NSURL.URLWithString_(actual_repository) ] if actual_repository else None ret, launchedURL = LSOpenFromURLSpec(spec, None) else: log_message("user postponed TeX Live updates") return 0
def size(self) -> ScreenSize: if self.__screen_size is None: size = CGDisplayBounds(CGMainDisplayID()).size self.__screen_size = ScreenSize(int(size.width), int(size.height)) return self.__screen_size
def display_size_osx(): from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID mainMonitor = CGDisplayBounds(CGMainDisplayID()) return int(mainMonitor.size.width), int(mainMonitor.size.height)
#!/usr/bin/python # Prints current screen resolution. # See: https://stackoverflow.com/q/1281397/55075 from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID display = CGDisplayBounds(CGMainDisplayID()) print("Current screen resolution: %dx%d" % (display.size.width, display.size.height))
Move mouse to edge of screen """ # osx libraries for mouse control and display sizes # mouse control from Quartz.CoreGraphics import CGEventCreateMouseEvent from Quartz.CoreGraphics import kCGMouseButtonLeft from Quartz.CoreGraphics import CGEventPost from Quartz.CoreGraphics import kCGEventMouseMoved from Quartz.CoreGraphics import kCGHIDEventTap # display size from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID def movemouse(x, y): theEvent = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (x,y), kCGMouseButtonLeft) CGEventPost(kCGHIDEventTap, theEvent) mainMonitor = CGDisplayBounds(CGMainDisplayID()) x=mainMonitor.size.width y=mainMonitor.size.height # Move mouse (must be an onscreen pixel thus, -1s) movemouse(x-2,y-10)
def get_display_size(display_id=None): if display_id is None: display_id = CGMainDisplayID() size_data = CGDisplayBounds(display_id) return (size_data.size.width, size_data.size.height)
def _getScreenSize(): ''' Returns the screen resolution as integers in the format of (width, height) ''' screen = CGDisplayBounds(CGMainDisplayID()) return (int(screen.size.width), int(screen.size.height))
def screen_size(): mainMonitor = CGDisplayBounds(CGMainDisplayID()) return (mainMonitor.size.width, mainMonitor.size.height)
def screen_size(): from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID mainMonitor = CGDisplayBounds(CGMainDisplayID()) return (mainMonitor.size.width, mainMonitor.size.height)
def __init__(self, xInit, xFinal, momentum, nIterations): self.z = 0 self.nIterations = nIterations self.momentum = momentum plt.style.use('seaborn') plt.rc('xtick', labelsize=17) # fontsize of the tick labels plt.rc('ytick', labelsize=17) plt.rc('legend', fontsize=20) plt.rc('font', size=15) plt.rc('axes', labelsize=15) # fontsize of the x and y labels self.x = range(xInit, xFinal) self.Y = [self.momentum * exp(-0.5 * _) for _ in self.x] self.size = len(self.x) self.error = norm.rvs(0, scale=0.0001, size=self.size) self.simulated_data = [ max(0, y + e) for (y, e) in zip(self.Y[:self.size], self.error) ] #print(self.simulated_data) #windows #self.width = GetSystemMetrics(0) #self.height = GetSystemMetrics(1) #mac mainMonitor = CGDisplayBounds(CGMainDisplayID()) self.width = mainMonitor.size.width self.height = mainMonitor.size.height self.fig = plt.figure(figsize=(self.width, self.height)) self.sub1 = self.fig.add_subplot(2, 1, 2) self.sub1.set_title('Visual', fontsize=25) self.sub1.margins(0.05) # Default margin is 0.05, value 0 means fit self.sub1.set_xlim([0, 75]) self.sub1.set_ylim([-150, 150]) self.sub2 = self.fig.add_subplot(2, 2, 1) self.sub2.set_title('Alignment Step', fontsize=25) self.sub3 = self.fig.add_subplot(2, 2, 2) self.sub3.set_title('Residual', fontsize=25) self.sub3.set_xlim([-3, 3]) self.sub3.set_ylim([0, 3000]) self.fig.suptitle('Fastest Job', fontsize=35) #sub1legend = self.sub1.legend(loc='lower left', bbox_to_anchor=(0.5, -0.05), shadow=True) #sub2legend = self.sub2.legend(loc='lower left', bbox_to_anchor=(0.5, -0.05), shadow=True np.random.seed(42) data = np.random.rand(4, 4) cMap = mpl.cm.get_cmap('viridis', 20) heat = self.sub3.pcolor(data, cmap=cMap) cbar = plt.colorbar(heat) cbar.ax.get_yaxis().set_ticks([]) for j, lab in enumerate(['$1-5$', '$6-10$', '$10-15$', '$15-20$']): cbar.ax.text(2, (2 * j + 1) / 8.0, lab, ha='center', va='center') cbar.ax.get_yaxis().labelpad = 90 cbar.ax.set_ylabel('Iterational Residual', rotation=270, fontsize=25) self.Xann = self.sub2.annotate('X Step', xy=(0, 0), xytext=(0, .25)) self.Yann = self.sub2.annotate('Y Step', xy=(0, 0), xytext=(0, .25)) self.Zann = self.sub2.annotate('Z Step', xy=(0, 0), xytext=(0, .25))
def get_screen_size(): """This function finds the width and height of the screen. This will be for a single monitor in a multi-monitor set-up. Args: None Returns: A list of numbers (width-in-pixels, height-in-pixels) """ backend = plt.get_backend() if 'GTK' in backend: # Implementation by starfry at # https://stackoverflow.com/questions/3129322/how-do-i-get-monitor-resolution-in-python import gtk window = gtk.Window() # the screen contains all monitors screen = window.get_screen() # collect data about active monitor curmon = screen.get_monitor_at_window(screen.get_active_window()) dx, dy, width, height = screen.get_monitor_geometry(curmon) # get geometry of current monitor elif 'Tk' in backend: # Modified version of implementation by FogleBird at # https://stackoverflow.com/questions/8762536/how-can-i-choose-the-default-wx-display-in-wxpython import wx MyApp = wx.App(False) # the wx.App object must be created first. display = wx.Display(0) # find the size of the first display screen dx, dy, width, height = display.GetGeometry() elif 'MacOSX' in backend: # Implementation by Mike Rhodes at # https://stackoverflow.com/questions/1281397/how-to-get-the-desktop-resolution-in-mac-via-python from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID from Quartz import CGDisplayScreenSize mainMonitor = CGDisplayBounds(CGMainDisplayID()) width = mainMonitor.size.width height = mainMonitor.size.height sizeInMm = CGDisplayScreenSize(CGMainDisplayID()) pixels2inches = width * 25.4 / sizeInMm.width # 25.4 mm = 1 inch elif 'WX' in backend: # Implementation by Justin at # https://stackoverflow.com/questions/3129322/how-do-i-get-monitor-resolution-in-python import ctypes user32 = ctypes.windll.user32 user32.SetProcessDPIAware() width = user32.GetSystemMetrics(0) height = user32.GetSystemMetrics(1) elif 'Qt4' in backend: # NOT TESTED YET. Implementation by Harsh Kumar Narula at # https://stackoverflow.com/questions/3129322/how-do-i-get-monitor-resolution-in-python from PyQt4 import QtGui MyApp = QtGui.QApplication(sys.argv) screen_resolution = MyApp.desktop().screenGeometry() width = screen_resolution.width() height = screen_resolution.height() elif 'Qt5' in backend: # Implementation by Harsh Kumar Narula at # https://stackoverflow.com/questions/3129322/how-do-i-get-monitor-resolution-in-python from PyQt5 import QtWidgets MyApp = QtWidgets.QApplication(sys.argv) screen_resolution = MyApp.desktop().screenGeometry() width = screen_resolution.width() height = screen_resolution.height() else: print 'Solution not implemented yet for backend =', backend width, height = (1280, 1024) return (width, height)