def loadYaml(self) -> dict: try: with open(self.filepath, "r") as yamlFile: return yaml.load(yamlFile, Loader=yaml.FullLoader) except Exception as e: Logger.get().error(e, exc_info=True) return None
def createDirIfEmpty(self) -> bool: if os.path.isdir(self.filepath): return True try: os.mkdir(self.filepath) except Exception as e: Logger.get().error(e, exc_info=True) return False return True
def update(self): try: resizedSurface = pygame.transform.smoothscale( self.getCurrentScreen(), self.scaledSize()) self.window.blit(resizedSurface, self.getCoord()) pygame.display.update() pygame.time.Clock().tick(60) except Exception as e: Logger.get().critical(e, exc_info=True) Logger.get().critical('Error updating pygame window!') self.doUpdate = False
def getText(self) -> str: # Combine prefix, text and suffix try: if self.surface.isState('selected') and self._editable: return self._prefix + self._text + '_' + self._suffix else: return self._prefix + self._text + self._suffix # Error, usually due to prefix, text or suffix not being str except: Logger.get().error('Error getting text for {}'.format(self.name), exc_info=True) return None
def __init__(self, icon: File, title: str, fullscreen: bool, windowScale: int, size: tuple): super().__init__() self.screensStack = [] self.doStackChange = False self.doUpdate = False # Set icon try: pygame.display.set_icon(pygame.image.load(icon.getPath())) except FileNotFoundError: Logger.get().error('No app icon image found at {}'.format( icon.getPath())) except Exception: Logger.get().error('Error loading app icon image {}!'.format( icon.getPath()), exc_info=True) # Set title try: pygame.display.set_caption(title) except Exception: Logger.get().error('Unable set display caption!', exc_info=True) # Set display self.width = size[0] self.height = size[1] if fullscreen: self.window = pygame.display.set_mode(self.size(), pygame.FULLSCREEN) # Get fullscreen window size windowWidth, windowHeight = self.window.get_size() # Set scaling self.scale = min(windowWidth / self.width, windowHeight / self.height) self.scaledWidth = int(self.width * self.scale) self.scaledWeight = int(self.height * self.scale) # Set coord to be center self.x = int((windowWidth - self.scaledWidth) / 2) self.y = int((windowHeight - self.scaledWeight) / 2) else: # Set scaling self.scale = windowScale self.scaledWidth = int(self.width * self.scale) self.scaledWeight = int(self.height * self.scale) # Set coord self.x = 0 self.y = 0 self.window = pygame.display.set_mode(self.scaledSize()) # Show display information Logger.get().debug(pygame.display.Info())
def loadWithState(self): if self._format.pos == 'top': self.surface.getScreen().blit(self.textSurface, self._frame.coord()) elif self._format.pos == 'bottom': self.surface.getScreen().blit(self.textSurface, (self._frame.x, self._frame.y + (self._frame.h - self.textHeight))) elif self._format.pos == 'center': self.surface.getScreen().blit( self.textSurface, (self._frame.x, self._frame.y + int( (self._frame.h - self.textHeight) / 2))) else: Logger.get().error('Unknown text postion type: "{}"'.format( self._format.pos))
def validateText(self) -> bool: # Check for regex matching valid = self._validation regexTexts = valid.regex.findall(self._text) Logger.get().debug('[{}] Regex matching result of {}'.format( self.item.name, regexTexts)) # Full match if len(regexTexts) == 1 and regexTexts[0] == self._text: if callable(valid.customMethod): return valid.customMethod(self._text) return True # Invalid based on regex else: return False
def changeStack(self, type_: str, screen: str = None) -> bool: # Notify another changeStack() is happening if self.doStackChange: Logger.get().warning( 'Another stack change is happening as well, this may cause issues.' ) self.doStackChange = True # Go back to previous screen if str(type_) == 'back': # Go back one screen if screen == None: self.screensStack.pop() # Go back to screen specified elif screen in self._container: self.screensStack = self.screensStack[:self.screensStack. index(screen) + 1] # Error else: Logger.get().error('"{}" is not a screen.'.format(screen)) return False # Load a new screen elif type_ == 'load': if screen in self._container: self.screensStack.append(screen) # Error else: Logger.get().error('"{}" is not a screen.'.format(screen)) return False # Error else: Logger.get().error('{} type not recognised.'.format(type_)) return False # Log change Logger.get().debug( 'Change stack completed with type:{} screen:{}'.format( type_, screen)) return True
def __init__(self, name: str, size: tuple): self.name = name self.frame = Frame(w=size[0], h=size[1]) # Logging App.LOGS_FOLDER.createDirIfEmpty() Logger.setUp(self.name, 5, "INFO", "DEBUG") # Resource self.resourceFiles = App.RESOURCES_FOLDER.getContainingFiles() # Font TextFormat.addCustomFonts( App.FONTS_FOLDER.getContainingFiles(withExtension=False, fileObject=False)) # Window self.window = Window(self.getResource("icon.png"), self.getName(), False, 1, size)
def mainloop(self, startScreen: str): # Start with startScreen self.screensStack.append(startScreen) while True: # fallback to startScreen if len(self.screensStack) == 0: self.screensStack.append(startScreen) Logger.get().error( 'No screen in stack, falling back to startScreen.') # Prep screen screen = self._container.get(self.screensStack[-1]) screen.start() screen.display() # Log current screen stacks Logger.get().debug('New screen stack of {}'.format( self.screensStack)) self.runScreen(screen) # When screen ends screen.end()
import os os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide" os.chdir(os.path.dirname(os.path.abspath(__file__))) # Dependency checking from code.api.utils.Dependency import Dependency with open("./requirements.txt", "r") as requirementsFile: packages = requirementsFile.read().split("\n") Dependency(packages).check() # App setup from code.api.App import App from code.api.utils.Logger import Logger from code.api.core.Screen import Screen from code.api.data.Text import TextFormat from code.api.utils.File import File from code.screens.home import home from code.screens.sort import sort app = App(name="A List of Sort v2", size=(1024, 768)) TextFormat.setDefaultFont(TextFormat.getCustomFont("Futura")) app.registerScreen(home()) app.registerScreen(sort()) Logger.get().info("STARTING APP") app.start("home")
def addScreen(self, screen: Screen): if not isinstance(screen, Screen): raise TypeError("Not an instance of Screen object.") self.addObject(screen.getName(), screen) Logger.get().debug('Added screen {}'.format(screen.getName()))
def copyTo(self, dst) -> bool: try: shutil.copyfile(self.filepath, dst.filepath) except Exception as e: Logger.get().error("Error copying file", exc_info=True)