deoversimplify

This commit is contained in:
MeexReay 2025-09-20 17:25:17 +03:00
parent 41943115ba
commit 5932aac00d
31 changed files with 498 additions and 517 deletions

1
.gitignore vendored
View file

@ -2,3 +2,4 @@ build/
dist/ dist/
pygwin2.egg-info/ pygwin2.egg-info/
src/pygwin2/__pycache__/ src/pygwin2/__pycache__/
.ruff_cache/

13
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,13 @@
{
"[python]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.codeActionsOnSave": {
"source.organizeImports.ruff": "always"
},
},
"ruff.configurationPreference": "filesystemFirst",
"ruff.lineLength": 110,
"ruff.lint.select": ["ALL"],
"ruff.lint.ignore": ["E501"],
}

View file

@ -16,7 +16,6 @@ license-files = ["LICENSE"]
dependencies = [ dependencies = [
"pydub", "pydub",
"pygame", "pygame",
"requests", # ?????????
"pyautogui", "pyautogui",
"inputs", "inputs",
"pillow", "pillow",
@ -41,3 +40,17 @@ requires = [
"setuptools >= 42" "setuptools >= 42"
] ]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[tool.ruff]
line-length = 88
indent-width = 4
target-version = "py39"
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F"]
ignore = []
fixable = ["ALL"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"

View file

@ -1,16 +1,16 @@
from pygwin.surface import surface import .pygame
import pygwin.keyboard as keyboard
from pygwin.console import console
from pygwin.color import color
import pygwin.gamepad as _gp
import pygwin.mouse as mouse
from pygwin.rect import rect
import pygwin.image as image
import pygwin.mixer as mixer
from pygwin.tray import tray
from pygame.locals import * from pygame.locals import *
import pygwin.font as font from .tray import tray
from pygwin._win import * from .rect import rect
from pygwin._pg import pg from .surface import surface
import pygwin.ui as ui from .console import console
gamepad = _gp.gamepad(pg) from .color import color
from .window import *
import .keyboard
import .mouse
import .image
import .mixer
import .font
import .ui
import .gamepad as _gp
gamepad = _gp.gamepad(pygame)

View file

@ -1,16 +0,0 @@
from contextlib import contextmanager as _cm
import os as _os
import sys as _sys
@_cm
def _suppress_stdout():
with open(_os.devnull, "w") as devnull:
old_stdout = _sys.stdout
_sys.stdout = devnull
try:
yield
finally:
_sys.stdout = old_stdout
with _suppress_stdout():
import pygame as pg
pg.init()

View file

@ -1,231 +0,0 @@
from pygwin.surface import surface as _surface
from pygwin.tray import tray as _tray
from datetime import datetime as _dt
from pygwin.image import save as _s
from pygwin._pg import pg as _pg
import pygwin.image as _img
try:
import win32job as _w32j
import win32api as _w32a
import win32con as _w32c
import win32gui as _w32g
nonwin32api = False
except:
nonwin32api = True
import sys as _sys
import warnings as _warn
import winerror as _we
import requests as _req
import tempfile as _tf
import threading as _t
import pickle as _p
import mouse as _m
import time as _ti
class _win(_surface):
def __init__(self, iconpath=None):
self._orig = _pg.display.get_surface()
super().__init__(self._orig.get_size())
self._orig = _pg.display.get_surface()
self._clock = _pg.time.Clock()
self._withfps = False
self._iconpath = iconpath
self._isallowdrag = False
# self._issmartdrag = False
if iconpath != None:
self.tray = _tray(self.title,iconpath)
def update(self, fps=-1):
if fps != -1:
self._clock.tick(fps)
self._withfps = True
_pg.display.update()
def resize(self, size=None):
if size == None:
return self.size
else:
self._orig = _pg.display.set_mode(size)
def title():
def fget(self):
return _pg.display.get_caption()[0]
def fset(self, value):
if type(value) != str:
return
_pg.display.set_caption(value)
def fdel(self):
pass
return locals()
title = property(**title())
def icon(value):
_pg.display.set_icon(_pg.image.load(value))
self._iconpath = iconpath
def size():
def fget(self):
return _pg.display.get_window_size()
def fset(self, value):
if type(value) in [list,tuple]:
return
_pg.display.set_mode(value)
def fdel(self):
pass
return locals()
size = property(**size())
def fullscreen(self):
_pg.display.toogle_fullscreen()
def close(self):
# _w32g.PostMessage(self.hwnd, _w32c.WM_CLOSE, 0, 0)
_pg.display.quit()
try:self.tray.stop()
except:pass
def focus(self):
if not nonwin32api:
self.hide()
self.show()
_w32g.BringWindowToTop(self.hwnd)
_w32g.ShowWindow(self.hwnd, _w32c.SW_SHOWNORMAL)
_w32g.SetForegroundWindow(self.hwnd)
def hide(self):
if not nonwin32api:
_w32g.ShowWindow(self.hwnd, _w32c.SW_HIDE)
def show(self):
if not nonwin32api:
_w32g.ShowWindow(self.hwnd, _w32c.SW_SHOW)
def move(self, x, y):
if not nonwin32api:
rect = self._getRect()
_w32g.MoveWindow(self.hwnd, int(x), int(y),
rect[2]-x, rect[3]-y, 0)
def screenshot(self, path):
_s(self._orig, path)
return path
def center(self,x=_pg.display.get_desktop_sizes()[0][0]/2,
y=_pg.display.get_desktop_sizes()[0][1]/2):
self.move(x-self.size[0]/2,y-self.size[1]/2)
def _getRect(self):
if not nonwin32api:
return _w32g.GetWindowRect(self.hwnd)
def denyDrag(self):
if not nonwin32api:
self._isallowdrag = True
def loop(self):
while self._isallowdrag:
pos = _m.get_position()
pos = [pos[i]-self.position[i] for i in range(2)]
if pos[0] < self._getRect()[2]-137:
if pos[1] < 30:
_m.release('left')
_t.Thread(target=lambda:loop(self),daemon=1).start()
def allowDrag(self):
if not nonwin32api:
self._isallowdrag = False
# def smartDrag(self, x):
# self.allowDrag()
# self._issmartdrag = x
# if x:
# self._isallowdrag = True
# def loop(self):
# wsd = None
# while self._issmartdrag:
# self.update()
# pos = _m.get_position()
# pos = [pos[i]-self.position[i] for i in range(2)]
# if pos[0] < _w32g.GetWindowRect(self.hwnd)[2]-137:
# if pos[1] < 30:
# if _m.is_pressed('left'):
# _m.release('left')
# if wsd == None:
# wsd = pos+list(self.position)
# else:
# if wsd != pos+list(self.position):
# self.move(wsd[2]+(pos[0]-wsd[0]),
# wsd[3]+(pos[1]-wsd[1]))
# else:
# wsd = None
# _ti.sleep(0.5)
# _t.Thread(target=lambda:loop(self),daemon=1).start()
@property
def position(self):
if not nonwin32api:
rect = self._getRect()
x = rect[0]
y = rect[1]
return (x, y)
@property
def rawFps(self):
if self._withfps:
return self._clock.get_fps()
else:
return float(f'2010.{_dt.now().year}')
@property
def fps(self):
return int(self.rawFps)
@property
def hwnd(self):
if not nonwin32api:
return _pg.display.get_wm_info()['window']
@property
def visible(self):
if not nonwin32api:
return _w32g.IsWindowVisible(self._win)
def create(title=None, size=(0,0), icon=None, resizable=False, noframe=False):
screen = _pg.display.set_mode(size)
if resizable:
screen = _pg.display.set_mode(size,_pg.RESIZABLE)
if noframe:
screen = _pg.display.set_mode(size,_pg.NOFRAME)
else:
if title != None:
_pg.display.set_caption(title)
if icon != None:
_pg.display.set_icon(_pg.image.load(icon))
return _win(icon)
def ramLimit(memory_limit):
if not nonwin32api:
g_hjob = None
def create_job(job_name='', breakaway='silent'):
hjob = _w32j.CreateJobObject(None, job_name)
if breakaway:
info = _w32j.QueryInformationJobObject(hjob,
_w32j.JobObjectExtendedLimitInformation)
if breakaway == 'silent':
info['BasicLimitInformation']['LimitFlags'] |= (
_w32j.JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK)
else:
info['BasicLimitInformation']['LimitFlags'] |= (
_w32j.JOB_OBJECT_LIMIT_BREAKAWAY_OK)
_w32j.SetInformationJobObject(hjob,
_w32j.JobObjectExtendedLimitInformation, info)
return hjob
def assign_job(hjob):
global g_hjob
hprocess = _w32a.GetCurrentProcess()
try:
_w32j.AssignProcessToJobObject(hjob, hprocess)
g_hjob = hjob
except _w32j.error as e:
if (e._we != _we.ERROR_ACCESS_DENIED or
_sys.getwindowsversion() >= (6, 2) or
not _w32j.IsProcessInJob(hprocess, None)):
raise
_warn.warn('The process is already in a job. Nested jobs are not '
'supported prior to Windows 8.')
def limit_memory(memory_limit):
if g_hjob is None:
return
info = _w32j.QueryInformationJobObject(g_hjob,
_w32j.JobObjectExtendedLimitInformation)
info['ProcessMemoryLimit'] = memory_limit
info['BasicLimitInformation']['LimitFlags'] |= (
_w32j.JOB_OBJECT_LIMIT_PROCESS_MEMORY)
_w32j.SetInformationJobObject(g_hjob,
_w32j.JobObjectExtendedLimitInformation, info)
assign_job(create_job())
limit_memory(memory_limit)
def close():
_pg.quit()
quit()
def getEvents():
return _pg.event.get()

View file

@ -1,86 +1,85 @@
from pygwin._pg import pg import .pygame
try: try:
import win32console as w32con import win32console
import win32con as w32c import win32con
import win32gui as w32g import win32gui
import win32api as w32a nonwin = False
nonwin32api = False
except: except:
nonwin32api = True nonwin = True
import pyautogui as pag import pyautogui
class console: class console:
def __init__(self): def __init__(self):
if not nonwin32api: if not nonwin:
self._hwnd = w32con.GetConsoleWindow() self._hwnd = win32console.GetConsoleWindow()
@property @property
def hwnd(self): def hwnd(self):
if not nonwin32api: if not nonwin:
return self._hwnd return self._hwnd
def focus(self): def focus(self):
if not nonwin32api: if not nonwin:
self.hide() self.hide()
self.show() self.show()
w32g.BringWindowToTop(self.hwnd) win32gui.BringWindowToTop(self.hwnd)
w32g.ShowWindow(self.hwnd, w32c.SW_SHOWNORMAL) win32gui.ShowWindow(self.hwnd, win32con.SW_SHOWNORMAL)
w32g.SetForegroundWindow(self.hwnd) win32gui.SetForegroundWindow(self.hwnd)
def hide(self): def hide(self):
if not nonwin32api: if not nonwin:
w32g.ShowWindow(self.hwnd, w32c.SW_HIDE) win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE)
def show(self): def show(self):
if not nonwin32api: if not nonwin:
w32g.ShowWindow(self.hwnd, w32c.SW_SHOW) win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
def move(self, x, y): def move(self, x, y):
if not nonwin32api: if not nonwin:
w32g.SetWindowPos(self.hwnd, x, y, self.size[0], self.size[1]) win32gui.SetWindowPos(self.hwnd, x, y, self.size[0], self.size[1])
def resize(self, width, height): def resize(self, width, height):
if not nonwin32api: if not nonwin:
w32g.SetWindowPos(self.hwnd, self.position[0], self.position[1], width, height) win32gui.SetWindowPos(self.hwnd, self.position[0], self.position[1], width, height)
def minimize(self): def minimize(self):
if not nonwin32api: if not nonwin:
w32g.ShowWindow(hwnd, w32c.SW_MINIMIZE) win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
return self.size return self.size
def maximize(self): def maximize(self):
if not nonwin32api: if not nonwin:
w32g.ShowWindow(hwnd, w32c.SW_MAXIMIZE) win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)
return self.size return self.size
def title(): def title():
def fget(self): def fget(self):
if not nonwin32api: if not nonwin:
return w32con.GetConsoleTitle() return win32console.GetConsoleTitle()
def fset(self, value): def fset(self, value):
if not nonwin32api: if not nonwin:
w32con.SetConsoleTitle(str(value)) win32console.SetConsoleTitle(str(value))
def fdel(self): def fdel(self):
pass pass
return locals() return locals()
title = property(**title()) title = property(**title())
def center(self,x=_pg.display.get_desktop_sizes()[0][0]/2, def center(self,x=pygame.display.get_desktop_sizes()[0][0]/2,
y=_pg.display.get_desktop_sizes()[0][1]/2): y=pygame.display.get_desktop_sizes()[0][1]/2):
if not nonwin32api: if not nonwin:
self.move(x-self.size[0]/2,y-self.size[1]/2) self.move(x-self.size[0]/2,y-self.size[1]/2)
@property @property
def visible(self): def visible(self):
if not nonwin32api: if not nonwin:
return w32g.IsWindowVisible(self.hwnd) return win32gui.IsWindowVisible(self.hwnd)
@property @property
def position(self): def position(self):
if not nonwin32api: if not nonwin:
rect = w32g.GetWindowRect(self.hwnd) rect = win32gui.GetWindowRect(self.hwnd)
x = rect[0]+7 x = rect[0]+7
y = rect[1] y = rect[1]
return (x, y) return (x, y)
@property @property
def size(self): def size(self):
if not nonwin32api: if not nonwin:
rect = w32g.GetWindowRect(self.hwnd) rect = win32gui.GetWindowRect(self.hwnd)
w = rect[2] - self.position[0]-7 w = rect[2] - self.position[0]-7
h = rect[3] - self.position[1]-7 h = rect[3] - self.position[1]-7
return (w, h) return (w, h)
def screenshot(self, path): def screenshot(self, path):
if not nonwin32api: if not nonwin:
rect = self.position+self.size rect = self.position+self.size
self.focus() self.focus()
pag.screenshot(path, region=rect) pyautogui.screenshot(path, region=rect)
return path return path
console = console() console = console()

