Search code examples
multithreadingsmalltalkpharo

Waiting in Pharo v3


I want to implement a method called Piece>>userMovesFor:seconds, which during "seconds" time fetches keyboard input and depending on it, sends some msgs to existing objects to cause them to make some computations (i mean they don't branch the future execution flow).

So from what i know about the system i thought the method could be schematically something like this.

Piece>>userMovesFor:seconds
| keyboardInterfacer |
keyboardInterfacer:=KeystrokeInterpreter on:self.
keyboardInterfacer takeKeyboardFocus .
self sleep:40 seconds.
keyboardInterfacer releaseKeyboardFocus .

KeystrokeInterpreter would be a subclass of Morph. While having the focus it would handle the keystrokes through Morph>>handleKeystroke.

Piece>>sleep:seconds would do nothing but wait "seconds" time.

So at some point of the execution the Piece instance would be sleeping doing nothing while the Morph instance handles the keyboard input.

My questions are two.

1) Is there a way to implement Piece>>sleep such that doesn't cause the system to freeze (so the KeystrokeInterpreter instance could do his job)?

I've tried with Duration>>wait and also implementing a self calling wait message on my own, but both alternatives freeze the execution of all objects in the image.

2) Is there a better way to implment Piece>>userMovesFor?


Solution

  • Since you are using Morphic, #step would be your best bet. You implement it on your Morph, as well as #stepTime (how often to step). As long as your Morph is open in the world, the steps will keep firing. Probably it would be easiest to track the timeout in the Morph too and provide a callback from Piece to pass control back.