diff --git a/examples/game.py b/examples/game.py index f0d72e7..2216fee 100644 --- a/examples/game.py +++ b/examples/game.py @@ -1,48 +1,50 @@ -import pygwin # Importing pygwin -import random # Importing random +import pygwin # Importing pygwin +import random # Importing random -win = pygwin.create('A Simple Game', (500,500)) # Creating window +win = pygwin.create("A Simple Game", (500, 500)) # Creating window -player = [250,250] # Player position -apple = pygwin.rect(random.randint(0,490), - random.randint(0,490),20,20) # Apple rect -score = 0 # Player score +player = [250, 250] # Player position +apple = pygwin.rect( + random.randint(0, 490), random.randint(0, 490), 20, 20 +) # Apple rect +score = 0 # Player score -run = True # Is loop running -while run: # Creating loop - for event in pygwin.getEvents(): # Events loop - if event.type == pygwin.QUIT: # If window quit - run = False # Break loop - win.fill((255,255,255)) # Fill window with color +run = True # Is loop running +while run: # Creating loop + for event in pygwin.getEvents(): # Events loop + if event.type == pygwin.QUIT: # If window quit + run = False # Break loop + win.fill((255, 255, 255)) # Fill window with color - win.blit(score,(0,0)) # Writing player score + win.blit(score, (0, 0)) # Writing player score - if pygwin.keyboard.isPressed('w'): # If keyboard key w pressed - player[1] -= 5 # Player position up - if pygwin.keyboard.isPressed('s'): # If keyboard key s pressed - player[1] += 5 # Player position down - if pygwin.keyboard.isPressed('d'): # If keyboard key d pressed - player[0] += 5 # Player position right - if pygwin.keyboard.isPressed('a'): # If keyboard key a pressed - player[0] -= 5 # Player position left + if pygwin.keyboard.isPressed("w"): # If keyboard key w pressed + player[1] -= 5 # Player position up + if pygwin.keyboard.isPressed("s"): # If keyboard key s pressed + player[1] += 5 # Player position down + if pygwin.keyboard.isPressed("d"): # If keyboard key d pressed + player[0] += 5 # Player position right + if pygwin.keyboard.isPressed("a"): # If keyboard key a pressed + player[0] -= 5 # Player position left - if player[0] <= -10: # If player out of the screen (left) - player[0] = 510 # Set player position in right - if player[1] <= -10: # If player out of the screen (up) - player[1] = 510 # Set player position in down - if player[0] > 510: # If player out of the screen (right) - player[0] = -10 # Set player position in left - if player[1] > 510: # If player out of the screen (down) - player[1] = -10 # Set player position in up + if player[0] <= -10: # If player out of the screen (left) + player[0] = 510 # Set player position in right + if player[1] <= -10: # If player out of the screen (up) + player[1] = 510 # Set player position in down + if player[0] > 510: # If player out of the screen (right) + player[0] = -10 # Set player position in left + if player[1] > 510: # If player out of the screen (down) + player[1] = -10 # Set player position in up - playerRect = pygwin.rect(player[0]-10,player[1]-10,20,20) # Player rect - win.draw.rect((0,0,0),playerRect) # Drawing player rect - win.draw.rect((200,50,50),apple) # Drawing apple rect + playerRect = pygwin.rect(player[0] - 10, player[1] - 10, 20, 20) # Player rect + win.draw.rect((0, 0, 0), playerRect) # Drawing player rect + win.draw.rect((200, 50, 50), apple) # Drawing apple rect - if playerRect.collide(apple): # If player rect collide apple rect - apple = pygwin.rect(random.randint(0,490), - random.randint(0,490),20,20) # Change apple rect - score += 1 # Update player score + if playerRect.collide(apple): # If player rect collide apple rect + apple = pygwin.rect( + random.randint(0, 490), random.randint(0, 490), 20, 20 + ) # Change apple rect + score += 1 # Update player score - win.update(60) # Update window -pygwin.close() # Close pygwin + win.update(60) # Update window +pygwin.close() # Close pygwin diff --git a/examples/record.py b/examples/record.py index ba910fb..2f1c6f3 100644 --- a/examples/record.py +++ b/examples/record.py @@ -1,37 +1,36 @@ import pygwin import random -win = pygwin.create('A Simple Game', (500,500)) +win = pygwin.create("A Simple Game", (500, 500)) -player = [250,250] -apple = pygwin.rect(random.randint(0,490), - random.randint(0,490),20,20) +player = [250, 250] +apple = pygwin.rect(random.randint(0, 490), random.randint(0, 490), 20, 20) score = 0 -record = pygwin.record(win,True) # Init recording -record.start() # Start recording +record = pygwin.record(win, True) # Init recording +record.start() # Start recording run = True while run: for event in pygwin.getEvents(): if event.type == pygwin.QUIT: run = False - record.stop() # Stop recording - win.fill((255,255,255)) + record.stop() # Stop recording + win.fill((255, 255, 255)) - playerRect = pygwin.rect(player[0]-10,player[1]-10,20,20) - win.draw.rect((0,0,0),playerRect) - win.draw.rect((200,50,50),apple) + playerRect = pygwin.rect(player[0] - 10, player[1] - 10, 20, 20) + win.draw.rect((0, 0, 0), playerRect) + win.draw.rect((200, 50, 50), apple) - win.blit(score,(0,0)) + win.blit(score, (0, 0)) - if pygwin.keyboard.isPressed('w'): + if pygwin.keyboard.isPressed("w"): player[1] -= 5 - if pygwin.keyboard.isPressed('s'): + if pygwin.keyboard.isPressed("s"): player[1] += 5 - if pygwin.keyboard.isPressed('d'): + if pygwin.keyboard.isPressed("d"): player[0] += 5 - if pygwin.keyboard.isPressed('a'): + if pygwin.keyboard.isPressed("a"): player[0] -= 5 if player[0] <= -10: @@ -44,10 +43,9 @@ while run: player[1] = -10 if playerRect.collide(apple): - apple = pygwin.rect(random.randint(0,490), - random.randint(0,490),20,20) + apple = pygwin.rect(random.randint(0, 490), random.randint(0, 490), 20, 20) score += 1 win.update(60) -record.render('Recording.mp4') # Render recording +record.render("Recording.mp4") # Render recording pygwin.close() diff --git a/examples/template.py b/examples/template.py index c75cb47..ecf015b 100644 --- a/examples/template.py +++ b/examples/template.py @@ -1,6 +1,6 @@ import pygwin -win = pygwin.create('Title',(500,500)) +win = pygwin.create("Title", (500, 500)) run = True while run: diff --git a/examples/ui.py b/examples/ui.py index efe5ed1..03cce5c 100644 --- a/examples/ui.py +++ b/examples/ui.py @@ -1,43 +1,47 @@ import pygwin -win = pygwin.create('UI example',(270,350)) -base = pygwin.ui.base(win) # Creating ui base +win = pygwin.create("UI example", (270, 350)) +base = pygwin.ui.base(win) # Creating ui base -lbl = pygwin.ui.label('Label') # Creating label -base.put(lbl,(130-(lbl.surface.size[0]/2),10)) # Putting label to base -base.put(pygwin.ui.button('Button',width=250),(10,50)) # Putting button to base -base.put(pygwin.ui.entry('Entry',width=123),(10,100)) # Putting entry to base -base.put(pygwin.ui.keySelect('Key',width=122),(138,100)) # Putting key selector to base -loadbar = pygwin.ui.loadingBar(250,25) # Creating loading bar -base.put(loadbar,(10,150)) # Putting loading bar to base -slider = pygwin.ui.slider(250) # Creating slider -base.put(slider,(10,170)) # Putting slider to base -cb = pygwin.ui.checkBox(25,borderWidth=2) # Creating checkbox -base.put(cb,(10,220)) # Putting checkbox to base -base.put(pygwin.ui.label('Checkbox',20),(45,225)) # Putting checkbox label to base -ta = pygwin.ui.textarea('Textarea',width=250,maxSymbols=20) # Creating textarea -ta.text += '0123456789\n0123456789' # Set text to textarea -ta.focus = True # Focus textarea -ta._generate() # Generate textarea surface -ta.focus = False # Unfocus textarea -base.put(ta,(10,255)) # Putting textarea to base -tta = pygwin.ui.tip('textarea', - *ta.surface.size, - waitBeforeShowing=30) # Creating textarea tip -base.put(tta,(10,255)) # Putting textarea tip to base +lbl = pygwin.ui.label("Label") # Creating label +base.put(lbl, (130 - (lbl.surface.size[0] / 2), 10)) # Putting label to base +base.put(pygwin.ui.button("Button", width=250), (10, 50)) # Putting button to base +base.put(pygwin.ui.entry("Entry", width=123), (10, 100)) # Putting entry to base +base.put( + pygwin.ui.keySelect("Key", width=122), (138, 100) +) # Putting key selector to base +loadbar = pygwin.ui.loadingBar(250, 25) # Creating loading bar +base.put(loadbar, (10, 150)) # Putting loading bar to base +slider = pygwin.ui.slider(250) # Creating slider +base.put(slider, (10, 170)) # Putting slider to base +cb = pygwin.ui.checkBox(25, borderWidth=2) # Creating checkbox +base.put(cb, (10, 220)) # Putting checkbox to base +base.put(pygwin.ui.label("Checkbox", 20), (45, 225)) # Putting checkbox label to base +ta = pygwin.ui.textarea("Textarea", width=250, maxSymbols=20) # Creating textarea +ta.text += "0123456789\n0123456789" # Set text to textarea +ta.focus = True # Focus textarea +ta._generate() # Generate textarea surface +ta.focus = False # Unfocus textarea +base.put(ta, (10, 255)) # Putting textarea to base +tta = pygwin.ui.tip( + "textarea", *ta.surface.size, waitBeforeShowing=30 +) # Creating textarea tip +base.put(tta, (10, 255)) # Putting textarea tip to base run = True while run: for event in pygwin.getEvents(): if event.type == pygwin.QUIT: run = False - base.draw() # Drawing base - if cb.get(): # If checkbox - loadbar.set(slider.get()) # If checkbox + base.draw() # Drawing base + if cb.get(): # If checkbox + loadbar.set(slider.get()) # If checkbox else: - loadbar.step() # Step loading bar - if loadbar.get() == loadbar.length: # If loading bar is full - loadbar.set(0) # Reset loading bar - tta.responceWidth,tta.responceHeight=ta.surface.size # Set responce width, height to textarea tip + loadbar.step() # Step loading bar + if loadbar.get() == loadbar.length: # If loading bar is full + loadbar.set(0) # Reset loading bar + tta.responceWidth, tta.responceHeight = ( + ta.surface.size + ) # Set responce width, height to textarea tip win.update(30) pygwin.close() diff --git a/examples/window-move.py b/examples/window-move.py index 1216b55..ea8aae6 100644 --- a/examples/window-move.py +++ b/examples/window-move.py @@ -1,13 +1,12 @@ import pygwin import random -win = pygwin.create('A Simple Game', (500,500)) -win.denyDrag() # Prohibit dragging the window -start_pos = win.position # Start window pos +win = pygwin.create("A Simple Game", (500, 500)) +win.denyDrag() # Prohibit dragging the window +start_pos = win.position # Start window pos -player = [250,250] -apple = pygwin.rect(random.randint(0,490), - random.randint(0,490),20,20) +player = [250, 250] +apple = pygwin.rect(random.randint(0, 490), random.randint(0, 490), 20, 20) score = 0 run = True @@ -15,38 +14,45 @@ while run: for event in pygwin.getEvents(): if event.type == pygwin.QUIT: run = False - win.fill((255,255,255)) + win.fill((255, 255, 255)) - win.blit(score,(0,0)) + win.blit(score, (0, 0)) set_position = list(win.position) - if pygwin.keyboard.isPressed('w'): + if pygwin.keyboard.isPressed("w"): player[1] -= 5 - set_position[1] -= 5 # Move window up - if pygwin.keyboard.isPressed('s'): + set_position[1] -= 5 # Move window up + if pygwin.keyboard.isPressed("s"): player[1] += 5 - set_position[1] += 5 # Move window down - if pygwin.keyboard.isPressed('d'): + set_position[1] += 5 # Move window down + if pygwin.keyboard.isPressed("d"): player[0] += 5 - set_position[0] += 5 # Move window right - if pygwin.keyboard.isPressed('a'): + set_position[0] += 5 # Move window right + if pygwin.keyboard.isPressed("a"): player[0] -= 5 - set_position[0] -= 5 # Move window left - win.move(*set_position) # Set position + set_position[0] -= 5 # Move window left + win.move(*set_position) # Set position - playerRect = pygwin.rect(player[0]-10,player[1]-10,20,20) - playerRect.x += start_pos[0]-win.position[0] # Set player rect x pos relatively start window position - playerRect.y += start_pos[1]-win.position[1] # Set player rect y pos relatively start window position - win.draw.rect((0,0,0),playerRect) + playerRect = pygwin.rect(player[0] - 10, player[1] - 10, 20, 20) + playerRect.x += ( + start_pos[0] - win.position[0] + ) # Set player rect x pos relatively start window position + playerRect.y += ( + start_pos[1] - win.position[1] + ) # Set player rect y pos relatively start window position + win.draw.rect((0, 0, 0), playerRect) - atemp = apple.copy() # Create copy of apple rect - atemp.x += start_pos[0]-win.position[0] # Set apple x pos relatively start window position - atemp.y += start_pos[1]-win.position[1] # Set apple y pos relatively start window position - win.draw.rect((200,50,50),atemp) + atemp = apple.copy() # Create copy of apple rect + atemp.x += ( + start_pos[0] - win.position[0] + ) # Set apple x pos relatively start window position + atemp.y += ( + start_pos[1] - win.position[1] + ) # Set apple y pos relatively start window position + win.draw.rect((200, 50, 50), atemp) if atemp.collide(playerRect): - apple = pygwin.rect(random.randint(50,490), - random.randint(50,490),20,20) + apple = pygwin.rect(random.randint(50, 490), random.randint(50, 490), 20, 20) score += 1 win.update(60) diff --git a/src/pygwin2/__init__.py b/src/pygwin2/__init__.py index a096035..524692b 100644 --- a/src/pygwin2/__init__.py +++ b/src/pygwin2/__init__.py @@ -1,16 +1,32 @@ -import .pygame -from pygame.locals import * +__all__ = [ + "pygame", + "tray", + "rect", + "surface", + "console", + "color", + "keyboard", + "mouse", + "mixer", + "image", + "font", + "ui", +] + +from . import pygame +from .pygame.locals import * from .tray import tray from .rect import rect from .surface import surface from .console import console from .color import color from .window import * -import .keyboard -import .mouse -import .image -import .mixer -import .font -import .ui -import .gamepad as _gp +from . import keyboard +from . import mouse +from . import image +from . import mixer +from . import font +from . import ui +from . import gamepad as _gp + gamepad = _gp.gamepad(pygame) diff --git a/src/pygwin2/color.py b/src/pygwin2/color.py index db99f34..45c711e 100644 --- a/src/pygwin2/color.py +++ b/src/pygwin2/color.py @@ -1,27 +1,34 @@ class color: - def __init__(self,r,g=None,b=None,a=255): + def __init__(self, r, g=None, b=None, a=255): try: - r,g,b = tuple(int(r[i:i+2],16)for i in(0,2,4)) - except: + r, g, b = tuple(int(r[i : i + 2], 16) for i in (0, 2, 4)) + except Exception as _: pass self.r = r self.g = g self.b = b self.a = a + def hex(self): - return '%02x%02x%02x' % (self.r,self.g,self.b) + return "%02x%02x%02x" % (self.r, self.g, self.b) + def rgb(self): - return (self.r,self.g,self.b,self.a) + return (self.r, self.g, self.b, self.a) + def inverse(self): - return color(255-self.r,255-self.g, - 255-self.b,255-self.a) - def __getitem__(self,x): - return [self.r,self.g,self.b,self.a][x] + return color(255 - self.r, 255 - self.g, 255 - self.b, 255 - self.a) + + def __getitem__(self, x): + return [self.r, self.g, self.b, self.a][x] + def __list__(self): - return [self.r,self.g,self.b,self.a] + return [self.r, self.g, self.b, self.a] + def __tuple__(self): return self.rgb() + def __repr__(self): return self.__str__() + def __str__(self): - return f'({",".join(str(i)for i in self.__list__())})' + return f"({','.join(str(i) for i in self.__list__())})" diff --git a/src/pygwin2/console.py b/src/pygwin2/console.py index ba48737..5e49e6b 100644 --- a/src/pygwin2/console.py +++ b/src/pygwin2/console.py @@ -1,21 +1,26 @@ -import .pygame +from . import pygame + try: import win32console import win32con import win32gui + nonwin = False -except: +except Exception as _: nonwin = True import pyautogui + class console: def __init__(self): if not nonwin: self._hwnd = win32console.GetConsoleWindow() + @property def hwnd(self): if not nonwin: return self._hwnd + def focus(self): if not nonwin: self.hide() @@ -23,63 +28,86 @@ class console: 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: win32gui.SetWindowPos(self.hwnd, x, y, self.size[0], self.size[1]) + def resize(self, width, height): if not nonwin: - win32gui.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): if not nonwin: - win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE) + win32gui.ShowWindow(self.hwnd, win32con.SW_MINIMIZE) return self.size + def maximize(self): if not nonwin: - win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE) + win32gui.ShowWindow(self.hwnd, win32con.SW_MAXIMIZE) return self.size + def title(): def fget(self): if not nonwin: return win32console.GetConsoleTitle() + def fset(self, value): if not nonwin: win32console.SetConsoleTitle(str(value)) + def fdel(self): pass + return locals() + title = property(**title()) - def center(self,x=pygame.display.get_desktop_sizes()[0][0]/2, - y=pygame.display.get_desktop_sizes()[0][1]/2): + + def center( + self, + x=pygame.display.get_desktop_sizes()[0][0] / 2, + y=pygame.display.get_desktop_sizes()[0][1] / 2, + ): 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 def visible(self): if not nonwin: return win32gui.IsWindowVisible(self.hwnd) + @property def position(self): if not nonwin: rect = win32gui.GetWindowRect(self.hwnd) - x = rect[0]+7 + x = rect[0] + 7 y = rect[1] return (x, y) + @property def size(self): if not nonwin: rect = win32gui.GetWindowRect(self.hwnd) - w = rect[2] - self.position[0]-7 - h = rect[3] - self.position[1]-7 + w = rect[2] - self.position[0] - 7 + h = rect[3] - self.position[1] - 7 return (w, h) + def screenshot(self, path): if not nonwin: - rect = self.position+self.size + rect = self.position + self.size self.focus() pyautogui.screenshot(path, region=rect) return path + + console = console() diff --git a/src/pygwin2/font.py b/src/pygwin2/font.py index afeeba0..0750e75 100644 --- a/src/pygwin2/font.py +++ b/src/pygwin2/font.py @@ -1,22 +1,38 @@ from .surface import surface -import .pygame +from . import pygame + class font: def __init__(self, path): self._path = path + def _font(self, size): - return pygame.font.Font(self._path,size) - def render(self, text, size, color, newLineSpace=5, - italic=False, bold=False, underline=False): + return pygame.font.Font(self._path, size) + + def render( + self, + text, + size, + color, + newLineSpace=5, + italic=False, + bold=False, + underline=False, + ): text = str(text) font = self._font(size) font.set_italic(italic) font.set_bold(bold) font.set_underline(underline) - if text.replace('\n', '') != text: - text = text.split('\n') - surf = pygame.Surface([font.size(max(text,key=lambda x:font.size(x)[0]))[0], - (font.size('123')[1]+newLineSpace)*len(text)],pygame.SRCALPHA) + if text.replace("\n", "") != text: + text = text.split("\n") + surf = pygame.Surface( + [ + font.size(max(text, key=lambda x: font.size(x)[0]))[0], + (font.size("123")[1] + newLineSpace) * len(text), + ], + pygame.SRCALPHA, + ) y = 0 for i in text: r = font.render(i, True, color) @@ -26,18 +42,27 @@ class font: y += newLineSpace else: surf = font.render(text, True, color) - surface = surface(surf.get_size()) - surface._surface_orig = surf - return surface - def size(self, text, size, newLineSpace=5, - italic=False,bold=False,underline=False): - return self.render(text, size, (255,255,255), - newLineSpace=newLineSpace, - italic=italic, bold=bold, - underline=underline).size + surface2 = surface(surf.get_size()) + surface2._surface_orig = surf + return surface2 + + def size( + self, text, size, newLineSpace=5, italic=False, bold=False, underline=False + ): + return self.render( + text, + size, + (255, 255, 255), + newLineSpace=newLineSpace, + italic=italic, + bold=bold, + underline=underline, + ).size + class sysFont(font): def __init__(self, name): self._path = pygame.font.match_font(name) + defaultFont = font(pygame.font.get_default_font()) diff --git a/src/pygwin2/gamepad.py b/src/pygwin2/gamepad.py index 8173df4..7bf34ff 100644 --- a/src/pygwin2/gamepad.py +++ b/src/pygwin2/gamepad.py @@ -3,111 +3,121 @@ import threading as _threading class gamepad: def __init__(self, pygame): - self._lasty = '' - self._lastx = '' + self._lasty = "" + self._lastx = "" self.founded = False - self._buttons = {'left-joystick': False, - 'right-joystick': False, - 'north': False, - 'south': False, - 'west': False, - 'east': False, - 'l1': False, - 'l2': False, - 'r1': False, - 'r2': False, - 'up': False, - 'down': False, - 'left': False, - 'right': False, - 'start': False, - 'select': False} + self._buttons = { + "left-joystick": False, + "right-joystick": False, + "north": False, + "south": False, + "west": False, + "east": False, + "l1": False, + "l2": False, + "r1": False, + "r2": False, + "up": False, + "down": False, + "left": False, + "right": False, + "start": False, + "select": False, + } self.leftJoystick = [0, 0] self.rightJoystick = [0, 0] self._pygame = pygame self._start() + def _tick(self): try: events = _inputs.get_gamepad() - except: + except Exception as _: return if not self._pygame.display.get_active(): return self.founded = True if events: for event in events: - if event.code == 'ABS_X': + if event.code == "ABS_X": self.leftJoystick[0] = event.state - elif event.code == 'ABS_Y': + elif event.code == "ABS_Y": self.leftJoystick[1] = event.state - elif event.code == 'ABS_RY': + elif event.code == "ABS_RY": self.rightJoystick[1] = event.state - elif event.code == 'ABS_RX': + elif event.code == "ABS_RX": self.rightJoystick[0] = event.state - elif event.code == 'BTN_THUMBL': - self._buttons['left-joystick'] = event.state - elif event.code == 'BTN_THUMBR': - self._buttons['right-joystick'] = event.state - elif event.code == 'BTN_TL': - self._buttons['l1'] = event.state - elif event.code == 'BTN_TR': - self._buttons['r1'] = event.state - elif event.code == 'ABS_Z': + elif event.code == "BTN_THUMBL": + self._buttons["left-joystick"] = event.state + elif event.code == "BTN_THUMBR": + self._buttons["right-joystick"] = event.state + elif event.code == "BTN_TL": + self._buttons["l1"] = event.state + elif event.code == "BTN_TR": + self._buttons["r1"] = event.state + elif event.code == "ABS_Z": if event.state == 255: - self._buttons['l2'] = 1 + self._buttons["l2"] = 1 elif event.state == 0: - self._buttons['l2'] = 0 - elif event.code == 'ABS_RZ': + self._buttons["l2"] = 0 + elif event.code == "ABS_RZ": if event.state == 255: - self._buttons['r2'] = 1 + self._buttons["r2"] = 1 elif event.state == 0: - self._buttons['r2'] = 0 - elif event.code == 'BTN_WEST': - self._buttons['west'] = event.state - elif event.code == 'BTN_NORTH': - self._buttons['north'] = event.state - elif event.code == 'BTN_EAST': - self._buttons['east'] = event.state - elif event.code == 'BTN_SOUTH': - self._buttons['south'] = event.state - elif event.code == 'ABS_HAT0Y': + self._buttons["r2"] = 0 + elif event.code == "BTN_WEST": + self._buttons["west"] = event.state + elif event.code == "BTN_NORTH": + self._buttons["north"] = event.state + elif event.code == "BTN_EAST": + self._buttons["east"] = event.state + elif event.code == "BTN_SOUTH": + self._buttons["south"] = event.state + elif event.code == "ABS_HAT0Y": if event.state == 1: - self._buttons['down'] = True - self._lasty = 'down' + self._buttons["down"] = True + self._lasty = "down" elif event.state == -1: - self._buttons['up'] = True - self._lasty = 'up' + self._buttons["up"] = True + self._lasty = "up" else: self._buttons[self._lasty] = False - elif event.code == 'ABS_HAT0X': + elif event.code == "ABS_HAT0X": if event.state == 1: - self._buttons['right'] = True - self._lastx = 'right' + self._buttons["right"] = True + self._lastx = "right" elif event.state == -1: - self._buttons['left'] = True - self._lastx = 'left' + self._buttons["left"] = True + self._lastx = "left" else: self._buttons[self._lastx] = False - elif event.code == 'BTN_START': - self._buttons['select'] = event.state - elif event.code == 'BTN_SELECT': - self._buttons['start'] = event.state + elif event.code == "BTN_START": + self._buttons["select"] = event.state + elif event.code == "BTN_SELECT": + self._buttons["start"] = event.state + def _start(self): self.founded = False self._started = True + def ttcb(self): while self._started: self._tick() - _threading.Thread(target=lambda:ttcb(self),daemon=True).start() + + _threading.Thread(target=lambda: ttcb(self), daemon=True).start() + def close(self): self._started = False + def isPressed(self, btn): return btn in self._buttons + def reset(self): - self._lasty = '' - self._lastx = '' + self._lasty = "" + self._lastx = "" self._buttons = [] self.leftJoystick = [0, 0] self.rightJoystick = [0, 0] + def getPressed(self): return self._buttons diff --git a/src/pygwin2/image.py b/src/pygwin2/image.py index 2ea306b..478f635 100644 --- a/src/pygwin2/image.py +++ b/src/pygwin2/image.py @@ -1,4 +1,4 @@ -import .pygame +from . import pygame from .surface import surface from PIL import Image import tempfile @@ -6,37 +6,45 @@ import pickle import bz2 import os + def load(path): - if path.endswith('.gif'): + if path.endswith(".gif"): im = Image.open(path) with tempfile.TemporaryDirectory() as td: surfs = [] for i in range(im.n_frames): im.seek(i) - p = os.path.join(td,f'{i}.png') + p = os.path.join(td, f"{i}.png") im.save(p) s = pygame.image.load(p) os.remove(p) sg = surface(s.get_size()) - sg.blit(s,(0,0)) + sg.blit(s, (0, 0)) surfs.append(sg) return surfs else: - im = Image.open(path.encode('utf8').decode('utf8')) - image = pygame.image.fromstring(im.tobytes(),im.size,im.mode) + im = Image.open(path.encode("utf8").decode("utf8")) + image = pygame.image.fromstring(im.tobytes(), im.size, im.mode) surf = surface(im.size) - surf.blit(image,(0,0)) + surf.blit(image, (0, 0)) return surf -def save(surface, dest): - pygame.image.save_extended(surface._grp(), dest) -def toBytes(surface): - return bz2.compress(pickle.dumps([pygame.image.tostring(surface._grp(),"RGBA"),list(surface.size)])) +def save(surf, dest): + pygame.image.save_extended(surf._grp(), dest) + + +def toBytes(surf): + return bz2.compress( + pickle.dumps( + [pygame.image.tostring(surf._grp(), "RGBA"), list(surf.size)] + ) + ) + def fromBytes(bytes): string = pickle.loads(bz2.decompress(bytes)) - surf = pygame.image.fromstring(string[0],tuple(string[1]),"RGBA") - surface = surface(tuple(string[1])) - surface.blit(surf,(0,0)) - return surface + surf = pygame.image.fromstring(string[0], tuple(string[1]), "RGBA") + surface2 = surface(tuple(string[1])) + surface2.blit(surf, (0, 0)) + return surface2 diff --git a/src/pygwin2/keyboard.py b/src/pygwin2/keyboard.py index bdbc0b3..a222b12 100644 --- a/src/pygwin2/keyboard.py +++ b/src/pygwin2/keyboard.py @@ -1,22 +1,13 @@ -import .pygame +from . import pygame + def getPressed(): fkeys = {} keys = pygame.key.get_pressed() for i in range(len(keys)): - fkeys.update({pygame.key.name(i):keys[i]}) + fkeys.update({pygame.key.name(i): keys[i]}) return fkeys + + def isPressed(key): return getPressed()[key] - -import inspect - -_aliases = {'getPressed':['gprs','getkeys'], - 'isPressed':['isprs','keyprs']} - -for i in _aliases.items(): - exec(f'args = inspect.signature({i[0]})') - args = [str(i[1]) for i in dict(args.parameters).items()] - args = ', '.join(args) - for i0 in i[1]: - exec(f"def {i0}({args}):return {i[0]}({args})") diff --git a/src/pygwin2/mixer.py b/src/pygwin2/mixer.py index 7b08cfe..b812a23 100644 --- a/src/pygwin2/mixer.py +++ b/src/pygwin2/mixer.py @@ -1,92 +1,122 @@ -import .pygame +from . import pygame import os import tempfile ffmpeg = None + class sound: def __init__(self, path): - if not (path.endswith('.wav') or path.endswith('.ogg')): + if not (path.endswith(".wav") or path.endswith(".ogg")): try: - from pydub import AudioSegment as as - if ffmpeg != None: - as.ffmpeg = ffmpeg - as.converter = ffmpeg - sound = as.from_file(path, os.path.splitext(path)[1]) - path = tempfile.mkstemp('.wav') + from pydub import AudioSegment + + if ffmpeg is not None: + AudioSegment.ffmpeg = ffmpeg + AudioSegment.converter = ffmpeg + sound = AudioSegment.from_file(path, os.path.splitext(path)[1]) + path = tempfile.mkstemp(".wav") sound.export(path, format="wav") - except: - print('Set ffmpeg to path so that you don'+\ - "'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.') + except Exception as _: + print( + "Set ffmpeg to path so that you don" + + "'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.' + ) self._sound = pygame.mixer.Sound(path) + def play(self): self._sound.play() + def stop(self): self._sound.stop() + def volume(): def fget(self): return self._sound.get_volume() + def fset(self, value): - if type(value) == int: + if type(value) is int: self._sound.set_volume(value) + def fdel(self): pass + return locals() + volume = property(**volume()) + @property def length(self): return self._sound.get_length() + class music: def __init__(self, path): - if path.endswith('.wav') or path.endswith('.ogg'): + if path.endswith(".wav") or path.endswith(".ogg"): self._path = path else: try: - from pydub import AudioSegment as as - if ffmpeg != None: - as.ffmpeg = ffmpeg - as.converter = ffmpeg - sound = as.from_file(path, os.path.splitext(path)[1]) - path = tempfile.mkstemp('.wav') + from pydub import AudioSegment + + if ffmpeg is not None: + AudioSegment.ffmpeg = ffmpeg + AudioSegment.converter = ffmpeg + sound = AudioSegment.from_file(path, os.path.splitext(path)[1]) + path = tempfile.mkstemp(".wav") sound.export(path, format="wav") - except: - print('Set ffmpeg to path so that you don'+\ - "'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.') + except Exception as _: + print( + "Set ffmpeg to path so that you don" + + "'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.' + ) pygame.mixer.music.load(path) + def play(self, loops=0): pygame.mixer.music.play(loops) + def stop(self): pygame.mixer.music.stop() + def restart(self): pygame.mixer.music.rewind() + def pause(self): pygame.mixer.music.pause() + def release(self): pygame.mixer.music.unpause() + def queue(self): pygame.mixer.music.queue(self._path) def volume(): def fget(self): return pygame.mixer.music.get_volume() + def fset(self, value): - if type(value) == int: + if type(value) is int: pygame.mixer.music.set_volume(value) + def fdel(self): pass + return locals() + volume = property(**volume()) def pos(): def fget(self): return pygame.mixer.music.get_pos() + def fset(self, value): - if type(value) == int: + if type(value) is int: pygame.mixer.music.set_pos(value) + def fdel(self): pass + return locals() + pos = property(**pos()) diff --git a/src/pygwin2/mouse.py b/src/pygwin2/mouse.py index e57ccc9..94a1207 100644 --- a/src/pygwin2/mouse.py +++ b/src/pygwin2/mouse.py @@ -1,35 +1,37 @@ -import .pygame -import inspect +from . import pygame + def getPressed(): 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): return getPressed()[x.lower()] + + def setPosition(x): pygame.mouse.set_pos(x) + + def getPosition(): return pygame.mouse.get_pos() + + def setVisible(x): pygame.mouse.set_visible(x) + + def getVisible(): return pygame.mouse.get_visible() + + def getCursor(): return pygame.mouse.get_cursor() + + def setCursor(size, hotspot=None, xormasks=None, andmasks=None): - if hotspot == None and xormasks == None and andmasks == None: + if hotspot is None and xormasks is None and andmasks is None: pygame.mouse.set_system_cursor(size) else: pygame.mouse.set_cursor(size, hotspot, xormasks, andmasks) - -_aliases = {'getPressed':['gprs','getbtns'], - 'isPressed':['isprs','btnprs'], - 'setPosition':['spos','setpos','move'], - 'getPosition':['gpos','getpos']} - -for i in _aliases.items(): - exec(f'args = inspect.signature({i[0]})') - args = [str(i[1]) for i in dict(args.parameters).items()] - args = ', '.join(args) - for i0 in i[1]: - exec(f"def {i0}({args}):return {i[0]}({args})") diff --git a/src/pygwin2/pygame.py b/src/pygwin2/pygame.py index ace702d..215e095 100644 --- a/src/pygwin2/pygame.py +++ b/src/pygwin2/pygame.py @@ -2,6 +2,7 @@ from contextlib import contextmanager import os import sys + @contextmanager def suppress_stdout(): with open(os.devnull, "w") as devnull: @@ -11,7 +12,9 @@ def suppress_stdout(): yield finally: sys.stdout = old_stdout - + + with suppress_stdout(): from pygame import * + init() diff --git a/src/pygwin2/record.py b/src/pygwin2/record.py index 658c860..0adb171 100644 --- a/src/pygwin2/record.py +++ b/src/pygwin2/record.py @@ -1,24 +1,23 @@ from contextlib import contextmanager -import .pygame +from . import pygame import moviepy.editor as mpe from array import array -from PIL import Image import numpy import threading -import pyautogui import tempfile import pyaudio import wave -import time import sys import cv2 import os + class record: - def __init__(self,win,audio=False): + def __init__(self, win, audio=False): self._isaudio = audio self._surface = win self.reset() + def reset(self): self._run = False self._fpss = [] @@ -27,57 +26,69 @@ class record: if self._isaudio: self._apy = pyaudio.PyAudio() self._aframs = [] - self._astrm = self.apy.open(format=pyaudio.paInt16,channels=1, - rate=44100,input=True,frames_per_buffer=1024) - def start(self,newThread=True): + self._astrm = self.apy.open( + format=pyaudio.paInt16, + channels=1, + rate=44100, + input=True, + frames_per_buffer=1024, + ) + + def start(self, newThread=True): self._run = True if self._isaudio: + def audiot(self): while self._run: self._aframs.append(self.astrm.read(1024)) - self._athread = threading.Thread(target=lambda:audiot(self)) + + self._athread = threading.Thread(target=lambda: audiot(self)) self._athread.start() + def main(self): while self.run: self._record() + if newThread: - self._thread = threading.Thread(target=lambda:main(self)) + self._thread = threading.Thread(target=lambda: main(self)) self._thread.start() - else:main() + else: + main() + def _record(self): if self._run: try: self._frames.append(self._surface) self._fpss.append(self._surface.rawFps) - except: + except Exception as _: pass + def render(self, path): temp = tempfile.gettempdir() if self.isaudio: - wavpath = os.path.join(temp, 'audio.wav') - wavfile = wave.open(wavpath, 'wb') + wavpath = os.path.join(temp, "audio.wav") + wavfile = wave.open(wavpath, "wb") wavfile.setnchannels(1) wavfile.setsampwidth(self._apy.get_sample_size(pyaudio.paInt16)) wavfile.setframerate(44100) af = [] for i in self._aframs: - af.append(array('h',i)) - wavfile.writeframes(b''.join(af)) + af.append(array("h", i)) + wavfile.writeframes(b"".join(af)) wavfile.close() fps = 0 for i in self._fpss: fps += i - fps = fps/len(self._fpss) + fps = fps / len(self._fpss) if self._isaudio: - noaudiopath = os.path.join(temp, 'noaudio.mp4') + noaudiopath = os.path.join(temp, "noaudio.mp4") else: noaudiopath = path - out = cv2.VideoWriter(noaudiopath,self._codec, - fps,self._surface.size) + out = cv2.VideoWriter(noaudiopath, self._codec, fps, self._surface.size) for i in self._frames: - frame = numpy.array(pygame.surfarray.array3d(i).swapaxes(0,1)) - frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB) + frame = numpy.array(pygame.surfarray.array3d(i).swapaxes(0, 1)) + frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) out.write(frame) out.release() @@ -86,22 +97,27 @@ class record: audioclip = mpe.AudioFileClip(wavpath) new_audioclip = mpe.CompositeAudioClip([audioclip]) videoclip.audio = new_audioclip + @contextmanager def ss(): with open(os.devnull, "w") as devnull: oso = sys.stdout sys.stdout = devnull - try:yield - finally:sys.stdout=oso + try: + yield + finally: + sys.stdout = oso + with ss(): videoclip.write_videofile(path) os.remove(noaudiopath) os.remove(wavpath) + def stop(self): self._run = False try: self._thread.join() - except: + except Exception as _: pass if self._isaudio: self._athread.join() diff --git a/src/pygwin2/rect.py b/src/pygwin2/rect.py index b8f39a2..638f406 100644 --- a/src/pygwin2/rect.py +++ b/src/pygwin2/rect.py @@ -1,38 +1,55 @@ -import .pygame +from . import pygame + +_aliases = { + "w": ["width"], + "h": ["height"], + "c": ["center", "middle"], + "x": ["left"], + "y": ["up"], + "r": ["right"], + "d": ["down"], +} -_aliases = {'w':['width'],'h':['height'], - 'c':['center','middle'], - 'x':['left'],'y':['up'], - 'r':['right'],'d':['down']} class rect: - def __init__(self,x,y,w,h): + def __init__(self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h self._reload() + def collide(self, x): - try:return self._rect.colliderect(x._rect_rect) - except:return self._rect.colliderect(x._rect) + try: + return self._rect.colliderect(x._rect_rect) + except Exception as _: + return self._rect.colliderect(x._rect) + def contains(self, x, y): - return self._rect.collidepoint(x,y) + return self._rect.collidepoint(x, y) + def copy(self): - return rect(self.x,self.y,self.w,self.h) + return rect(self.x, self.y, self.w, self.h) + def _reload(self): - 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.r,self.d = self.x+self.w,self.y+self.h - self._rect = pygame.Rect(self.x,self.y,self.w,self.h) - def __getitem__(self,x): - return [self.x,self.y,self.w,self.h][x] + self.r, self.d = self.x + self.w, self.y + self.h + self._rect = pygame.Rect(self.x, self.y, self.w, self.h) + + def __getitem__(self, x): + return [self.x, self.y, self.w, self.h][x] + def __list__(self): - return [self.x,self.y,self.w,self.h] + return [self.x, self.y, self.w, self.h] + def __tuple__(self): - return (self.x,self.y,self.w,self.h) + return (self.x, self.y, self.w, self.h) + def __str__(self): - return f'<{self.x}x{self.y},{self.w}x{self.h}>' - def __setattr__(self,attr,data): + return f"<{self.x}x{self.y},{self.w}x{self.h}>" + + def __setattr__(self, attr, data): if attr in _aliases.values(): ma = None for i in _aliases.items(): @@ -40,8 +57,9 @@ class rect: ma = i[0] break attr = ma - object.__setattr__(self,attr,data) - def __getattr__(self,attr): + object.__setattr__(self, attr, data) + + def __getattr__(self, attr): if attr in _aliases.values(): ma = None for i in _aliases.items(): diff --git a/src/pygwin2/surface.py b/src/pygwin2/surface.py index 478215e..3dd3037 100644 --- a/src/pygwin2/surface.py +++ b/src/pygwin2/surface.py @@ -1,60 +1,76 @@ from .rect import rect from .color import color -import .pygame +from . import pygame + class surface: def __init__(self, size): self._size = size self._orig = pygame.Surface(size, pygame.SRCALPHA) + @property def pixels(self): pixels = [] for x in range(self.size[0]): pixels.append([]) for y in range(self.size[1]): - pixels[x].append(self.getPixel(x,y)) + pixels[x].append(self.getPixel(x, y)) return pixels + @property def size(self): return self._size + def _grp(self): return self._orig + def rect(self, x=0, y=0, center=[]): if center == []: return rect(x, y, self.size[0], self.size[1]) else: - return rect(center[0]-(self.size[0]/2), - center[1]-(self.size[1]/2), - self.size[0], self.size[1]) + return rect( + center[0] - (self.size[0] / 2), + center[1] - (self.size[1] / 2), + self.size[0], + self.size[1], + ) + def copy(self): surf = surface(self._size) surf._surface_orig = self._orig surf._surface_size = self._size return surf + def getPixel(self, x, y): - return color(*self._orig.get_at((x,y))) + return color(*self._orig.get_at((x, y))) + def setPixel(self, x, y, color): - self._orig.set_at((x,y),color) + self._orig.set_at((x, y), color) return self.copy() + def blit(self, surf, xy): - if type(surf) != surface and type(surf) != pygame.Surface: + if type(surf) is not surface and type(surf) is pygame.Surface: from pygwin.font import defaultFont as _df - surf = _df.render(surf, 25, (0,0,0)) + + surf = _df.render(surf, 25, (0, 0, 0)) try: self._orig.blit(surf._surface_orig, xy) - except: + except Exception as _: try: self._orig.blit(surf._orig, xy) - except: + except Exception as _: self._orig.blit(surf, xy) return self.copy() + def fill(self, color): self._orig.fill(list(color)) return self.copy() + def crop(self, rect): self._orig = self._orig.subsurface(rect) self._size = self._orig.get_size() return self.copy() + def scale(self, size, smooth=False): if not smooth: self._orig = pygame.transform.scale(self._orig, size) @@ -62,84 +78,129 @@ class surface: self._orig = pygame.transform.smoothscale(self._orig, size) self._size = self._orig.get_size() return self.copy() + def rotate(self, angle): self._orig = pygame.transform.rotate(self._orig, angle) self._size = self._orig.get_size() return self.copy() + def flip(self, x, y): self._orig = pygame.transform.flip(self._orig, x, y) return self.copy() + def blur(self, amt): - if amt < 0:return self.copy() - scale = (int(self._orig.get_width()*(amt+1)), - int(self._orig.get_height()*(amt+1))) + if amt < 0: + return self.copy() + scale = ( + int(self._orig.get_width() * (amt + 1)), + int(self._orig.get_height() * (amt + 1)), + ) size = self._orig.get_size() - self._orig = pygame.transform.smoothscale(self._orig,scale) - self._orig = pygame.transform.smoothscale(self._orig,size) + self._orig = pygame.transform.smoothscale(self._orig, scale) + self._orig = pygame.transform.smoothscale(self._orig, size) return self.copy() class _draw: - def __init__(self,surface): + def __init__(self, surface): self._surf = surface - def rect(self,color,rect, - width=0,borderRadius=0, - borderTopLeftRadius=-1, - borderTopRightRadius=-1, - borderBottomLeftRadius=-1, - borderBottomRightRadius=-1): + + def rect( + self, + color, + rect, + width=0, + borderRadius=0, + borderTopLeftRadius=-1, + borderTopRightRadius=-1, + borderBottomLeftRadius=-1, + borderBottomRightRadius=-1, + ): try: orig = self._surf._surface_orig - except: + except Exception as _: orig = self._surf._orig - pygame.draw.rect(orig,color,pygame.Rect(rect[0],rect[1],rect[2],rect[3]), - width,borderRadius,borderTopLeftRadius,borderTopRightRadius, - borderBottomLeftRadius,borderBottomRightRadius) + pygame.draw.rect( + orig, + color, + pygame.Rect(rect[0], rect[1], rect[2], rect[3]), + width, + borderRadius, + borderTopLeftRadius, + borderTopRightRadius, + borderBottomLeftRadius, + borderBottomRightRadius, + ) return self._surf.copy() + def polygon(self, color, points, width=0): try: orig = self._surf._surface_orig - except: + except Exception as _: orig = self._surf._orig - pygame.draw.polygon(orig,color,points,width) + pygame.draw.polygon(orig, color, points, width) return self._surf.copy() - def circle(self,color,center, - radius,width=0, - drawTopLeft=1, - drawTopRight=1, - drawBottomLeft=1, - drawBottomRight=1): + + def circle( + self, + color, + center, + radius, + width=0, + drawTopLeft=1, + drawTopRight=1, + drawBottomLeft=1, + drawBottomRight=1, + ): try: orig = self._surf._surface_orig - except: + except Exception as _: orig = self._surf._orig - pygame.draw.circle(orig,color,center,radius, - width,drawTopRight,drawTopLeft, - drawBottomLeft,drawBottomRight) + pygame.draw.circle( + orig, + color, + center, + radius, + width, + drawTopRight, + drawTopLeft, + drawBottomLeft, + drawBottomRight, + ) return self._surf.copy() - def ellipse(self,color,rect,width=0): + + def ellipse(self, color, rect, width=0): try: orig = self._surf._surface_orig - except: + except Exception as _: orig = self._surf._orig - pygame.draw.ellipse(orig,color,pygame.Rect(rect[0], - rect[1],rect[2],rect[3]),width) + pygame.draw.ellipse( + orig, color, pygame.Rect(rect[0], rect[1], rect[2], rect[3]), width + ) return self._surf.copy() - def line(self,color,start,end,width=1): + + def line(self, color, start, end, width=1): try: orig = self._surf._surface_orig - except: + except Exception as _: orig = self._surf._orig - pygame.draw.line(orig,color,start,end,width) + pygame.draw.line(orig, color, start, end, width) return self._surf.copy() - def arc(self,color,rect,startAngle,stopAngle,width=1): + + def arc(self, color, rect, startAngle, stopAngle, width=1): try: orig = self._surf._surface_orig - except: + except Exception as _: orig = self._surf._orig - pygame.draw.arc(orig,color,pygame.Rect(rect[0], - rect[1],rect[2],rect[3]), - startAngle,stopAngle,width) + pygame.draw.arc( + orig, + color, + pygame.Rect(rect[0], rect[1], rect[2], rect[3]), + startAngle, + stopAngle, + width, + ) return self._surf.copy() + @property def draw(self): return self._draw(self) diff --git a/src/pygwin2/tray.py b/src/pygwin2/tray.py index d60186d..848b6eb 100644 --- a/src/pygwin2/tray.py +++ b/src/pygwin2/tray.py @@ -2,6 +2,7 @@ import threading import wx import wx.adv + class tray(wx.adv.TaskBarIcon): def __init__(self, tooltip, iconpath): class App(wx.App): @@ -9,6 +10,7 @@ class tray(wx.adv.TaskBarIcon): self.frame = wx.Frame(None) self.SetTopWindow(self.frame) return True + self._app = App(False) self.frame = self._app.frame super().__init__() @@ -16,33 +18,41 @@ class tray(wx.adv.TaskBarIcon): self._iconpath = iconpath self.setIcon(iconpath) self._menu = wx.Menu() + def CreatePopupMenu(self): return self._menu + def GetPopupMenu(self): return self._menu + def setIcon(self, path): self._bicon = wx.Icon(wx.Bitmap(path)) self.SetIcon(self._bicon, self._tooltip) + def setTooltip(self, tooltip): self.SetIcon(self._bicon, tooltip) self._tooltip = tooltip + def onLeftMouseButton(self): pass + def addSeparator(self): self._menu.AppendSeparator() - def addCommand(self,text,func=lambda:None): - item = wx.MenuItem(self._menu,-1,text) - self._menu.Bind(wx.EVT_MENU, - lambda x:func(), - id=item.GetId()) + + def addCommand(self, text, func=lambda: None): + item = wx.MenuItem(self._menu, -1, text) + self._menu.Bind(wx.EVT_MENU, lambda x: func(), id=item.GetId()) self._menu.Append(item) + def start(self, thread=True): def cbotld(x): return self.onLeftMouseButton() - self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN,cbotld) - if thread: threading.Thread( - target=self._app.MainLoop, - daemon=1).start() - else: self._app.MainLoop() + + self.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, cbotld) + if thread: + threading.Thread(target=self._app.MainLoop, daemon=1).start() + else: + self._app.MainLoop() + def stop(self): wx.CallAfter(self._app.frame.Close) diff --git a/src/pygwin2/ui/__init__.py b/src/pygwin2/ui/__init__.py index 370a986..a9cc6e6 100644 --- a/src/pygwin2/ui/__init__.py +++ b/src/pygwin2/ui/__init__.py @@ -1,2 +1,4 @@ +__all__ = ["widget", "base"] + from . import widget from . import base diff --git a/src/pygwin2/ui/base.py b/src/pygwin2/ui/base.py index 47923d6..1bf650a 100644 --- a/src/pygwin2/ui/base.py +++ b/src/pygwin2/ui/base.py @@ -1,32 +1,32 @@ -import ...pygame -from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l -from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct import copy as _copy + class widget: power = True destroyed = False + def _args(self, locals): args = _copy.copy(locals) for i in args.items(): - if i[0] != 'self': + if i[0] != "self": exec(f'self.{i[0]} = args["{i[0]}"]') self._args = args + def __init__(self, surface): self._args(locals()) + def draw(self, win, pos): - win.blit(self.surface,pos) + win.blit(self.surface, pos) + def on(self): self.power = True + def off(self): self.power = False + def destroy(self): self.destroyed = True + def config(self, **parameters): if parameters != {}: for i in parameters.items(): @@ -37,12 +37,14 @@ class widget: return self._args self.__init__(**self._args) + class base: - def __init__(self, win, bg=(128,128,128)): + def __init__(self, win, bg=(128, 128, 128)): self._widgets = {} self._bg = bg self._win = win self._page = 0 + def draw(self): self._win.fill(self._bg) for i in self._widgets[self._page]: @@ -50,17 +52,23 @@ class base: i[0].draw(self._win, i[1]) if i[0].destroyed: self._widgets[self._page].remove(i) + def put(self, widget, pos, page=0): if page not in self._widgets: self.blankPage(page) self._widgets[page].append([widget, pos]) + def selectPage(self, page): self._page = page + def getPage(self): return self._page + def getWidgets(self, page=0): return self._widgets[page] - def setWidgetPos(self,index,pos,page=0): + + def setWidgetPos(self, index, pos, page=0): self._widgets[page][index] = [self._widgets[page][index][0], pos] - def blankPage(self,page): - self._widgets.update({page:[]}) + + def blankPage(self, page): + self._widgets.update({page: []}) diff --git a/src/pygwin2/ui/widget/__init__.py b/src/pygwin2/ui/widget/__init__.py index ceace21..02ba39a 100644 --- a/src/pygwin2/ui/widget/__init__.py +++ b/src/pygwin2/ui/widget/__init__.py @@ -1,3 +1,17 @@ +__all__ = [ + "checkbox", + "entry", + "keyselect", + "button", + "combobox", + "image", + "label", + "loadingbar", + "textarea", + "tip", + "slider", +] + from . import checkbox from . import entry from . import keyselect diff --git a/src/pygwin2/ui/widget/button.py b/src/pygwin2/ui/widget/button.py index 2b16c3b..d3f83c1 100644 --- a/src/pygwin2/ui/widget/button.py +++ b/src/pygwin2/ui/widget/button.py @@ -1,41 +1,49 @@ -import ...pygame +from ... import pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l +from ...font import deaultFont as _df from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ... import mouse as _m +from .base import widget + class button(widget): - def __init__(self,text, - func=lambda:None, - fontSize=30,font=_df, - width=None,height=None, - bg=(70,70,70),fg=(180,180,200), - afg=(50,50,50),abg=(200,200,200), - borderColor=(50,50,50),borderWidth=5): + def __init__( + self, + text, + func=lambda: None, + fontSize=30, + font=_df, + width=None, + height=None, + bg=(70, 70, 70), + fg=(180, 180, 200), + afg=(50, 50, 50), + abg=(200, 200, 200), + borderColor=(50, 50, 50), + borderWidth=5, + ): super()._args(locals()) self.cl0 = False self.cl1 = False self.nc0 = True self._generate() + def _generate(self, position=None): - if self.width == None or self.height == None: - textSize = self.font.size(self.text,self.fontSize) - if self.width != None: - self.surface = _s((self.width,textSize[1]+10)) - elif self.height != None: - self.surface = _s((textSize[0]+50,self.height)) + if self.width is None or self.height is None: + textSize = self.font.size(self.text, self.fontSize) + if self.width is not None: + self.surface = _s((self.width, textSize[1] + 10)) + elif self.height is not None: + self.surface = _s((textSize[0] + 50, self.height)) else: - self.surface = _s((textSize[0]+50,textSize[1]+10)) + self.surface = _s((textSize[0] + 50, textSize[1] + 10)) else: - self.surface = _s((self.width,self.height)) - if position != None: + self.surface = _s((self.width, self.height)) + if position is not None: contains = self.surface.rect(position[0], position[1]).contains( - _m.getPosition()[0], _m.getPosition()[1]) - cacm = contains and _m.isPressed('left') + _m.getPosition()[0], _m.getPosition()[1] + ) + cacm = contains and _m.isPressed("left") else: contains = False cacm = False @@ -55,23 +63,33 @@ class button(widget): self.cl1 = False self.surface.fill(self.borderColor) if cacm: - self.surface.draw.rect(self.abg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) + self.surface.draw.rect( + self.abg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) else: - self.surface.draw.rect(self.bg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) + self.surface.draw.rect( + self.bg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) if cacm: - text = self.font.render(self.text,self.fontSize,self.afg) + text = self.font.render(self.text, self.fontSize, self.afg) else: - text = self.font.render(self.text,self.fontSize,self.fg) - pos = text.rect(center=( - self.surface.size[0]/2, - self.surface.size[1]/2)) + text = self.font.render(self.text, self.fontSize, self.fg) + pos = text.rect(center=(self.surface.size[0] / 2, self.surface.size[1] / 2)) pos = [pos.x, pos.y] - self.surface.blit(text,pos) + self.surface.blit(text, pos) + def draw(self, win, pos): self._generate(pos) - win.blit(self.surface,pos) - + win.blit(self.surface, pos) diff --git a/src/pygwin2/ui/widget/checkbox.py b/src/pygwin2/ui/widget/checkbox.py index 9201df9..f7380cd 100644 --- a/src/pygwin2/ui/widget/checkbox.py +++ b/src/pygwin2/ui/widget/checkbox.py @@ -1,34 +1,41 @@ -import ...pygame +from ... import pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ... import mouse as _m +from .base import widget + class checkBox(widget): - def __init__(self,width=50,bg=(180,180,180), - fg=(50,180,50),afg=(70,200,70), - abg=(120,120,120),borderColor=(220,220,220), - borderWidth=5): + def __init__( + self, + width=50, + bg=(180, 180, 180), + fg=(50, 180, 50), + afg=(70, 200, 70), + abg=(120, 120, 120), + borderColor=(220, 220, 220), + borderWidth=5, + ): super()._args(locals()) self.cl0 = False self.cl1 = False self.nc0 = True self.x = False self._generate() + def set(self, x): self.x = x + def get(self): return self.x + def _generate(self, position=None): - self.surface = _s((self.width,self.width)) - if position != None: + self.surface = _s((self.width, self.width)) + if position is not None: contains = self.surface.rect(position[0], position[1]).contains( - _m.getPosition()[0], _m.getPosition()[1]) - cacm = contains and _m.isPressed('left') + _m.getPosition()[0], _m.getPosition()[1] + ) + cacm = contains and _m.isPressed("left") else: contains = False cacm = False @@ -42,30 +49,58 @@ class checkBox(widget): self.nc0 = False self.cl0 = False if cacm and not self.cl1: - self.x=self.x==0 + self.x = self.x == 0 self.cl1 = True elif not cacm: self.cl1 = False self.surface.fill(self.borderColor) if cacm: - self.surface.draw.rect(self.abg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) + self.surface.draw.rect( + self.abg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) if self.x: - self.surface.draw.line(self.afg,[self.borderWidth,self.width/2+self.borderWidth], - [self.width/2,self.width-self.borderWidth],self.borderWidth) - self.surface.draw.line(self.afg,[self.width/2,self.width-self.borderWidth], - [self.width-self.borderWidth,self.borderWidth],self.borderWidth) + self.surface.draw.line( + self.afg, + [self.borderWidth, self.width / 2 + self.borderWidth], + [self.width / 2, self.width - self.borderWidth], + self.borderWidth, + ) + self.surface.draw.line( + self.afg, + [self.width / 2, self.width - self.borderWidth], + [self.width - self.borderWidth, self.borderWidth], + self.borderWidth, + ) else: - self.surface.draw.rect(self.bg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) + self.surface.draw.rect( + self.bg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) if self.x: - self.surface.draw.line(self.fg,[self.borderWidth,self.width/2+self.borderWidth], - [self.width/2,self.width-self.borderWidth],self.borderWidth) - self.surface.draw.line(self.fg,[self.width/2,self.width-self.borderWidth], - [self.width-self.borderWidth,self.borderWidth],self.borderWidth) + self.surface.draw.line( + self.fg, + [self.borderWidth, self.width / 2 + self.borderWidth], + [self.width / 2, self.width - self.borderWidth], + self.borderWidth, + ) + self.surface.draw.line( + self.fg, + [self.width / 2, self.width - self.borderWidth], + [self.width - self.borderWidth, self.borderWidth], + self.borderWidth, + ) + def draw(self, win, pos): self._generate(pos) - win.blit(self.surface,pos) - + win.blit(self.surface, pos) diff --git a/src/pygwin2/ui/widget/combobox.py b/src/pygwin2/ui/widget/combobox.py index 4966eea..3704f05 100644 --- a/src/pygwin2/ui/widget/combobox.py +++ b/src/pygwin2/ui/widget/combobox.py @@ -1,25 +1,30 @@ -import ...pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l -from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ...font import deaultFont as _df +from .base import widget + class comboBox(widget): - def __init__(self,text,values=[], -fontSize=30,font=_df,width=None,height=None, -bg=(70,70,70),fg=(180,180,200),afg=(50,50,50), -abg=(200,200,200),borderColor=(50,50,50),borderWidth=5): + def __init__( + self, + text, + values=[], + fontSize=30, + font=_df, + width=None, + height=None, + bg=(70, 70, 70), + fg=(180, 180, 200), + afg=(50, 50, 50), + abg=(200, 200, 200), + borderColor=(50, 50, 50), + borderWidth=5, + ): super()._args(locals()) self._generate() def _generate(self, position=None): - self.surface = _s((255,self.width)) + self.surface = _s((255, self.width)) def draw(self, win, pos): self._generate(pos) - win.blit(self.surface,pos) - + win.blit(self.surface, pos) diff --git a/src/pygwin2/ui/widget/entry.py b/src/pygwin2/ui/widget/entry.py index c3ef7ef..3040499 100644 --- a/src/pygwin2/ui/widget/entry.py +++ b/src/pygwin2/ui/widget/entry.py @@ -1,117 +1,157 @@ -import ...pygame +from ... import pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l +from ...font import deaultFont as _df from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ... import mouse as _m +from ... import keyboard as _k +from ... import pes as _ct +from .base import widget + class entry(widget): - def __init__(self,hint='',fontSize=30,font=_df, - width=None,height=None,hide=False, - bg=(70,70,70),fg=(180,180,200), - afg=(200,200,200),abg=(50,50,50), - hintColor=(100,100,100), - lineColor=(200,200,200), - borderColor=(50,50,50), - borderWidth=5,maxSymbols=None, - whitelist=None,blacklist=[]): + def __init__( + self, + hint="", + fontSize=30, + font=_df, + width=None, + height=None, + hide=False, + bg=(70, 70, 70), + fg=(180, 180, 200), + afg=(200, 200, 200), + abg=(50, 50, 50), + hintColor=(100, 100, 100), + lineColor=(200, 200, 200), + borderColor=(50, 50, 50), + borderWidth=5, + maxSymbols=None, + whitelist=None, + blacklist=[], + ): super()._args(locals()) - self.text = '' + self.text = "" self.focus = False self.tick = 0 self.wcl = False self.startHint = self.hint self.ws = False - if self.width == None or self.height == None: - if self.hint != '': - hintSize = self.font.size(self.hint,self.fontSize) + if self.width is None or self.height is None: + if self.hint != "": + hintSize = self.font.size(self.hint, self.fontSize) else: - hintSize = (150,self.font.size('X',self.fontSize)[1]) - if self.height == None: - self.height = hintSize[1]+10 - if self.width == None: - self.width = hintSize[0]+50 - self.surface = _s((self.width,self.height)) + hintSize = (150, self.font.size("X", self.fontSize)[1]) + if self.height is None: + self.height = hintSize[1] + 10 + if self.width is None: + self.width = hintSize[0] + 50 + self.surface = _s((self.width, self.height)) self.wclk = [] self.wsnr = False - def _generate(self,position=None): + + def _generate(self, position=None): self.surface.fill(self.borderColor) if self.focus: - self.surface.draw.rect(self.abg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) - if self.text == '': + self.surface.draw.rect( + self.abg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) + if self.text == "": if not self.hide: - text = self.font.render(self.hint,self.fontSize,self.hintColor) + text = self.font.render(self.hint, self.fontSize, self.hintColor) else: - text = self.font.render('*'*len(self.hint),self.fontSize,self.hintColor) + text = self.font.render( + "*" * len(self.hint), self.fontSize, self.hintColor + ) else: if not self.hide: - text = self.font.render(self.text,self.fontSize,self.afg) + text = self.font.render(self.text, self.fontSize, self.afg) else: - text = self.font.render('*'*len(self.text),self.fontSize,self.afg) + text = self.font.render( + "*" * len(self.text), self.fontSize, self.afg + ) x = 10 - if text.size[0] >= self.surface.size[0]-20: - x = self.surface.size[0]-text.size[0]-10 - self.surface.blit(text,(x,self.surface.size[1]/2-text.size[1]/2)) + if text.size[0] >= self.surface.size[0] - 20: + x = self.surface.size[0] - text.size[0] - 10 + self.surface.blit(text, (x, self.surface.size[1] / 2 - text.size[1] / 2)) for i in _k.getPressed().items(): if i[1]: if i[0] not in self.wclk: if len(i[0]) == 1: self.insert(i[0]) - elif i[0] == 'backspace': + elif i[0] == "backspace": self.delete() - elif i[0] == 'return': + elif i[0] == "return": self.focus = False - elif i[0] == 'space': - self.insert(' ') + elif i[0] == "space": + self.insert(" ") self.wclk.append(i[0]) else: if i[0] in self.wclk: self.wclk.remove(i[0]) self.tick += 1 if self.tick >= 60: - if self.text != '': - points = [[x+text.size[0],self.surface.size[1]/2-text.size[1]/2], - [x+text.size[0],self.surface.size[1]/2-text.size[1]/2+self.surface.size[1]-10]] - self.surface.draw.line(self.lineColor,points[0],points[1],3) + if self.text != "": + points = [ + [x + text.size[0], self.surface.size[1] / 2 - text.size[1] / 2], + [ + x + text.size[0], + self.surface.size[1] / 2 + - text.size[1] / 2 + + self.surface.size[1] + - 10, + ], + ] + self.surface.draw.line(self.lineColor, points[0], points[1], 3) if self.tick == 120: self.tick = 0 else: - self.surface.draw.rect(self.bg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) - if self.text == '': + self.surface.draw.rect( + self.bg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) + if self.text == "": if not self.hide: - text = self.font.render(self.hint,self.fontSize,self.hintColor) + text = self.font.render(self.hint, self.fontSize, self.hintColor) else: - text = self.font.render('*'*len(self.hint),self.fontSize,self.hintColor) + text = self.font.render( + "*" * len(self.hint), self.fontSize, self.hintColor + ) else: if self.hide: - text = self.font.render(self.text,self.fontSize,self.fg) + text = self.font.render(self.text, self.fontSize, self.fg) else: - text = self.font.render('*'*len(self.text),self.fontSize,self.fg) - x = self.surface.size[0]/2-text.size[0]/2 - if text.size[0] >= self.surface.size[0]-20: - x = self.surface.size[0]-text.size[0]-10 - self.surface.blit(text,(x,self.surface.size[1]/2-text.size[1]/2)) + text = self.font.render( + "*" * len(self.text), self.fontSize, self.fg + ) + x = self.surface.size[0] / 2 - text.size[0] / 2 + if text.size[0] >= self.surface.size[0] - 20: + x = self.surface.size[0] - text.size[0] - 10 + self.surface.blit(text, (x, self.surface.size[1] / 2 - text.size[1] / 2)) - if position != None: - if self.surface.rect(position[0], - position[1]).contains(_m.getPosition()[0], - _m.getPosition()[1]): + if position is not None: + if self.surface.rect(position[0], position[1]).contains( + _m.getPosition()[0], _m.getPosition()[1] + ): if not self.wcl: _m.setCursor(pygame.SYSTEM_CURSOR_HAND) else: if not self.ws: _m.setCursor(pygame.SYSTEM_CURSOR_ARROW) self.ws = True - if _m.isPressed('left'): + if _m.isPressed("left"): if not self.wcl: - self.focus=self.focus==0 + self.focus = self.focus == 0 self.wcl = True else: self.wcl = False @@ -120,33 +160,55 @@ class entry(widget): if not self.wsnr: _m.setCursor(pygame.SYSTEM_CURSOR_ARROW) self.wsnr = True - if _m.isPressed('left'): + if _m.isPressed("left"): self.focus = False - def insert(self,text): + + def insert(self, text): if _ct.WinDLL("User32.dll").GetKeyState(0x14): text = text.upper() - if hex(getattr(_ct.windll.LoadLibrary("user32.dll"), "GetKeyboardLayout")(0))=='0x4190419': - text = text.translate(dict(zip(map(ord, - '''qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOPASDFGHJKLZXCVBNM'''), - '''йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗФЫВАПРОЛДЯЧСМИТЬ'''))) - if pygame.key.get_pressed()[pygame.K_LSHIFT] or pygame.key.get_pressed()[pygame.K_RSHIFT]: - text = text.translate(dict(zip(map(ord, - u'''1234567890-=[]\;',./`'''), - u'''!@#$%^&*()_+{}|:"<>?~'''))) + if ( + hex(getattr(_ct.windll.LoadLibrary("user32.dll"), "GetKeyboardLayout")(0)) + == "0x4190419" + ): + text = text.translate( + dict( + zip( + map( + ord, + """qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOPASDFGHJKLZXCVBNM""", + ), + """йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗФЫВАПРОЛДЯЧСМИТЬ""", + ) + ) + ) + if ( + pygame.key.get_pressed()[pygame.K_LSHIFT] + or pygame.key.get_pressed()[pygame.K_RSHIFT] + ): + text = text.translate( + dict( + zip( + map(ord, """1234567890-=[]\;',./`"""), + """!@#$%^&*()_+{}|:"<>?~""", + ) + ) + ) if text in self.blacklist: return - if self.whitelist != None: + if self.whitelist is not None: if text not in self.whitelist: return - if self.maxSymbols != None: + if self.maxSymbols is not None: if len(self.text) > self.maxSymbols: return self.text += text - def delete(self,symbols=1): - self.text = self.text[:0-symbols] + + def delete(self, symbols=1): + self.text = self.text[: 0 - symbols] + def draw(self, win, pos): self._generate(pos) - win.blit(self.surface,pos) + win.blit(self.surface, pos) + def get(self): return self.text - diff --git a/src/pygwin2/ui/widget/image.py b/src/pygwin2/ui/widget/image.py index bc6166a..959f833 100644 --- a/src/pygwin2/ui/widget/image.py +++ b/src/pygwin2/ui/widget/image.py @@ -1,12 +1,6 @@ -import ...pygame -from ...surface import surface as _s -from ...font import defaultFont as _df from ...image import load as _l -from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from .base import widget + class image(widget): def __init__(self, path): diff --git a/src/pygwin2/ui/widget/keyselect.py b/src/pygwin2/ui/widget/keyselect.py index ea06688..f5ffba7 100644 --- a/src/pygwin2/ui/widget/keyselect.py +++ b/src/pygwin2/ui/widget/keyselect.py @@ -1,104 +1,133 @@ -import ...pygame +from ... import pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l +from ...font import deaultFont as _df from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ... import mouse as _m +from ... import keyboard as _k +from .entry import entry + class keySelect(entry): - def __init__(self,keyBefore='', - fontSize=30,font=_df, - width=None,height=None, - bg=(70,70,70),fg=(180,180,200), - afg=(200,200,200),abg=(50,50,50), - hintColor=(100,100,100), - lineColor=(200,200,200), - borderColor=(50,50,50), - borderWidth=5,maxSymbols=None, - whitelist=None,blacklist=[]): + def __init__( + self, + keyBefore="", + fontSize=30, + font=_df, + width=None, + height=None, + bg=(70, 70, 70), + fg=(180, 180, 200), + afg=(200, 200, 200), + abg=(50, 50, 50), + hintColor=(100, 100, 100), + lineColor=(200, 200, 200), + borderColor=(50, 50, 50), + borderWidth=5, + maxSymbols=None, + whitelist=None, + blacklist=[], + ): super()._args(locals()) - self.hint = '' + self.hint = "" self.text = keyBefore self.focus = False self.tick = 0 self.wcl = False self.startHint = self.hint self.ws = False - if self.width == None or self.height == None: - if self.hint != '': - hintSize = self.font.size(self.hint,self.fontSize) + if self.width is None or self.height is None: + if self.hint != "": + hintSize = self.font.size(self.hint, self.fontSize) else: - hintSize = (150,self.font.size('X',self.fontSize)[1]) - if self.height == None: - self.height = hintSize[1]+10 - if self.width == None: - self.width = hintSize[0]+50 - self.surface = _s((self.width,self.height)) + hintSize = (150, self.font.size("X", self.fontSize)[1]) + if self.height is None: + self.height = hintSize[1] + 10 + if self.width is None: + self.width = hintSize[0] + 50 + self.surface = _s((self.width, self.height)) self.wclk = [] self.wsnr = False - def _generate(self,position=None): + + def _generate(self, position=None): self.surface.fill(self.borderColor) if self.focus: - self.surface.draw.rect(self.abg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) - if self.text == '': - text = self.font.render(self.hint,self.fontSize,self.hintColor) + self.surface.draw.rect( + self.abg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) + if self.text == "": + text = self.font.render(self.hint, self.fontSize, self.hintColor) else: - text = self.font.render(self.text,self.fontSize,self.afg) - x = self.surface.size[0]/2-text.size[0]/2 - if text.size[0] >= self.surface.size[0]-20: - x = self.surface.size[0]-text.size[0]-10 - self.surface.blit(text,(x,self.surface.size[1]/2-text.size[1]/2)) + text = self.font.render(self.text, self.fontSize, self.afg) + x = self.surface.size[0] / 2 - text.size[0] / 2 + if text.size[0] >= self.surface.size[0] - 20: + x = self.surface.size[0] - text.size[0] - 10 + self.surface.blit(text, (x, self.surface.size[1] / 2 - text.size[1] / 2)) for i in _k.getPressed().items(): if i[1] and self.focus: if i[0] in self.blacklist: continue - if self.whitelist != None: + if self.whitelist is not None: if i[0] not in self.whitelist: continue - if self.maxSymbols != None: + if self.maxSymbols is not None: if len(self.text) > self.maxSymbols: continue self.text = i[0] break self.tick += 1 if self.tick >= 60: - if self.text != '': - points = [[x+text.size[0],self.surface.size[1]/2-text.size[1]/2], - [x+text.size[0],self.surface.size[1]/2-text.size[1]/2+self.surface.size[1]-10]] - self.surface.draw.line(self.lineColor,points[0],points[1],3) + if self.text != "": + points = [ + [x + text.size[0], self.surface.size[1] / 2 - text.size[1] / 2], + [ + x + text.size[0], + self.surface.size[1] / 2 + - text.size[1] / 2 + + self.surface.size[1] + - 10, + ], + ] + self.surface.draw.line(self.lineColor, points[0], points[1], 3) if self.tick == 120: self.tick = 0 else: - self.surface.draw.rect(self.bg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) - if self.text == '': - text = self.font.render(self.hint,self.fontSize,self.hintColor) + self.surface.draw.rect( + self.bg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) + if self.text == "": + text = self.font.render(self.hint, self.fontSize, self.hintColor) else: - text = self.font.render(self.text,self.fontSize,self.fg) - x = self.surface.size[0]/2-text.size[0]/2 - if text.size[0] >= self.surface.size[0]-20: - x = self.surface.size[0]-text.size[0]-10 - self.surface.blit(text,(x,self.surface.size[1]/2-text.size[1]/2)) + text = self.font.render(self.text, self.fontSize, self.fg) + x = self.surface.size[0] / 2 - text.size[0] / 2 + if text.size[0] >= self.surface.size[0] - 20: + x = self.surface.size[0] - text.size[0] - 10 + self.surface.blit(text, (x, self.surface.size[1] / 2 - text.size[1] / 2)) - if position != None: - if self.surface.rect(position[0], - position[1]).contains(_m.getPosition()[0], - _m.getPosition()[1]): + if position is not None: + if self.surface.rect(position[0], position[1]).contains( + _m.getPosition()[0], _m.getPosition()[1] + ): if not self.wcl: _m.setCursor(pygame.SYSTEM_CURSOR_HAND) else: if not self.ws: _m.setCursor(pygame.SYSTEM_CURSOR_ARROW) self.ws = True - if _m.isPressed('left'): + if _m.isPressed("left"): if not self.wcl: - self.focus=self.focus==0 + self.focus = self.focus == 0 self.wcl = True else: self.wcl = False @@ -107,10 +136,12 @@ class keySelect(entry): if not self.wsnr: _m.setCursor(pygame.SYSTEM_CURSOR_ARROW) self.wsnr = True - if _m.isPressed('left'): + if _m.isPressed("left"): self.focus = False + def draw(self, win, pos): self._generate(pos) - win.blit(self.surface,pos) + win.blit(self.surface, pos) + def get(self): return self.text diff --git a/src/pygwin2/ui/widget/label.py b/src/pygwin2/ui/widget/label.py index b6e7792..e430f03 100644 --- a/src/pygwin2/ui/widget/label.py +++ b/src/pygwin2/ui/widget/label.py @@ -1,15 +1,7 @@ -import ...pygame -from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l -from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ...font import deaultFont as _df +from .base import widget + class label(widget): - def __init__(self,text,size=30, - color=(0,0,0),font=_df): - self.surface = font.render(text,size,color) - + def __init__(self, text, size=30, color=(0, 0, 0), font=_df): + self.surface = font.render(text, size, color) diff --git a/src/pygwin2/ui/widget/loadingbar.py b/src/pygwin2/ui/widget/loadingbar.py index e57fc33..c34c744 100644 --- a/src/pygwin2/ui/widget/loadingbar.py +++ b/src/pygwin2/ui/widget/loadingbar.py @@ -1,43 +1,52 @@ -import ...pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from .base import widget + class loadingBar(widget): - def __init__(self,width, - height=50, - length=100, - bg=(70,70,70), - loadedColor=(50,200,50), - borderColor=(50,50,50), - borderWidth=5): + def __init__( + self, + width, + height=50, + length=100, + bg=(70, 70, 70), + loadedColor=(50, 200, 50), + borderColor=(50, 50, 50), + borderWidth=5, + ): super()._args(locals()) self.loaded = 0 - def step(self,count=1): + + def step(self, count=1): self.loaded += 1 if self.loaded > self.length: self.loaded = self.length + def set(self, x): self.loaded = x if self.loaded > self.length: self.loaded = self.length + def reset(self): self.loaded = 0 + def get(self): return self.loaded - def draw(self, win, pos): - self.surface = _s((self.width,self.height)) - self.surface.fill(self.borderColor) - self.surface.draw.rect(self.bg,_r(5,5, - self.surface.size[0]-10, - self.surface.size[1]-10)) - self.surface.draw.rect(self.loadedColor,_r(self.borderWidth,self.borderWidth, - (self.surface.size[0]/self.length*self.loaded)-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) - win.blit(self.surface, pos) + def draw(self, win, pos): + self.surface = _s((self.width, self.height)) + self.surface.fill(self.borderColor) + self.surface.draw.rect( + self.bg, _r(5, 5, self.surface.size[0] - 10, self.surface.size[1] - 10) + ) + self.surface.draw.rect( + self.loadedColor, + _r( + self.borderWidth, + self.borderWidth, + (self.surface.size[0] / self.length * self.loaded) + - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) + win.blit(self.surface, pos) diff --git a/src/pygwin2/ui/widget/slider.py b/src/pygwin2/ui/widget/slider.py index 7334b4a..61f863e 100644 --- a/src/pygwin2/ui/widget/slider.py +++ b/src/pygwin2/ui/widget/slider.py @@ -1,64 +1,74 @@ -import ...pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ... import mouse as _m +from .base import widget + class slider(widget): - def __init__(self,width, - bg=(70,70,70), - fg=(200,200,200), - horizontal=True): + def __init__(self, width, bg=(70, 70, 70), fg=(200, 200, 200), horizontal=True): super()._args(locals()) self.s = False self.x = 12.5 self._generate(None) + def _generate(self, pos): if self.horizontal: - self.surface = _s((self.width,50)) - self.surface.draw.line(self.bg,[12.5,25],[self.width-12.5,25],10) - self.surface.draw.circle(self.bg,[12.5,26],5) - self.surface.draw.circle(self.bg,[self.width-12.5,26],5) - self.surface.draw.circle(self.fg,[self.x,25],12.5) + self.surface = _s((self.width, 50)) + self.surface.draw.line(self.bg, [12.5, 25], [self.width - 12.5, 25], 10) + self.surface.draw.circle(self.bg, [12.5, 26], 5) + self.surface.draw.circle(self.bg, [self.width - 12.5, 26], 5) + self.surface.draw.circle(self.fg, [self.x, 25], 12.5) else: - self.surface = _s((50,self.width)) - self.surface.draw.line(self.bg,[25,12.5],[25,self.width-12.5],10) - self.surface.draw.circle(self.bg,[26,12.5],5) - self.surface.draw.circle(self.bg,[26,self.width-12.5],5) - self.surface.draw.circle(self.fg,[25,self.x],12.5) - if pos != None: - if _m.isPressed('left'): + self.surface = _s((50, self.width)) + self.surface.draw.line(self.bg, [25, 12.5], [25, self.width - 12.5], 10) + self.surface.draw.circle(self.bg, [26, 12.5], 5) + self.surface.draw.circle(self.bg, [26, self.width - 12.5], 5) + self.surface.draw.circle(self.fg, [25, self.x], 12.5) + if pos is not None: + if _m.isPressed("left"): if self.horizontal: - rect = _r(pos[0]+5,pos[1], - self.surface.size[0]-10, - self.surface.size[1]) - if rect.contains(_m.getPosition()[0], - _m.getPosition()[1]) or self.s: - self.x = _m.getPosition()[0]-pos[0] - if self.x < 12.5: self.x = 12.5 - if self.x > self.width-12.5: self.x = self.width-12.5 + rect = _r( + pos[0] + 5, + pos[1], + self.surface.size[0] - 10, + self.surface.size[1], + ) + if ( + rect.contains(_m.getPosition()[0], _m.getPosition()[1]) + or self.s + ): + self.x = _m.getPosition()[0] - pos[0] + if self.x < 12.5: + self.x = 12.5 + if self.x > self.width - 12.5: + self.x = self.width - 12.5 self.s = True else: - rect = _r(pos[0],pos[1]+5, - self.surface.size[0], - self.surface.size[1]-10) - if rect.contains(_m.getPosition()[0], - _m.getPosition()[1]) or self.s: - self.x = _m.getPosition()[1]-pos[1] - if self.x < 12.5: self.x = 12.5 - if self.x > self.width-12.5: self.x = self.width-12.5 + rect = _r( + pos[0], + pos[1] + 5, + self.surface.size[0], + self.surface.size[1] - 10, + ) + if ( + rect.contains(_m.getPosition()[0], _m.getPosition()[1]) + or self.s + ): + self.x = _m.getPosition()[1] - pos[1] + if self.x < 12.5: + self.x = 12.5 + if self.x > self.width - 12.5: + self.x = self.width - 12.5 self.s = True else: self.s = False + def get(self): - return int(self.x/(self.width-10)*101) + return int(self.x / (self.width - 10) * 101) + def set(self, x): - self.x = x/101*(self.width-10) + self.x = x / 101 * (self.width - 10) + def draw(self, win, pos): self._generate(pos) win.blit(self.surface, pos) - diff --git a/src/pygwin2/ui/widget/textarea.py b/src/pygwin2/ui/widget/textarea.py index 92e4e28..16a5973 100644 --- a/src/pygwin2/ui/widget/textarea.py +++ b/src/pygwin2/ui/widget/textarea.py @@ -1,121 +1,154 @@ -import ...pygame +from ... import pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l +from ...font import deaultFont as _df from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ... import mouse as _m +from ... import keyboard as _k +from ... import pes as _ct +from .base import widget + class textarea(widget): - def __init__(self,hint='',fontSize=30, - font=_df,width=None,bg=(70,70,70), - fg=(180,180,200),afg=(200,200,200), - abg=(50,50,50),hintColor=(100,100,100), - lineColor=(200,200,200), - borderColor=(50,50,50), - borderWidth=5,maxSymbols=None, - whitelist=None,blacklist=[]): + def __init__( + self, + hint="", + fontSize=30, + font=_df, + width=None, + bg=(70, 70, 70), + fg=(180, 180, 200), + afg=(200, 200, 200), + abg=(50, 50, 50), + hintColor=(100, 100, 100), + lineColor=(200, 200, 200), + borderColor=(50, 50, 50), + borderWidth=5, + maxSymbols=None, + whitelist=None, + blacklist=[], + ): super()._args(locals()) - self.text = '' + self.text = "" self.focus = False self.tick = 0 self.wcl = False self.startHint = self.hint self.ws = False - if self.hint != '': - hintSize = self.font.size(self.hint,self.fontSize) + if self.hint != "": + hintSize = self.font.size(self.hint, self.fontSize) else: - hintSize = (150,self.font.size('X',self.fontSize)[1]) - self.height = hintSize[1]+10 - if self.width == None: - self.width = hintSize[0]+50 - self.surface = _s((self.width,self.height)) + hintSize = (150, self.font.size("X", self.fontSize)[1]) + self.height = hintSize[1] + 10 + if self.width is None: + self.width = hintSize[0] + 50 + self.surface = _s((self.width, self.height)) self.wclk = [] self.wsnr = False - def _generate(self,position=None): + + def _generate(self, position=None): self.surface.fill(self.borderColor) if self.focus: - if self.text != '': - self.height = self.font.size(self.text,self.fontSize)[1]+10 + if self.text != "": + self.height = self.font.size(self.text, self.fontSize)[1] + 10 else: - self.height = self.font.size('X',self.fontSize)[1]+10 - self.surface = _s((self.width,self.height)) + self.height = self.font.size("X", self.fontSize)[1] + 10 + self.surface = _s((self.width, self.height)) self.surface.fill(self.borderColor) - self.surface.draw.rect(self.abg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) - if self.text == '': - text = self.font.render(self.hint,self.fontSize,self.hintColor) + self.surface.draw.rect( + self.abg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) + if self.text == "": + text = self.font.render(self.hint, self.fontSize, self.hintColor) else: - text = self.font.render(self.text,self.fontSize,self.afg) + text = self.font.render(self.text, self.fontSize, self.afg) try: - last = self.text.split('\n')[-1] - except: + last = self.text.split("\n")[-1] + except Exception as _: last = self.text x = 10 - if self.font.size(last,self.fontSize)[0] >= self.surface.size[0]-20: - x = self.surface.size[0]-self.font.size(last,self.fontSize)[0] - self.surface.blit(text,(x,self.surface.size[1]/2-text.size[1]/2)) + if self.font.size(last, self.fontSize)[0] >= self.surface.size[0] - 20: + x = self.surface.size[0] - self.font.size(last, self.fontSize)[0] + self.surface.blit(text, (x, self.surface.size[1] / 2 - text.size[1] / 2)) for i in _k.getPressed().items(): if i[1]: if i[0] not in self.wclk: if len(i[0]) == 1: self.insert(i[0]) - elif i[0] == 'backspace': + elif i[0] == "backspace": self.delete() - elif i[0] == 'return': - if self.maxSymbols != None: + elif i[0] == "return": + if self.maxSymbols is not None: if len(self.text) > self.maxSymbols: continue - self.text += '\n' - elif i[0] == 'space': - self.insert(' ') + self.text += "\n" + elif i[0] == "space": + self.insert(" ") self.wclk.append(i[0]) else: if i[0] in self.wclk: self.wclk.remove(i[0]) self.tick += 1 if self.tick >= 60: - if self.text != '': - points = [[x+self.font.size(last,self.fontSize)[0], - self.surface.size[1]-(self.font.size('X',self.fontSize)[1])], - [x+self.font.size(last,self.fontSize)[0], - self.surface.size[1]/2-text.size[1]/2+self.surface.size[1]-10]] - self.surface.draw.line(self.lineColor,points[0],points[1],3) + if self.text != "": + points = [ + [ + x + self.font.size(last, self.fontSize)[0], + self.surface.size[1] + - (self.font.size("X", self.fontSize)[1]), + ], + [ + x + self.font.size(last, self.fontSize)[0], + self.surface.size[1] / 2 + - text.size[1] / 2 + + self.surface.size[1] + - 10, + ], + ] + self.surface.draw.line(self.lineColor, points[0], points[1], 3) if self.tick == 120: self.tick = 0 else: - self.surface.draw.rect(self.bg,_r(self.borderWidth,self.borderWidth, - self.surface.size[0]-self.borderWidth*2, - self.surface.size[1]-self.borderWidth*2)) - if self.text == '': - text = self.font.render(self.hint,self.fontSize,self.hintColor) + self.surface.draw.rect( + self.bg, + _r( + self.borderWidth, + self.borderWidth, + self.surface.size[0] - self.borderWidth * 2, + self.surface.size[1] - self.borderWidth * 2, + ), + ) + if self.text == "": + text = self.font.render(self.hint, self.fontSize, self.hintColor) else: - text = self.font.render(self.text,self.fontSize,self.fg) + text = self.font.render(self.text, self.fontSize, self.fg) try: - last = self.text.split('\n')[-1] - except: + last = self.text.split("\n")[-1] + except Exception as _: last = self.text - x = self.surface.size[0]/2-text.size[0]/2 - if self.font.size(last,self.fontSize)[0] >= self.surface.size[0]-20: - x = self.surface.size[0]-self.font.size(last,self.fontSize)[0] - self.surface.blit(text,(x,self.surface.size[1]/2-text.size[1]/2)) + x = self.surface.size[0] / 2 - text.size[0] / 2 + if self.font.size(last, self.fontSize)[0] >= self.surface.size[0] - 20: + x = self.surface.size[0] - self.font.size(last, self.fontSize)[0] + self.surface.blit(text, (x, self.surface.size[1] / 2 - text.size[1] / 2)) - if position != None: - if self.surface.rect(position[0], - position[1]).contains(_m.getPosition()[0], - _m.getPosition()[1]): + if position is not None: + if self.surface.rect(position[0], position[1]).contains( + _m.getPosition()[0], _m.getPosition()[1] + ): if not self.wcl: _m.setCursor(pygame.SYSTEM_CURSOR_HAND) else: if not self.ws: _m.setCursor(pygame.SYSTEM_CURSOR_ARROW) self.ws = True - if _m.isPressed('left'): + if _m.isPressed("left"): if not self.wcl: - self.focus=self.focus==0 + self.focus = self.focus == 0 self.wcl = True else: self.wcl = False @@ -124,33 +157,55 @@ class textarea(widget): if not self.wsnr: _m.setCursor(pygame.SYSTEM_CURSOR_ARROW) self.wsnr = True - if _m.isPressed('left'): + if _m.isPressed("left"): self.focus = False - def insert(self,text): + + def insert(self, text): if _ct.WinDLL("User32.dll").GetKeyState(0x14): text = text.upper() - if pygame.key.get_pressed()[pygame.K_LSHIFT] or pygame.key.get_pressed()[pygame.K_RSHIFT]: - text = text.translate(dict(zip(map(ord, '''1234567890-=[]\\;'''+"',./`"), - '''!@#$%^&*()_+{}|:"<>?~'''))) - if hex(getattr(_ct.windll.LoadLibrary("user32.dll"), - "GetKeyboardLayout")(0))=='0x4190419': - text = text.translate(dict(zip(map(ord, - '''qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~'''), - '''йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё'''))) + if ( + pygame.key.get_pressed()[pygame.K_LSHIFT] + or pygame.key.get_pressed()[pygame.K_RSHIFT] + ): + text = text.translate( + dict( + zip( + map(ord, """1234567890-=[]\\;""" + "',./`"), + """!@#$%^&*()_+{}|:"<>?~""", + ) + ) + ) + if ( + hex(getattr(_ct.windll.LoadLibrary("user32.dll"), "GetKeyboardLayout")(0)) + == "0x4190419" + ): + text = text.translate( + dict( + zip( + map( + ord, + """qwertyuiop[]asdfghjkl;'zxcvbnm,./`QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?~""", + ), + """йцукенгшщзхъфывапролджэячсмитьбю.ёЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,Ё""", + ) + ) + ) if text in self.blacklist: return - if self.whitelist != None: + if self.whitelist is not None: if text not in self.whitelist: return - if self.maxSymbols != None: + if self.maxSymbols is not None: if len(self.text) > self.maxSymbols: return self.text += text - def delete(self,symbols=1): - self.text = self.text[:0-symbols] + + def delete(self, symbols=1): + self.text = self.text[: 0 - symbols] + def draw(self, win, pos): self._generate(pos) - win.blit(self.surface,pos) + win.blit(self.surface, pos) + def get(self): return self.text - diff --git a/src/pygwin2/ui/widget/tip.py b/src/pygwin2/ui/widget/tip.py index 038eaed..30100f2 100644 --- a/src/pygwin2/ui/widget/tip.py +++ b/src/pygwin2/ui/widget/tip.py @@ -1,55 +1,71 @@ -import ...pygame from ...surface import surface as _s -from ...font import defaultFont as _df -from ...image import load as _l +from ...font import deaultFont as _df from ...rect import rect as _r -import ...mouse as _m -import ...keyboard as _k -import ctypes as _ct -import copy as _copy +from ... import mouse as _m +from .base import widget + class tip(widget): - def __init__(self,text,responceWidth,responceHeight,fontSize=15,font=_df, - borderColor=(180,180,50),borderWidth=2,bg=(255,255,128), - fg=(35,35,5),waitBeforeShowing=0, - tipPosRelativeCursor=(10,10)): + def __init__( + self, + text, + responceWidth, + responceHeight, + fontSize=15, + font=_df, + borderColor=(180, 180, 50), + borderWidth=2, + bg=(255, 255, 128), + fg=(35, 35, 5), + waitBeforeShowing=0, + tipPosRelativeCursor=(10, 10), + ): super()._args(locals()) self.tick = -1 - self.lcp = (0,0) + self.lcp = (0, 0) self.tprc = self.tipPosRelativeCursor self._generate() + def _generate(self, position=None): - self.surface = _s((self.responceWidth, - self.responceHeight)) - if position != None: + self.surface = _s((self.responceWidth, self.responceHeight)) + if position is not None: self.tick += 1 if self.lcp != _m.getPosition(): self.tick = 0 self.lcp = _m.getPosition() if self.tick >= self.waitBeforeShowing: mp = _m.getPosition() - mp = [mp[0]+self.tprc[0]-position[0], - mp[1]+self.tprc[1]-position[1]] - rect = _r(mp[0],mp[1], - self.font.size(self.text,self.fontSize)[0]+4, - self.font.size(self.text,self.fontSize)[1]+6) - if mp[0]<0 or mp[1]<0:return - if mp[0]>self.responceWidth:return - if mp[1]>self.responceHeight:return - if mp[0]>self.responceWidth-rect.w: - mp[0]=self.responceWidth-rect.w - if mp[1]>self.responceHeight-rect.h: - mp[1]=self.responceHeight-rect.h - rect = _r(mp[0],mp[1], - self.font.size(self.text,self.fontSize)[0]+4, - self.font.size(self.text,self.fontSize)[1]+6) - self.surface.draw.rect(self.bg,rect) - self.surface.draw.rect( - self.borderColor,rect,self.borderWidth) - ts = self.font.render( - self.text,self.fontSize,self.fg) - self.surface.blit(ts,(mp[0]+2,mp[1]+3)) + mp = [ + mp[0] + self.tprc[0] - position[0], + mp[1] + self.tprc[1] - position[1], + ] + rect = _r( + mp[0], + mp[1], + self.font.size(self.text, self.fontSize)[0] + 4, + self.font.size(self.text, self.fontSize)[1] + 6, + ) + if mp[0] < 0 or mp[1] < 0: + return + if mp[0] > self.responceWidth: + return + if mp[1] > self.responceHeight: + return + if mp[0] > self.responceWidth - rect.w: + mp[0] = self.responceWidth - rect.w + if mp[1] > self.responceHeight - rect.h: + mp[1] = self.responceHeight - rect.h + rect = _r( + mp[0], + mp[1], + self.font.size(self.text, self.fontSize)[0] + 4, + self.font.size(self.text, self.fontSize)[1] + 6, + ) + self.surface.draw.rect(self.bg, rect) + self.surface.draw.rect(self.borderColor, rect, self.borderWidth) + ts = self.font.render(self.text, self.fontSize, self.fg) + self.surface.blit(ts, (mp[0] + 2, mp[1] + 3)) + def draw(self, win, pos): self._generate(pos) - win.blit(self.surface,pos) - + win.blit(self.surface, pos) diff --git a/src/pygwin2/window.py b/src/pygwin2/window.py index fa45869..df8611f 100644 --- a/src/pygwin2/window.py +++ b/src/pygwin2/window.py @@ -3,12 +3,14 @@ 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 @@ -16,6 +18,7 @@ import sys import threading import mouse + class _win(_surface): def __init__(self, iconpath=None): self._orig = pygame.display.get_surface() @@ -26,44 +29,59 @@ class _win(_surface): self._iconpath = iconpath self._isallowdrag = False if iconpath is not None: - self.tray = _tray(self.title,iconpath) + 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]: + 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() @@ -71,6 +89,7 @@ class _win(_surface): self.tray.stop() except Exception as _: pass + def focus(self): if not nonwin: self.hide() @@ -78,40 +97,53 @@ class _win(_surface): 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) + 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 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: + 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() + 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: @@ -119,30 +151,35 @@ class _win(_surface): 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}') + 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'] + 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): + +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) + pygame.display.set_mode(size, pygame.RESIZABLE) if noframe: - pygame.display.set_mode(size,pygame.NOFRAME) + pygame.display.set_mode(size, pygame.NOFRAME) else: if title is not None: pygame.display.set_caption(title) @@ -150,23 +187,30 @@ def create(title=None, size=(0,0), icon=None, resizable=False, noframe=False): 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'): + + 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) + 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) + info["BasicLimitInformation"]["LimitFlags"] |= ( + win32job.JOB_OBJECT_LIMIT_BREAKAWAY_OK + ) + win32job.SetInformationJobObject( + hjob, win32job.JobObjectExtendedLimitInformation, info + ) return hjob + def assign_job(hjob): if nonwin: return @@ -176,26 +220,35 @@ def ramLimit(memory_limit): 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)): + 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) + 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()