1#!/usr/bin/env python 2""" pygame.examples.scrap_clipboard 3 4Demonstrates the clipboard capabilities of pygame. 5 6Copy/paste! 7 8 9Keyboard Controls 10----------------- 11 12g - get and print types in clipboard. If, image blit to screen. 13p - place some text into clipboard 14a - print types available in the clipboard 15i - put image into the clipboard 16""" 17import os 18 19import pygame as pg 20import pygame.scrap as scrap 21from pygame.compat import as_bytes 22 23BytesIO = pg.compat.get_BytesIO() 24 25 26def usage(): 27 print("Press the 'g' key to get all of the current clipboard data") 28 print("Press the 'p' key to put a string into the clipboard") 29 print("Press the 'a' key to get a list of the currently available types") 30 print("Press the 'i' key to put an image into the clipboard") 31 32 33main_dir = os.path.split(os.path.abspath(__file__))[0] 34 35pg.init() 36screen = pg.display.set_mode((200, 200)) 37c = pg.time.Clock() 38going = True 39 40# Initialize the scrap module and use the clipboard mode. 41scrap.init() 42scrap.set_mode(pg.SCRAP_CLIPBOARD) 43 44usage() 45 46while going: 47 for e in pg.event.get(): 48 if e.type == pg.QUIT or (e.type == pg.KEYDOWN and e.key == pg.K_ESCAPE): 49 going = False 50 51 elif e.type == pg.KEYDOWN and e.key == pg.K_g: 52 # This means to look for data. 53 print("Getting the different clipboard data..") 54 for t in scrap.get_types(): 55 r = scrap.get(t) 56 if r and len(r) > 500: 57 print("Type %s : (large %i byte buffer)" % (t, len(r))) 58 elif r is None: 59 print("Type %s : None" % (t,)) 60 else: 61 print("Type %s : '%s'" % (t, r.decode("ascii", "ignore"))) 62 if "image" in t: 63 namehint = t.split("/")[1] 64 if namehint in ["bmp", "png", "jpg"]: 65 f = BytesIO(r) 66 loaded_surf = pg.image.load(f, "." + namehint) 67 screen.blit(loaded_surf, (0, 0)) 68 69 elif e.type == pg.KEYDOWN and e.key == pg.K_p: 70 # Place some text into the selection. 71 print("Placing clipboard text.") 72 scrap.put(pg.SCRAP_TEXT, as_bytes("Hello. This is a message from scrap.")) 73 74 elif e.type == pg.KEYDOWN and e.key == pg.K_a: 75 # Get all available types. 76 print("Getting the available types from the clipboard.") 77 types = scrap.get_types() 78 print(types) 79 if len(types) > 0: 80 print("Contains %s: %s" % (types[0], scrap.contains(types[0]))) 81 print("Contains _INVALID_: ", scrap.contains("_INVALID_")) 82 83 elif e.type == pg.KEYDOWN and e.key == pg.K_i: 84 print("Putting image into the clipboard.") 85 scrap.set_mode(pg.SCRAP_CLIPBOARD) 86 fp = open(os.path.join(main_dir, "data", "liquid.bmp"), "rb") 87 buf = fp.read() 88 scrap.put("image/bmp", buf) 89 fp.close() 90 91 elif e.type in (pg.KEYDOWN, pg.MOUSEBUTTONDOWN): 92 usage() 93 pg.display.flip() 94 c.tick(40) 95pg.quit() 96