Skip to content

Commit

Permalink
https://github.com/hasii2011/albow-python-3/issues/34
Browse files Browse the repository at this point in the history
  • Loading branch information
hasii2011 committed May 26, 2019
1 parent 8fff83d commit fa714c2
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 33 deletions.
62 changes: 36 additions & 26 deletions albow/core/RootWidget.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@

from typing import List

import sys

from time import sleep

from pygame.locals import *
Expand All @@ -16,19 +18,19 @@
from pygame.event import set_grab

from albow.core.Widget import Widget

from albow.core.Scheduler import Scheduler

from albow.core.CoreUtilities import CoreUtilities

from albow.core.CancelException import CancelException
from albow.core.ApplicationException import ApplicationException

from albow.media.MusicUtilities import MusicUtilities
from albow.core.UserEventCall import UserEventCall

MUSIC_END_EVENT = USEREVENT + 1
from albow.media.MusicUtilities import MusicUtilities

DOUBLE_CLICK_TIME = 300 # milliseconds
DOUBLE_CLICK_TIME = 300
"""
Time is in milliseconds
"""


class RootWidget(Widget):
Expand All @@ -39,9 +41,10 @@ class RootWidget(Widget):
The root widget can be found using the `RootWidget.get_root()`
"""
#
# surface Pygame display surface
# is_gl True if OpenGL surface
MUSIC_END_EVENT = USEREVENT + 1
"""
API consumer user events **MUST** start there events after this one
"""

root_widget = None
"""
Expand Down Expand Up @@ -70,30 +73,25 @@ class RootWidget(Widget):
"""
nextFrameDue = 0.0

do_draw = False
_is_gl_container = True
frame_time = 0.0
_use_sleep = True
do_draw = False
_is_gl_container = True
frame_time = 0.0
_use_sleep = True

last_mouse_event: Event = Event(0, {'pos': (0, 0), 'local': (0, 0)})

last_mouse_event: Event = Event(0)
userEventCallList: List = []

def __init__(self, surface: Surface, **kwds):
"""
Initializes the root widget with the given surface, which will normally be the PyGame screen,
but could be a subsurface of it.
Args:
surface: A pygame surface
surface: A Pygame surface
**kwds:
"""
RootWidget.last_mouse_event.dict['pos'] = (0, 0)
RootWidget.last_mouse_event.dict['local'] = (0, 0)

#
# Python 3 update
#
# Widget.__init__(self, surface.get_rect())
super().__init__(surface.get_rect(), **kwds)

CoreUtilities.init_timebase()
Expand Down Expand Up @@ -342,11 +340,20 @@ def run_modal(self, modal_widget: Widget):
event.dict['pos'] = RootWidget.last_mouse_event.pos
event.dict['local'] = RootWidget.last_mouse_event.local
RootWidget.last_mouse_event_handler.setup_cursor(event)
elif eventType == MUSIC_END_EVENT:
elif eventType == RootWidget.MUSIC_END_EVENT:
self.music_end()
elif eventType == USEREVENT:
if defer_drawing and not use_sleep:
RootWidget.ourTimerEvent = event
else:
#
# Maybe someone has register some user events handler
#
for cb in RootWidget.userEventCallList:
if cb.userEvent == eventType:
print(f"eventType: {eventType}")
cb.func(event)

except CancelException:
pass
#
Expand All @@ -368,9 +375,6 @@ def begin_frame(self):
"""Deprecated, use timer_event() instead."""
pass

# def get_root(self):
# return self

def has_focus(self):
return True

Expand Down Expand Up @@ -407,6 +411,12 @@ def getTopWidget():
def getFocus():
return RootWidget.top_widget.get_focus()

@staticmethod
def addUserEvent(newCallback: UserEventCall):

RootWidget.userEventCallList.append(newCallback)
print("addUserEvent")

# ========================================================================
#
# Abstract methods follow
Expand Down
11 changes: 11 additions & 0 deletions albow/core/UserEventCall.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

from typing import Callable

from dataclasses import dataclass


@dataclass
class UserEventCall:

func: Callable
userEvent: int
4 changes: 3 additions & 1 deletion albow/demo/DemoShell.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
from albow.demo.screens.DemoMenuBarScreen import DemoMenuBarScreen
from albow.demo.screens.DemoMusicScreen import DemoMusicScreen
from albow.demo.screens.DemoListBoxScreen import DemoListBoxScreen
from albow.demo.screens.DemoUserEventsScreen import DemoUserEventsScreen

from albow.demo.screens.LaunchDemosScreen import LaunchDemosScreen

DEMO_FRAME_TIME = 50 # ms
DEMO_FRAME_TIME = 50 # ms


class DemoShell(Shell):
Expand Down Expand Up @@ -54,6 +55,7 @@ def __init__(self, display):
self.menuBarScreen = DemoMenuBarScreen(self)
self.musicScreen = DemoMusicScreen(self)
self.listBoxScreen = DemoListBoxScreen(self)
self.userEventsScreen = DemoUserEventsScreen(self)

self.menu_screen = LaunchDemosScreen(self) # Do this last
self.set_timer(DEMO_FRAME_TIME)
Expand Down
8 changes: 8 additions & 0 deletions albow/demo/loggingConfiguration.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@
],
"propagate": "0"
},
"albow.demo.screens.DemoUserEventsScreen": {
"level": "INFO",
"handlers": [
"consoleHandler"
],
"propagate": "0"
},

"albow.media.EnableMusicControl": {
"level": "INFO",
"handlers": [
Expand Down
71 changes: 71 additions & 0 deletions albow/demo/screens/DemoUserEventsScreen.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@

import logging

from logging import Logger

import pygame
from pygame.event import Event

from albow.core.RootWidget import RootWidget
from albow.core.Shell import Shell
from albow.core.UserEventCall import UserEventCall

from albow.layout.Column import Column

from albow.demo.screens.BaseDemoScreen import BaseDemoScreen


class DemoUserEventsScreen(BaseDemoScreen):

CLOCK_EVENT = RootWidget.MUSIC_END_EVENT + 1
KLINGON_TORPEDO_EVENT = CLOCK_EVENT + 1

classLogger: Logger = None

def __init__(self, shell: Shell):

super().__init__(shell)

self.logger = logging.getLogger(__name__)
DemoUserEventsScreen.classLogger = self.logger

contentAttrs = {
"align": "c"
}

contents: Column = Column([self.backButton], **contentAttrs)

clockEventCall: UserEventCall = UserEventCall(func=DemoUserEventsScreen.userEventCallback, userEvent=DemoUserEventsScreen.CLOCK_EVENT)
ktkEventCall: UserEventCall = UserEventCall(func=DemoUserEventsScreen.userEventCallback, userEvent=DemoUserEventsScreen.KLINGON_TORPEDO_EVENT)

RootWidget.addUserEvent(clockEventCall)
RootWidget.addUserEvent(ktkEventCall)
self.add_centered(contents)

def enter_screen(self):
"""
Called from the Shell after switching to this screen from another screen.
"""
self.logger.info("Start timers")
pygame.time.set_timer(DemoUserEventsScreen.CLOCK_EVENT, 10 * 1000)
pygame.time.set_timer(DemoUserEventsScreen.KLINGON_TORPEDO_EVENT, 15 * 1000)

def leave_screen(self):
"""
Called from the Shell before switching away from this screen to another screen.
"""
#
# From the pygame official documentation
#
# To disable the timer for an event, set the milliseconds argument to 0.
#
self.logger.info("Stop timers")
pygame.time.set_timer(DemoUserEventsScreen.CLOCK_EVENT, 0)
pygame.time.set_timer(DemoUserEventsScreen.KLINGON_TORPEDO_EVENT, 0)

@staticmethod
def userEventCallback(theEvent: Event):

timeMSecs: float = theEvent.dict['time']
timeSecs: float = timeMSecs // 1000
DemoUserEventsScreen.classLogger.info(f"theEvent.type: '{theEvent.type}, time(seconds) since start: {timeSecs}")
13 changes: 7 additions & 6 deletions albow/demo/screens/LaunchDemosScreen.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
DEMO_TITLE_TEXT_SIZE = 24
DEMO_BUTTON_TEXT_SIZE = 12


class LaunchDemosScreen(Screen):
"""
Buttons
Expand All @@ -34,16 +35,16 @@ def __init__(self, shell: Shell):
super().__init__(shell)

self.shell = shell
f1 = ResourceUtility.get_font(DEMO_TITLE_TEXT_SIZE, Theme.BUILT_IN_FONT)
f1 = ResourceUtility.get_font(DEMO_TITLE_TEXT_SIZE, Theme.BUILT_IN_FONT)

title = Label("Albow Demonstration", font=f1)
emptyButton = Button("Empty", enabled=False)
# emptyButton = Button("Empty", enabled=False)

menuArray = [
[
self.screen_button("Text Screen", shell.text_screen),
self.screen_button("Text Fields", shell.fields_screen),
self.screen_button("Controls", shell.controls_screen),
self.screen_button("Text Screen", shell.text_screen),
self.screen_button("Text Fields", shell.fields_screen),
self.screen_button("Controls", shell.controls_screen),
],
[
self.screen_button("Animation", shell.anim_screen),
Expand All @@ -63,7 +64,7 @@ def __init__(self, shell: Shell):
[
self.screen_button("Music", shell.musicScreen),
self.screen_button("ListBox", shell.listBoxScreen),
emptyButton
self.screen_button("User Events", shell.userEventsScreen)
]
]

Expand Down

0 comments on commit fa714c2

Please sign in to comment.