View file

@ -1,11 +1,11 @@
from pygwin.surface import surface as _surface from .surface import surface
from pygwin._pg import pg as _pg import .pygame
class font: class font:
def __init__(self, path): def __init__(self, path):
self._path = path self._path = path
def _font(self, size): def _font(self, size):
return _pg.font.Font(self._path,size) return pygame.font.Font(self._path,size)
def render(self, text, size, color, newLineSpace=5, def render(self, text, size, color, newLineSpace=5,
italic=False, bold=False, underline=False): italic=False, bold=False, underline=False):
text = str(text) text = str(text)
@ -15,8 +15,8 @@ class font:
font.set_underline(underline) font.set_underline(underline)
if text.replace('\n', '') != text: if text.replace('\n', '') != text:
text = text.split('\n') text = text.split('\n')
surf = _pg.Surface([font.size(max(text,key=lambda x:font.size(x)[0]))[0], surf = pygame.Surface([font.size(max(text,key=lambda x:font.size(x)[0]))[0],
(font.size('123')[1]+newLineSpace)*len(text)],_pg.SRCALPHA) (font.size('123')[1]+newLineSpace)*len(text)],pygame.SRCALPHA)
y = 0 y = 0
for i in text: for i in text:
r = font.render(i, True, color) r = font.render(i, True, color)
@ -26,7 +26,7 @@ class font:
y += newLineSpace y += newLineSpace
else: else:
surf = font.render(text, True, color) surf = font.render(text, True, color)
surface = _surface(surf.get_size()) surface = surface(surf.get_size())
surface._surface_orig = surf surface._surface_orig = surf
return surface return surface
def size(self, text, size, newLineSpace=5, def size(self, text, size, newLineSpace=5,
@ -38,6 +38,6 @@ class font:
class sysFont(font): class sysFont(font):
def __init__(self, name): def __init__(self, name):
self._path = _pg.font.match_font(name) self._path = pygame.font.match_font(name)
defaultFont = font(_pg.font.get_default_font()) defaultFont = font(pygame.font.get_default_font())

View file

@ -1,6 +1,5 @@
import inputs as _inputs import inputs as _inputs
import threading as _threading import threading as _threading
import time as _time
class gamepad: class gamepad:
def __init__(self, pygame): def __init__(self, pygame):

View file

@ -1,43 +1,42 @@
from pygwin._pg import pg as _pg import .pygame
from pygwin.surface import surface as _surface from .surface import surface
from PIL import Image as _im from PIL import Image
import tempfile as _tf import tempfile
import randstr as _rs import pickle
import pickle as _p import bz2
import bz2 as _bz2 import os
import os as _os
def load(path): def load(path):
if path.endswith('.gif'): if path.endswith('.gif'):
im = _im.open(path) im = Image.open(path)
with _tf.TemporaryDirectory() as td: with tempfile.TemporaryDirectory() as td:
surfs = [] surfs = []
for i in range(im.n_frames): for i in range(im.n_frames):
im.seek(i) im.seek(i)
p = _os.path.join(td,f'{i}.png') p = os.path.join(td,f'{i}.png')
im.save(p) im.save(p)
s = _pg.image.load(p) s = pygame.image.load(p)
_os.remove(p) os.remove(p)
sg = _surface(s.get_size()) sg = surface(s.get_size())
sg.blit(s,(0,0)) sg.blit(s,(0,0))
surfs.append(sg) surfs.append(sg)
return surfs return surfs
else: else:
im = _im.open(path.encode('utf8').decode('utf8')) im = Image.open(path.encode('utf8').decode('utf8'))
image = _pg.image.fromstring(im.tobytes(),im.size,im.mode) image = pygame.image.fromstring(im.tobytes(),im.size,im.mode)
surf = _surface(im.size) surf = surface(im.size)
surf.blit(image,(0,0)) surf.blit(image,(0,0))
return surf return surf
def save(surface, dest): def save(surface, dest):
_pg.image.save_extended(surface._grp(), dest) pygame.image.save_extended(surface._grp(), dest)
def toBytes(surface): def toBytes(surface):
return _bz2.compress(_p.dumps([_pg.image.tostring(surface._grp(),"RGBA"),list(surface.size)])) return bz2.compress(pickle.dumps([pygame.image.tostring(surface._grp(),"RGBA"),list(surface.size)]))
def fromBytes(bytes): def fromBytes(bytes):
string = _p.loads(_bz2.decompress(bytes)) string = pickle.loads(bz2.decompress(bytes))
surf = _pg.image.fromstring(string[0],tuple(string[1]),"RGBA") surf = pygame.image.fromstring(string[0],tuple(string[1]),"RGBA")
surface = _surface(tuple(string[1])) surface = surface(tuple(string[1]))
surface.blit(surf,(0,0)) surface.blit(surf,(0,0))
return surface return surface

View file

@ -1,21 +1,21 @@
from pygwin._pg import pg as _pg import .pygame
def getPressed(): def getPressed():
fkeys = {} fkeys = {}
keys = _pg.key.get_pressed() keys = pygame.key.get_pressed()
for i in range(len(keys)): for i in range(len(keys)):
fkeys.update({_pg.key.name(i):keys[i]}) fkeys.update({pygame.key.name(i):keys[i]})
return fkeys return fkeys
def isPressed(key): def isPressed(key):
return getPressed()[key] return getPressed()[key]
import inspect as _i import inspect
_aliases = {'getPressed':['gprs','getkeys'], _aliases = {'getPressed':['gprs','getkeys'],
'isPressed':['isprs','keyprs']} 'isPressed':['isprs','keyprs']}
for i in _aliases.items(): for i in _aliases.items():
exec(f'args = _i.signature({i[0]})') exec(f'args = inspect.signature({i[0]})')
args = [str(i[1]) for i in dict(args.parameters).items()] args = [str(i[1]) for i in dict(args.parameters).items()]
args = ', '.join(args) args = ', '.join(args)
for i0 in i[1]: for i0 in i[1]:

View file

@ -1,6 +1,6 @@
from pygwin._pg import pg as _pg import .pygame
import os as _os import os
import tempfile as _tf import tempfile
ffmpeg = None ffmpeg = None
@ -8,18 +8,18 @@ class sound:
def __init__(self, path): def __init__(self, path):
if not (path.endswith('.wav') or path.endswith('.ogg')): if not (path.endswith('.wav') or path.endswith('.ogg')):
try: try:
from pydub import AudioSegment as _as from pydub import AudioSegment as as
if ffmpeg != None: if ffmpeg != None:
_as.ffmpeg = ffmpeg as.ffmpeg = ffmpeg
_as.converter = ffmpeg as.converter = ffmpeg
sound = _as.from_file(path, _os.path.splitext(path)[1]) sound = as.from_file(path, os.path.splitext(path)[1])
path = _tf.mkstemp('.wav') path = tempfile.mkstemp('.wav')
sound.export(path, format="wav") sound.export(path, format="wav")
except: except:
print('Set ffmpeg to path so that you don'+\ print('Set ffmpeg to path so that you don'+\
"'t have to convert the file to "+\ "'t have to convert the file to "+\
'".wav". If you have installed, but the error still appears, write down the path to ffmpeg.exe in plugin.ffmpeg.') '".wav". If you have installed, but the error still appears, write down the path to ffmpeg.exe in plugin.ffmpeg.')
self._sound = _pg.mixer.Sound(path) self._sound = pygame.mixer.Sound(path)
def play(self): def play(self):
self._sound.play() self._sound.play()
def stop(self): def stop(self):
@ -44,37 +44,37 @@ class music:
self._path = path self._path = path
else: else:
try: try:
from pydub import AudioSegment as _as from pydub import AudioSegment as as
if ffmpeg != None: if ffmpeg != None:
_as.ffmpeg = ffmpeg as.ffmpeg = ffmpeg
_as.converter = ffmpeg as.converter = ffmpeg
sound = _as.from_file(path, _os.path.splitext(path)[1]) sound = as.from_file(path, os.path.splitext(path)[1])
path = _tf.mkstemp('.wav') path = tempfile.mkstemp('.wav')
sound.export(path, format="wav") sound.export(path, format="wav")
except: except:
print('Set ffmpeg to path so that you don'+\ print('Set ffmpeg to path so that you don'+\
"'t have to convert the file to "+\ "'t have to convert the file to "+\
'".wav". If you have installed, but the error still appears, write down the path to ffmpeg.exe in plugin.ffmpeg.') '".wav". If you have installed, but the error still appears, write down the path to ffmpeg.exe in plugin.ffmpeg.')
_pg.mixer.music.load(path) pygame.mixer.music.load(path)
def play(self, loops=0): def play(self, loops=0):
_pg.mixer.music.play(loops) pygame.mixer.music.play(loops)
def stop(self): def stop(self):
_pg.mixer.music.stop() pygame.mixer.music.stop()
def restart(self): def restart(self):
_pg.mixer.music.rewind() pygame.mixer.music.rewind()
def pause(self): def pause(self):
_pg.mixer.music.pause() pygame.mixer.music.pause()
def release(self): def release(self):
_pg.mixer.music.unpause() pygame.mixer.music.unpause()
def queue(self): def queue(self):
_pg.mixer.music.queue(self._path) pygame.mixer.music.queue(self._path)
def volume(): def volume():
def fget(self): def fget(self):
return _pg.mixer.music.get_volume() return pygame.mixer.music.get_volume()
def fset(self, value): def fset(self, value):
if type(value) == int: if type(value) == int:
_pg.mixer.music.set_volume(value) pygame.mixer.music.set_volume(value)
def fdel(self): def fdel(self):
pass pass
return locals() return locals()
@ -82,10 +82,10 @@ class music:
def pos(): def pos():
def fget(self): def fget(self):
return _pg.mixer.music.get_pos() return pygame.mixer.music.get_pos()
def fset(self, value): def fset(self, value):
if type(value) == int: if type(value) == int:
_pg.mixer.music.set_pos(value) pygame.mixer.music.set_pos(value)
def fdel(self): def fdel(self):
pass pass
return locals() return locals()

View file

@ -1,27 +1,26 @@
from pygwin._pg import pg as _pg import .pygame
import inspect
def getPressed(): def getPressed():
orig = _pg.mouse.get_pressed(3) orig = pygame.mouse.get_pressed(3)
return {'left':orig[0],'middle':orig[1],'right':orig[2]} return {'left':orig[0],'middle':orig[1],'right':orig[2]}
def isPressed(x): def isPressed(x):
return getPressed()[x.lower()] return getPressed()[x.lower()]
def setPosition(x): def setPosition(x):
_pg.mouse.set_pos(x) pygame.mouse.set_pos(x)
def getPosition(): def getPosition():
return _pg.mouse.get_pos() return pygame.mouse.get_pos()
def setVisible(x): def setVisible(x):
_pg.mouse.set_visible(x) pygame.mouse.set_visible(x)
def getVisible(): def getVisible():
return _pg.mouse.get_visible() return pygame.mouse.get_visible()
def getCursor(): def getCursor():
return _pg.mouse.get_cursor() return pygame.mouse.get_cursor()
def setCursor(size, hotspot=None, xormasks=None, andmasks=None): def setCursor(size, hotspot=None, xormasks=None, andmasks=None):
if hotspot == None and xormasks == None and andmasks == None: if hotspot == None and xormasks == None and andmasks == None:
_pg.mouse.set_system_cursor(size) pygame.mouse.set_system_cursor(size)
else: else:
_pg.mouse.set_cursor(size, hotspot, xormasks, andmasks) pygame.mouse.set_cursor(size, hotspot, xormasks, andmasks)
import inspect as _i
_aliases = {'getPressed':['gprs','getbtns'], _aliases = {'getPressed':['gprs','getbtns'],
'isPressed':['isprs','btnprs'], 'isPressed':['isprs','btnprs'],
@ -29,7 +28,7 @@ _aliases = {'getPressed':['gprs','getbtns'],
'getPosition':['gpos','getpos']} 'getPosition':['gpos','getpos']}
for i in _aliases.items(): for i in _aliases.items():
exec(f'args = _i.signature({i[0]})') exec(f'args = inspect.signature({i[0]})')
args = [str(i[1]) for i in dict(args.parameters).items()] args = [str(i[1]) for i in dict(args.parameters).items()]
args = ', '.join(args) args = ', '.join(args)
for i0 in i[1]: for i0 in i[1]:

17
src/pygwin2/pygame.py Normal file
View file

@ -0,0 +1,17 @@
from contextlib import contextmanager
import os
import sys
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
with suppress_stdout():
from pygame import *
init()

View file

@ -1,9 +1,9 @@
from contextlib import contextmanager from contextlib import contextmanager
from pygwin._pg import pg as _pg import .pygame
import moviepy.editor as mpe import moviepy.editor as mpe
from array import array from array import array
from PIL import Image from PIL import Image
import numpy as np import numpy
import threading import threading
import pyautogui import pyautogui
import tempfile import tempfile
@ -76,7 +76,7 @@ class record:
out = cv2.VideoWriter(noaudiopath,self._codec, out = cv2.VideoWriter(noaudiopath,self._codec,
fps,self._surface.size) fps,self._surface.size)
for i in self._frames: for i in self._frames:
frame = np.array(_pg.surfarray.array3d(i).swapaxes(0,1)) frame = numpy.array(pygame.surfarray.array3d(i).swapaxes(0,1))
frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
out.write(frame) out.write(frame)
out.release() out.release()

View file

@ -1,4 +1,4 @@
from pygwin._pg import pg import .pygame
_aliases = {'w':['width'],'h':['height'], _aliases = {'w':['width'],'h':['height'],
'c':['center','middle'], 'c':['center','middle'],
@ -23,7 +23,7 @@ class rect:
self.c = (self.x/2+self.w/2,self.y/2+self.h/2) self.c = (self.x/2+self.w/2,self.y/2+self.h/2)
self.cx, self.cy = self.c self.cx, self.cy = self.c
self.r,self.d = self.x+self.w,self.y+self.h self.r,self.d = self.x+self.w,self.y+self.h
self._rect = pg.Rect(self.x,self.y,self.w,self.h) self._rect = pygame.Rect(self.x,self.y,self.w,self.h)
def __getitem__(self,x): def __getitem__(self,x):
return [self.x,self.y,self.w,self.h][x] return [self.x,self.y,self.w,self.h][x]
def __list__(self): def __list__(self):
@ -51,10 +51,3 @@ class rect:
attr = ma attr = ma
data = self.__dict__[attr] data = self.__dict__[attr]
return data return data
# def fromSurface(surf,x=0,y=0,c=())
#
# # print(dir(property))
# r = rect(123,321,654,987)
# print(r.width)

View file

@ -1,16 +1,11 @@
from pygwin.rect import rect as _r from .rect import rect
from pygwin.color import color as _clr from .color import color
from pygwin._pg import pg as _pg import .pygame
from PIL import Image as _im
import tempfile as _tf
import randstr as _rs
import time as _t
import os as _os
class surface: class surface:
def __init__(self, size): def __init__(self, size):
self._size = size self._size = size
self._orig = _pg.Surface(size, _pg.SRCALPHA) self._orig = pygame.Surface(size, pygame.SRCALPHA)
@property @property
def pixels(self): def pixels(self):
pixels = [] pixels = []
@ -26,9 +21,9 @@ class surface:
return self._orig return self._orig
def rect(self, x=0, y=0, center=[]): def rect(self, x=0, y=0, center=[]):
if center == []: if center == []:
return _r(x, y, self.size[0], self.size[1]) return rect(x, y, self.size[0], self.size[1])
else: else:
return _r(center[0]-(self.size[0]/2), return rect(center[0]-(self.size[0]/2),
center[1]-(self.size[1]/2), center[1]-(self.size[1]/2),
self.size[0], self.size[1]) self.size[0], self.size[1])
def copy(self): def copy(self):
@ -37,12 +32,12 @@ class surface:
surf._surface_size = self._size surf._surface_size = self._size
return surf return surf
def getPixel(self, x, y): def getPixel(self, x, y):
return _clr(*self._orig.get_at((x,y))) return color(*self._orig.get_at((x,y)))
def setPixel(self, x, y, color): def setPixel(self, x, y, color):
self._orig.set_at((x,y),color) self._orig.set_at((x,y),color)
return self.copy() return self.copy()
def blit(self, surf, xy): def blit(self, surf, xy):
if type(surf) != surface and type(surf) != _pg.Surface: if type(surf) != surface and type(surf) != pygame.Surface:
from pygwin.font import defaultFont as _df from pygwin.font import defaultFont as _df
surf = _df.render(surf, 25, (0,0,0)) surf = _df.render(surf, 25, (0,0,0))
try: try:
@ -62,25 +57,25 @@ class surface:
return self.copy() return self.copy()
def scale(self, size, smooth=False): def scale(self, size, smooth=False):
if not smooth: if not smooth:
self._orig = _pg.transform.scale(self._orig, size) self._orig = pygame.transform.scale(self._orig, size)
else: else:
self._orig = _pg.transform.smoothscale(self._orig, size) self._orig = pygame.transform.smoothscale(self._orig, size)
self._size = self._orig.get_size() self._size = self._orig.get_size()
return self.copy() return self.copy()
def rotate(self, angle): def rotate(self, angle):
self._orig = _pg.transform.rotate(self._orig, angle) self._orig = pygame.transform.rotate(self._orig, angle)
self._size = self._orig.get_size() self._size = self._orig.get_size()
return self.copy() return self.copy()
def flip(self, x, y): def flip(self, x, y):
self._orig = _pg.transform.flip(self._orig, x, y) self._orig = pygame.transform.flip(self._orig, x, y)
return self.copy() return self.copy()
def blur(self, amt): def blur(self, amt):
if amt < 0:return self.copy() if amt < 0:return self.copy()
scale = (int(self._orig.get_width()*(amt+1)), scale = (int(self._orig.get_width()*(amt+1)),
int(self._orig.get_height()*(amt+1))) int(self._orig.get_height()*(amt+1)))
size = self._orig.get_size() size = self._orig.get_size()
self._orig = _pg.transform.smoothscale(self._orig,scale) self._orig = pygame.transform.smoothscale(self._orig,scale)
self._orig = _pg.transform.smoothscale(self._orig,size) self._orig = pygame.transform.smoothscale(self._orig,size)
return self.copy() return self.copy()
class _draw: class _draw:
@ -96,7 +91,7 @@ class surface:
orig = self._surf._surface_orig orig = self._surf._surface_orig
except: except:
orig = self._surf._orig orig = self._surf._orig
_pg.draw.rect(orig,color,_pg.Rect(rect[0],rect[1],rect[2],rect[3]), pygame.draw.rect(orig,color,pygame.Rect(rect[0],rect[1],rect[2],rect[3]),
width,borderRadius,borderTopLeftRadius,borderTopRightRadius, width,borderRadius,borderTopLeftRadius,borderTopRightRadius,
borderBottomLeftRadius,borderBottomRightRadius) borderBottomLeftRadius,borderBottomRightRadius)
return self._surf.copy() return self._surf.copy()
@ -105,7 +100,7 @@ class surface:
orig = self._surf._surface_orig orig = self._surf._surface_orig
except: except:
orig = self._surf._orig orig = self._surf._orig
_pg.draw.polygon(orig,color,points,width) pygame.draw.polygon(orig,color,points,width)
return self._surf.copy() return self._surf.copy()
def circle(self,color,center, def circle(self,color,center,
radius,width=0, radius,width=0,
@ -117,7 +112,7 @@ class surface:
orig = self._surf._surface_orig orig = self._surf._surface_orig
except: except:
orig = self._surf._orig orig = self._surf._orig
_pg.draw.circle(orig,color,center,radius, pygame.draw.circle(orig,color,center,radius,
width,drawTopRight,drawTopLeft, width,drawTopRight,drawTopLeft,
drawBottomLeft,drawBottomRight) drawBottomLeft,drawBottomRight)
return self._surf.copy() return self._surf.copy()
@ -126,7 +121,7 @@ class surface:
orig = self._surf._surface_orig orig = self._surf._surface_orig
except: except:
orig = self._surf._orig orig = self._surf._orig
_pg.draw.ellipse(orig,color,_pg.Rect(rect[0], pygame.draw.ellipse(orig,color,pygame.Rect(rect[0],
rect[1],rect[2],rect[3]),width) rect[1],rect[2],rect[3]),width)
return self._surf.copy() return self._surf.copy()
def line(self,color,start,end,width=1): def line(self,color,start,end,width=1):
@ -134,14 +129,14 @@ class surface:
orig = self._surf._surface_orig orig = self._surf._surface_orig
except: except:
orig = self._surf._orig orig = self._surf._orig
_pg.draw.line(orig,color,start,end,width) pygame.draw.line(orig,color,start,end,width)
return self._surf.copy() return self._surf.copy()
def arc(self,color,rect,startAngle,stopAngle,width=1): def arc(self,color,rect,startAngle,stopAngle,width=1):
try: try:
orig = self._surf._surface_orig orig = self._surf._surface_orig
except: except:
orig = self._surf._orig orig = self._surf._orig
_pg.draw.arc(orig,color,_pg.Rect(rect[0], pygame.draw.arc(orig,color,pygame.Rect(rect[0],
rect[1],rect[2],rect[3]), rect[1],rect[2],rect[3]),
startAngle,stopAngle,width) startAngle,stopAngle,width)
return self._surf.copy() return self._surf.copy()

View file

@ -1,8 +1,6 @@
import threading import threading
import wx import wx
import wx.adv import wx.adv
from pygwin._pg import pg
import copy
class tray(wx.adv.TaskBarIcon): class tray(wx.adv.TaskBarIcon):
def __init__(self, tooltip, iconpath): def __init__(self, tooltip, iconpath):
@ -39,7 +37,8 @@ class tray(wx.adv.TaskBarIcon):
id=item.GetId()) id=item.GetId())
self._menu.Append(item) self._menu.Append(item)
def start(self, thread=True): def start(self, thread=True):
cbotld = lambda x:self.onLeftMouseButton() def cbotld(x):
return self.onLeftMouseButton()
self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN,cbotld) self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN,cbotld)
if thread: threading.Thread( if thread: threading.Thread(
target=self._app.MainLoop, target=self._app.MainLoop,

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy
@ -40,12 +40,12 @@ class button(widget):
contains = False contains = False
cacm = False cacm = False
if contains and not self.cl0: if contains and not self.cl0:
_m.setCursor(_pg.SYSTEM_CURSOR_HAND) _m.setCursor(pygame.SYSTEM_CURSOR_HAND)
self.cl0 = True self.cl0 = True
self.nc0 = True self.nc0 = True
elif not contains: elif not contains:
if self.nc0: if self.nc0:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.nc0 = False self.nc0 = False
self.cl0 = False self.cl0 = False
if cacm and not self.cl1: if cacm and not self.cl1:

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy
@ -33,12 +33,12 @@ class checkBox(widget):
contains = False contains = False
cacm = False cacm = False
if contains and not self.cl0: if contains and not self.cl0:
_m.setCursor(_pg.SYSTEM_CURSOR_HAND) _m.setCursor(pygame.SYSTEM_CURSOR_HAND)
self.cl0 = True self.cl0 = True
self.nc0 = True self.nc0 = True
elif not contains: elif not contains:
if self.nc0: if self.nc0:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.nc0 = False self.nc0 = False
self.cl0 = False self.cl0 = False
if cacm and not self.cl1: if cacm and not self.cl1:

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy
@ -104,10 +104,10 @@ class entry(widget):
position[1]).contains(_m.getPosition()[0], position[1]).contains(_m.getPosition()[0],
_m.getPosition()[1]): _m.getPosition()[1]):
if not self.wcl: if not self.wcl:
_m.setCursor(_pg.SYSTEM_CURSOR_HAND) _m.setCursor(pygame.SYSTEM_CURSOR_HAND)
else: else:
if not self.ws: if not self.ws:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.ws = True self.ws = True
if _m.isPressed('left'): if _m.isPressed('left'):
if not self.wcl: if not self.wcl:
@ -118,7 +118,7 @@ class entry(widget):
self.wsnr = False self.wsnr = False
else: else:
if not self.wsnr: if not self.wsnr:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.wsnr = True self.wsnr = True
if _m.isPressed('left'): if _m.isPressed('left'):
self.focus = False self.focus = False
@ -129,7 +129,7 @@ class entry(widget):
text = text.translate(dict(zip(map(ord, text = text.translate(dict(zip(map(ord,
'''qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOPASDFGHJKLZXCVBNM'''), '''qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOPASDFGHJKLZXCVBNM'''),
'''йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗФЫВАПРОЛДЯЧСМИТЬ'''))) '''йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗФЫВАПРОЛДЯЧСМИТЬ''')))
if _pg.key.get_pressed()[_pg.K_LSHIFT] or _pg.key.get_pressed()[_pg.K_RSHIFT]: if pygame.key.get_pressed()[pygame.K_LSHIFT] or pygame.key.get_pressed()[pygame.K_RSHIFT]:
text = text.translate(dict(zip(map(ord, text = text.translate(dict(zip(map(ord,
u'''1234567890-=[]\;',./`'''), u'''1234567890-=[]\;',./`'''),
u'''!@#$%^&*()_+{}|:"<>?~'''))) u'''!@#$%^&*()_+{}|:"<>?~''')))

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy
@ -91,10 +91,10 @@ class keySelect(entry):
position[1]).contains(_m.getPosition()[0], position[1]).contains(_m.getPosition()[0],
_m.getPosition()[1]): _m.getPosition()[1]):
if not self.wcl: if not self.wcl:
_m.setCursor(_pg.SYSTEM_CURSOR_HAND) _m.setCursor(pygame.SYSTEM_CURSOR_HAND)
else: else:
if not self.ws: if not self.ws:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.ws = True self.ws = True
if _m.isPressed('left'): if _m.isPressed('left'):
if not self.wcl: if not self.wcl:
@ -105,7 +105,7 @@ class keySelect(entry):
self.wsnr = False self.wsnr = False
else: else:
if not self.wsnr: if not self.wsnr:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.wsnr = True self.wsnr = True
if _m.isPressed('left'): if _m.isPressed('left'):
self.focus = False self.focus = False

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy
@ -108,10 +108,10 @@ class textarea(widget):
position[1]).contains(_m.getPosition()[0], position[1]).contains(_m.getPosition()[0],
_m.getPosition()[1]): _m.getPosition()[1]):
if not self.wcl: if not self.wcl:
_m.setCursor(_pg.SYSTEM_CURSOR_HAND) _m.setCursor(pygame.SYSTEM_CURSOR_HAND)
else: else:
if not self.ws: if not self.ws:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.ws = True self.ws = True
if _m.isPressed('left'): if _m.isPressed('left'):
if not self.wcl: if not self.wcl:
@ -122,14 +122,14 @@ class textarea(widget):
self.wsnr = False self.wsnr = False
else: else:
if not self.wsnr: if not self.wsnr:
_m.setCursor(_pg.SYSTEM_CURSOR_ARROW) _m.setCursor(pygame.SYSTEM_CURSOR_ARROW)
self.wsnr = True self.wsnr = True
if _m.isPressed('left'): if _m.isPressed('left'):
self.focus = False self.focus = False
def insert(self,text): def insert(self,text):
if _ct.WinDLL("User32.dll").GetKeyState(0x14): if _ct.WinDLL("User32.dll").GetKeyState(0x14):
text = text.upper() text = text.upper()
if _pg.key.get_pressed()[_pg.K_LSHIFT] or _pg.key.get_pressed()[_pg.K_RSHIFT]: if pygame.key.get_pressed()[pygame.K_LSHIFT] or pygame.key.get_pressed()[pygame.K_RSHIFT]:
text = text.translate(dict(zip(map(ord, '''1234567890-=[]\\;'''+"',./`"), text = text.translate(dict(zip(map(ord, '''1234567890-=[]\\;'''+"',./`"),
'''!@#$%^&*()_+{}|:"<>?~'''))) '''!@#$%^&*()_+{}|:"<>?~''')))
if hex(getattr(_ct.windll.LoadLibrary("user32.dll"), if hex(getattr(_ct.windll.LoadLibrary("user32.dll"),

View file

@ -1,10 +1,10 @@
from pygwin._pg import pg as _pg import ...pygame
from pygwin.surface import surface as _s from ...surface import surface as _s
from pygwin.font import defaultFont as _df from ...font import defaultFont as _df
from pygwin.image import load as _l from ...image import load as _l
from pygwin.rect import rect as _r from ...rect import rect as _r
import pygwin.mouse as _m import ...mouse as _m
import pygwin.keyboard as _k import ...keyboard as _k
import ctypes as _ct import ctypes as _ct
import copy as _copy import copy as _copy

201
src/pygwin2/window.py Normal file
View file

@ -0,0 +1,201 @@
from pygwin.surface import surface as _surface
from pygwin.tray import tray as _tray
from datetime import datetime as _dt
from pygwin.image import save as _s
from pygwin.pygame import pg as pygame
try:
import win32job
import win32api
import win32con
import win32gui
import winerror
nonwin = False
except Exception as _:
nonwin = True
import sys
import threading
import mouse
class _win(_surface):
def __init__(self, iconpath=None):
self._orig = pygame.display.get_surface()
super().__init__(self._orig.get_size())
self._orig = pygame.display.get_surface()
self._clock = pygame.time.Clock()
self._withfps = False
self._iconpath = iconpath
self._isallowdrag = False
if iconpath is not None:
self.tray = _tray(self.title,iconpath)
def update(self, fps=-1):
if fps != -1:
self._clock.tick(fps)
self._withfps = True
pygame.display.update()
def resize(self, size=None):
if size is None:
return self.size
else:
self._orig = pygame.display.set_mode(size)
def title():
def fget(self):
return pygame.display.get_caption()[0]
def fset(self, value):
if type(value) is str:
return
pygame.display.set_caption(value)
def fdel(self):
pass
return locals()
title = property(**title())
def icon(self, value):
pygame.display.set_icon(pygame.image.load(value))
self._iconpath = value
def size():
def fget(self):
return pygame.display.get_window_size()
def fset(self, value):
if type(value) in [list,tuple]:
return
pygame.display.set_mode(value)
def fdel(self):
pass
return locals()
size = property(**size())
def fullscreen(self):
pygame.display.toogle_fullscreen()
def close(self):
# win32gui.PostMessage(self.hwnd, win32con.WM_CLOSE, 0, 0)
pygame.display.quit()
try:
self.tray.stop()
except Exception as _:
pass
def focus(self):
if not nonwin:
self.hide()
self.show()
win32gui.BringWindowToTop(self.hwnd)
win32gui.ShowWindow(self.hwnd, win32con.SW_SHOWNORMAL)
win32gui.SetForegroundWindow(self.hwnd)
def hide(self):
if not nonwin:
win32gui.ShowWindow(self.hwnd, win32con.SW_HIDE)
def show(self):
if not nonwin:
win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)
def move(self, x, y):
if not nonwin:
rect = self._getRect()
win32gui.MoveWindow(self.hwnd, int(x), int(y),
rect[2]-x, rect[3]-y, 0)
def screenshot(self, path):
_s(self._orig, path)
return path
def center(self,x=pygame.display.get_desktop_sizes()[0][0]/2,
y=pygame.display.get_desktop_sizes()[0][1]/2):
self.move(x-self.size[0]/2,y-self.size[1]/2)
def _getRect(self):
if not nonwin:
return win32gui.GetWindowRect(self.hwnd)
def denyDrag(self):
if not nonwin:
self._isallowdrag = True
def loop(self):
while self._isallowdrag:
pos = mouse.get_position()
pos = [pos[i]-self.position[i] for i in range(2)]
if pos[0] < self._getRect()[2]-137:
if pos[1] < 30:
mouse.release('left')
threading.Thread(target=lambda:loop(self),daemon=1).start()
def allowDrag(self):
if not nonwin:
self._isallowdrag = False
@property
def position(self):
if not nonwin:
rect = self._getRect()
x = rect[0]
y = rect[1]
return (x, y)
@property
def rawFps(self):
if self._withfps:
return self._clock.get_fps()
else:
return float(f'2010.{_dt.now().year}')
@property
def fps(self):
return int(self.rawFps)
@property
def hwnd(self):
if not nonwin:
return pygame.display.get_wm_info()['window']
@property
def visible(self):
if not nonwin:
return win32gui.IsWindowVisible(self._win)
def create(title=None, size=(0,0), icon=None, resizable=False, noframe=False):
pygame.display.set_mode(size)
if resizable:
pygame.display.set_mode(size,pygame.RESIZABLE)
if noframe:
pygame.display.set_mode(size,pygame.NOFRAME)
else:
if title is not None:
pygame.display.set_caption(title)
if icon is not None:
pygame.display.set_icon(pygame.image.load(icon))
return _win(icon)
def ramLimit(memory_limit):
if not nonwin:
g_hjob = None
def create_job(job_name='', breakaway='silent'):
hjob = win32job.CreateJobObject(None, job_name)
if breakaway:
info = win32job.QueryInformationJobObject(hjob,
win32job.JobObjectExtendedLimitInformation)
if breakaway == 'silent':
info['BasicLimitInformation']['LimitFlags'] |= (
win32job.JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK)
else:
info['BasicLimitInformation']['LimitFlags'] |= (
win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK)
win32job.SetInformationJobObject(hjob,
win32job.JobObjectExtendedLimitInformation, info)
return hjob
def assign_job(hjob):
if nonwin:
return
global g_hjob
hprocess = win32api.GetCurrentProcess()
try:
win32job.AssignProcessToJobObject(hjob, hprocess)
g_hjob = hjob
except win32job.error as e:
if (e._we != winerror.ERROR_ACCESS_DENIED or
sys.getwindowsversion() >= (6, 2) or
not win32job.IsProcessInJob(hprocess, None)):
raise
def limit_memory(memory_limit):
if g_hjob is None:
return
info = win32job.QueryInformationJobObject(g_hjob,
win32job.JobObjectExtendedLimitInformation)
info['ProcessMemoryLimit'] = memory_limit
info['BasicLimitInformation']['LimitFlags'] |= (
win32job.JOB_OBJECT_LIMIT_PROCESS_MEMORY)
win32job.SetInformationJobObject(g_hjob,
win32job.JobObjectExtendedLimitInformation, info)
assign_job(create_job())
limit_memory(memory_limit)
def close():
pygame.quit()
quit()
def getEvents():
return pygame.event.get()