Best Python code snippet using pyscreenshot_python
SnapshotWaylandGrabber.py
Source:SnapshotWaylandGrabber.py
1# -*- coding: utf-8 -*-2# Copyright (c) 2019 Detlev Offenbach <detlev@die-offenbachs.de>3#4"""5Module implementing a grabber object for non-Wayland desktops.6"""7import os8import uuid9from PyQt5.QtCore import pyqtSignal, QObject, QTimer10from PyQt5.QtGui import QPixmap, QCursor11from PyQt5.QtWidgets import QApplication12try:13 from PyQt5.QtDBus import QDBusInterface, QDBusMessage14 DBusAvailable = True15except ImportError:16 DBusAvailable = False17from E5Gui import E5MessageBox18from .SnapshotModes import SnapshotModes19import Globals20class SnapshotWaylandGrabber(QObject):21 """22 Class implementing a grabber object for non-Wayland desktops.23 24 @signal grabbed(QPixmap) emitted after the grab operation is finished25 """26 grabbed = pyqtSignal(QPixmap)27 28 def __init__(self, parent=None):29 """30 Constructor31 32 @param parent reference to the parent object33 @type QObject34 """35 super(SnapshotWaylandGrabber, self).__init__(parent)36 37 from .SnapshotTimer import SnapshotTimer38 self.__grabTimer = SnapshotTimer()39 self.__grabTimer.timeout.connect(self.__performGrab)40 41 def supportedModes(self):42 """43 Public method to get the supported screenshot modes.44 45 @return tuple of supported screenshot modes46 @rtype tuple of SnapshotModes47 """48 if DBusAvailable and Globals.isKdeDesktop():49 modes = (50 SnapshotModes.Fullscreen,51 SnapshotModes.SelectedScreen,52 SnapshotModes.SelectedWindow,53 )54 elif DBusAvailable and Globals.isGnomeDesktop():55 modes = (56 SnapshotModes.Fullscreen,57 SnapshotModes.SelectedScreen,58 SnapshotModes.SelectedWindow,59 SnapshotModes.Rectangle,60 )61 else:62 modes = ()63 64 return modes65 66 def grab(self, mode, delay=0, captureCursor=False,67 captureDecorations=False):68 """69 Public method to perform a grab operation potentially after a delay.70 71 @param mode screenshot mode72 @type ScreenshotModes73 @param delay delay in seconds74 @type int75 @param captureCursor flag indicating to include the mouse cursor76 @type bool77 @param captureDecorations flag indicating to include the window78 decorations (only used for mode SnapshotModes.SelectedWindow)79 @type bool80 """81 if not DBusAvailable:82 # just to play it safe83 self.grabbed.emit(QPixmap())84 return85 86 self.__mode = mode87 self.__captureCursor = captureCursor88 self.__captureDecorations = captureDecorations89 if delay:90 self.__grabTimer.start(delay)91 else:92 QTimer.singleShot(200, self.__performGrab)93 94 def __performGrab(self):95 """96 Private method to perform the grab operations.97 98 @exception RuntimeError raised to indicate an unsupported grab mode99 """100 if self.__mode == SnapshotModes.Fullscreen:101 self.__grabFullscreen()102 elif self.__mode == SnapshotModes.SelectedScreen:103 self.__grabSelectedScreen()104 elif self.__mode == SnapshotModes.SelectedWindow:105 self.__grabSelectedWindow()106 elif self.__mode == SnapshotModes.Rectangle:107 self.__grabRectangle()108 else:109 raise RuntimeError("unsupported grab mode given")110 111 def __grabFullscreen(self):112 """113 Private method to grab the complete desktop.114 """115 snapshot = QPixmap()116 117 if Globals.isKdeDesktop():118 interface = QDBusInterface(119 "org.kde.KWin",120 "/Screenshot",121 "org.kde.kwin.Screenshot"122 )123 reply = interface.call(124 "screenshotFullscreen",125 self.__captureCursor126 )127 if self.__checkReply(reply, 1):128 filename = reply.arguments()[0]129 if filename:130 snapshot = QPixmap(filename)131 try:132 os.remove(filename)133 except OSError:134 # just ignore it135 pass136 elif Globals.isGnomeDesktop():137 path = self.__temporaryFilename()138 interface = QDBusInterface(139 "org.gnome.Shell",140 "/org/gnome/Shell/Screenshot",141 "org.gnome.Shell.Screenshot"142 )143 reply = interface.call(144 "Screenshot",145 self.__captureCursor,146 False,147 path148 )149 if self.__checkReply(reply, 2):150 filename = reply.arguments()[1]151 if filename:152 snapshot = QPixmap(filename)153 try:154 os.remove(filename)155 except OSError:156 # just ignore it157 pass158 159 self.grabbed.emit(snapshot)160 161 def __grabSelectedScreen(self):162 """163 Private method to grab a selected screen.164 """165 snapshot = QPixmap()166 167 if Globals.isKdeDesktop():168 # Step 1: get the screen number of screen containing the cursor169 if Globals.qVersionTuple() >= (5, 10, 0):170 screen = QApplication.screenAt(QCursor.pos())171 try:172 screenId = QApplication.screens().index(screen)173 except ValueError:174 # default to screen 0175 screenId = 0176 else:177 desktop = QApplication.desktop()178 screenId = desktop.screenNumber(QCursor.pos())179 180 # Step 2: grab the screen181 interface = QDBusInterface(182 "org.kde.KWin",183 "/Screenshot",184 "org.kde.kwin.Screenshot"185 )186 reply = interface.call(187 "screenshotScreen",188 screenId,189 self.__captureCursor190 )191 if self.__checkReply(reply, 1):192 filename = reply.arguments()[0]193 if filename:194 snapshot = QPixmap(filename)195 try:196 os.remove(filename)197 except OSError:198 # just ignore it199 pass200 elif Globals.isGnomeDesktop():201 # Step 1: grab entire desktop202 path = self.__temporaryFilename()203 interface = QDBusInterface(204 "org.gnome.Shell",205 "/org/gnome/Shell/Screenshot",206 "org.gnome.Shell.Screenshot"207 )208 reply = interface.call(209 "ScreenshotWindow",210 self.__captureDecorations,211 self.__captureCursor,212 False,213 path214 )215 if self.__checkReply(reply, 2):216 filename = reply.arguments()[1]217 if filename:218 snapshot = QPixmap(filename)219 try:220 os.remove(filename)221 except OSError:222 # just ignore it223 pass224 225 # Step 2: extract the area of the screen containing226 # the cursor227 if not snapshot.isNull():228 if Globals.qVersionTuple() >= (5, 10, 0):229 screen = QApplication.screenAt(QCursor.pos())230 geom = screen.geometry()231 else:232 desktop = QApplication.desktop()233 screenId = desktop.screenNumber(QCursor.pos())234 geom = desktop.screenGeometry(screenId)235 snapshot = snapshot.copy(geom)236 237 self.grabbed.emit(snapshot)238 239 def __grabSelectedWindow(self):240 """241 Private method to grab a selected window.242 """243 snapshot = QPixmap()244 245 if Globals.isKdeDesktop():246 mask = 0247 if self.__captureDecorations:248 mask |= 1249 if self.__captureCursor:250 mask |= 2251 interface = QDBusInterface(252 "org.kde.KWin",253 "/Screenshot",254 "org.kde.kwin.Screenshot"255 )256 reply = interface.call(257 "interactive",258 mask259 )260 if self.__checkReply(reply, 1):261 filename = reply.arguments()[0]262 if filename:263 snapshot = QPixmap(filename)264 try:265 os.remove(filename)266 except OSError:267 # just ignore it268 pass269 elif Globals.isGnomeDesktop():270 path = self.__temporaryFilename()271 interface = QDBusInterface(272 "org.gnome.Shell",273 "/org/gnome/Shell/Screenshot",274 "org.gnome.Shell.Screenshot"275 )276 reply = interface.call(277 "ScreenshotWindow",278 self.__captureDecorations,279 self.__captureCursor,280 False,281 path282 )283 if self.__checkReply(reply, 2):284 filename = reply.arguments()[1]285 if filename:286 snapshot = QPixmap(filename)287 try:288 os.remove(filename)289 except OSError:290 # just ignore it291 pass292 293 self.grabbed.emit(snapshot)294 295 def __grabRectangle(self):296 """297 Private method to grab a rectangular desktop area.298 """299 snapshot = QPixmap()300 301 if Globals.isGnomeDesktop():302 # Step 1: let the user select the area303 interface = QDBusInterface(304 "org.gnome.Shell",305 "/org/gnome/Shell/Screenshot",306 "org.gnome.Shell.Screenshot"307 )308 reply = interface.call("SelectArea")309 if self.__checkReply(reply, 4):310 x, y, width, height = reply.arguments()[:4]311 312 # Step 2: grab the selected area313 path = self.__temporaryFilename()314 reply = interface.call(315 "ScreenshotArea",316 x, y, width, height,317 False,318 path319 )320 if self.__checkReply(reply, 2):321 filename = reply.arguments()[1]322 if filename:323 snapshot = QPixmap(filename)324 try:325 os.remove(filename)326 except OSError:327 # just ignore it328 pass329 330 self.grabbed.emit(snapshot)331 332 def __checkReply(self, reply, argumentsCount):333 """334 Private method to check, if a reply is valid.335 336 @param reply reference to the reply message337 @type QDBusMessage338 @param argumentsCount number of expected arguments339 @type int340 @return flag indicating validity341 @rtype bool342 """343 if reply.type() == QDBusMessage.ReplyMessage:344 if len(reply.arguments()) == argumentsCount:345 return True346 347 E5MessageBox.warning(348 None,349 self.tr("Screenshot Error"),350 self.tr("<p>Received an unexpected number of reply arguments."351 " Expected {0} but got {1}</p>").format(352 argumentsCount,353 len(reply.arguments()),354 ))355 356 elif reply.type() == QDBusMessage.ErrorMessage:357 E5MessageBox.warning(358 None,359 self.tr("Screenshot Error"),360 self.tr("<p>Received error <b>{0}</b> from DBus while"361 " performing screenshot.</p><p>{1}</p>").format(362 reply.errorName(),363 reply.errorMessage(),364 ))365 366 elif reply.type() == QDBusMessage.InvalidMessage:367 E5MessageBox.warning(368 None,369 self.tr("Screenshot Error"),370 self.tr("Received an invalid reply."))371 372 else:373 E5MessageBox.warning(374 None,375 self.tr("Screenshot Error"),376 self.tr("Received an unexpected reply."))377 378 return False379 380 def __temporaryFilename(self):381 """382 Private method to generate a temporary filename.383 384 @return path name for a unique, temporary file385 @rtype str386 """...
kwin_dbus.py
Source:kwin_dbus.py
...22 class Screenshot(MessageGenerator):23 interface = "org.kde.kwin.Screenshot"24 def __init__(self, object_path="/Screenshot", bus_name="org.kde.KWin"):25 super().__init__(object_path=object_path, bus_name=bus_name)26 def screenshotFullscreen(self, captureCursor):27 return new_method_call(28 self, "screenshotFullscreen", "b", (captureCursor,)29 )30 def screenshotArea(self, x, y, width, height, captureCursor):31 return new_method_call(32 self,33 "screenshotArea",34 "iiiib",35 (x, y, width, height, captureCursor),36 )37 # https://jeepney.readthedocs.io/en/latest/integrate.html38 connection = connect_and_authenticate(bus="SESSION")39 dbscr = Screenshot()40 # bbox not working:41 # if bbox: msg = dbscr.screenshotArea(bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1], False)42 msg = dbscr.screenshotFullscreen(False)43 filename = connection.send_and_get_reply(msg)44 filename = filename[0]45 if not filename:46 raise KdeDBusError()47 im = Image.open(filename)48 os.remove(filename)49 if bbox:50 im = im.crop(bbox)51 return im52 def backend_version(self):...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!