PyQt event propagation from ignorant model to view - user-interface

I'm trying to write a GUI in PyQt that has a network layer which should notify the GUI of any new messages that are received over the network. In C#, I would have written a delegate/event pair in my net class:
//event handler for propagating new message to GUI
public delegate void MessageReceived(String from, String msg);
public event MessageReceived messageReceived;
This way, all the GUI needs is a reference to the messageReceived variable (and the net class remains agnostic).
Now, I've read all about signals and slots in PyQt, but I haven't been able to find anything that explains how to replicate the above functionality. Any ideas?

I've only recently learned to appreciate the awesomeness of SIGNAL(), and it's not too complicated.
You'd want to create a new class that is threaded:
class NetworkThing(QtCore.QThread):
def __init__(self, parent = None):
super(NetworkThing, self).__init__(parent)
def run(self):
while True:
time.wait(1.0)
# Do your background stuff, and then emit:
self.emit(QtCore.SIGNAL('messageRecieved(QString)'), 'The response text.')
From within your main application initialization function, you need to prepare a new variable and a new SIGNAL() catcher:
self.networkThing = NetworkThing()
self.connect(self.networkThing, QtCore.SIGNAL('messageRecieved(QString)'), self.processEvent)
Now, the response of the networking thread it piped instantly to the function processEvent().
Just as a side note, the run() function of NetworkThing() is automatically run by PyQt4, so there is rarely a time when you manually call it. Instead, call self.networkThing.start().
If you want to look at a pretty nice example of this stuff, read this article: http://diotavelli.net/PyQtWiki/Threading,_Signals_and_Slots.

Related

Subclassing commands.Bot vs instantiating it

I usually see this in code:
class MyBotClient(commands.Bot):
async def on_ready()....
client = MyBotClient()
But I always do this in my code:
client = commands.Bot(command_prefix=....)
What is the difference between these two methods, and is there any advantage of either of them?
Customizability, Maintainability and Code Cleanliness
The difference is mainly customizability, maintainability and code cleanliness.
Code Cleanliness
I had like 10 variables that are an attribute of client, e.g.
bot = commands.Bot(...)
bot.x = ""
bot.y = 1
bot.z = 0.2
# and so on to like 10 lines...
when I created my own class, I put it in another file and the class is like
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
self.x = ""
self.y = 1
self.z = 0.2
# and so on...
Now my main file just cleanly creates the bot and runs it, simple, but this is mainly because it's open-source
Customizability
Subclassing allows you to extend, expand, and even diminish, or
degrade, the existing functions and coroutines. Perhaps to add extra
validation of parameters, perform additional processing to the
original function, or even to change the purpose of the function or
coroutine altogether.
From What Are the Benefits of Subclassing (Visual Basic)
You can add/change so much with a subclassed bot, for example, you can make a custom context class that is returned instead of the usual commands.Context, this would allow you to add custom functions/attributes to even the context. One of the things I did is that I overrode the send method of my custom context so that it replies to the user on every command
Maintainability
This kinda falls under code cleanliness as it makes the code easier to maintain/change in the future. Like all your events can stay in one place, and even in my example before, I had like 140 commands at the time, I wanted the bot to switch to the new discord reply system, I didn't need to replace ctx.send with ctx.reply everywhere in each file, I just overrode the send to use reply unless it's explicitly disallowed

Xamarin Async Constructor

For my application I need to fetch some data asynchronously and do some initialization for each page. Unfortunately, a constructor does not allow me to make asynchronous calls. I followed this article and put all of my code into the OnAppearing method. However, since then I ran into multiple issues since each platform handles the event a little bit differently. For example, I have pages where you can take pictures, on iOS the OnAppearing is called again every time after the camera is closed while Android doesn't. It doesn't seem like a reliable method for my needs, which is also described here:
Calls to the OnDisappearing and OnAppearing overrides cannot be treated as guaranteed indications of page navigation. For example, on iOS, the OnDisappearing override is called on the active page when the application terminates.
I am searching for a method/way where I can perform my own initialization. The constructor would be perfect for that but I cannot perform anything asynchronously in there. Please do not provide me with any work arounds, I am searching for a solution that is the "recommended" way or maybe someone with a lot of experience can tell me what they are doing. (I also don't want to .Wait() or .Result as it will lock my app)
You can use Stephen Cleary's excellent NotifyTaskCompletion class.
You can read more how it works and what to do/don't in these cases in Microsoft's excellent Async Programming : Patterns for Asynchronous MVVM Applications: Data Binding. The highlights of this topics are:
Let’s walk through the core method
NotifyTaskCompletion.WatchTaskAsync. This method takes a task
representing the asynchronous operation, and (asynchronously) waits
for it to complete. Note that the await does not use
ConfigureAwait(false); I want to return to the UI context before
raising the PropertyChanged notifications. This method violates a
common coding guideline here: It has an empty general catch clause. In
this case, though, that’s exactly what I want. I don’t want to
propagate exceptions directly back to the main UI loop; I want to
capture any exceptions and set properties so that the error handling
is done via data binding. When the task completes, the type raises
PropertyChanged notifications for all the appropriate properties.
A sample usage of it:
public class MainViewModel
{
public MainViewModel()
{
UrlByteCount = new NotifyTaskCompletion<int>(
MyStaticService.CountBytesInUrlAsync("http://www.example.com"));
}
public NotifyTaskCompletion<int> UrlByteCount { get; private set; }
}
Here, the demo is about binding the returned asynchronous value to some bindable property, but of course you can you is without any return value (for simple data loading).
This may be too simple to say, but you CAN run asynchronous tasks in the constructor. Just wrap it in an anonymous Task.
public MyConstructor() {
Task.Run(async () => {
<Your code>
}
}
Be careful when doing this though as you can get into resource conflict issues if you accidentally open the page twice.
Another thing I like to do is use an _isInit flag, which indicates a first time use, and then never again.

Use one instance of AsyncTask throughout Activity

I have a number of AsyncTask set up as individual classes. I reuse them throughout my app. I wonder, in places where the same AsyncTask may be needed more than one is it possible to use one instance of that custom AsyncTask class multiple times? This is really a cosmetic problem since it bothers me having redundant sections of code, especially when an AsyncTask uses a callback to communicate with it's starting activity.
I've tried to do it this way -
MyTask task = new MyTask(new someCallBackListener){
#Override
public void taskDone(boolean youDone){
}
});
And then in my activity just calling
task.execute(params);
This seems to work the first time, but I cannot execute it more than once. Do I really just need to initialize a new task each time I want to use it?
An asynctask can be executed only once as per the android documentation here(section Threading rules)which says
The task can be executed only once (an exception will be thrown if a
second execution is attempted.)
So its not possible to reuse an AsyncTask instance. Further this SO link would help you!
While you can't use twice the same instance I think you could reuse the callback implementation by creating the instance this way
new MyTask(this).execute(params);
and implementing the callback in the Activity or the Fragment like this
public class SomeActivity extends Activity implements MyTask.someCallBackListener {
//All the Activity code
public void taskDone(boolean youDone) {
}
}
This way, you can create multiple instances of your AsyncTask without those redundant sections of code that bother you.

Loose programming in high level languages, how, why and how much?

I'm writing my code in Haxe. This is quite irrelevant to the question though, as long as you keep in mind that it's a high level language and compareable with Java, ActionScript, JavaScript, C#, etc. (I'm using pseudocode here).
I'm going to work on a big project and am busy preparing now. For this question I'll create a small scenario though: a simple application which has a Main class (this one is executed when the application launches) and a LoginScreen class (this is basically a class that loads a login screen so that the user can login).
Typically I guess this would look like the following:
Main constructor:
loginScreen = new LoginScreen()
loginScreen.load();
LoginScreen load():
niceBackground = loader.loadBitmap("somebg.png");
someButton = new gui.customButton();
someButton.onClick = buttonIsPressed;
LoginScreen buttonIsPressed():
socketConnection = new network.SocketConnection();
socketConnection.connect(host, ip);
socketConnection.write("login#auth#username#password");
socketConnection.onData = gotAuthConfirmation;
LoginScreen gotAuthConfirmation(response):
if response == "success" {
//login success.. continue
}
This simple scenario adds the following dependencies and downsides to our classes:
Main will not load without LoginScreen
LoginScreen will not load without the custom loader class
LoginScreen will not load without our custom button class
LoginScreen will not load without our custom SocketConnection class
SocketConnection (which will have to be accessed by a lot of different classes in the future) has been set inside LoginScreen now, which is actually quite irrelevant from it, apart from the fact that the LoginScreen requires a socket connection for the first time
To solve these problems, I have been suggested to do "Event-Driven-Programming", or loose coupling. As far as I understand, this basically means that one has to make classes independent from each other and then bind them together in separate binders.
So question 1: is my view on it true or false? Does one have to use binders?
I heard Aspect Oriented Programming could help here. Unfortunately Haxe does not support this configuration.
However, I do have access to an event library which basically allows me to create a signaller (public var loginPressedSignaller = new Signaller()), to fire a signaller (loginPressedSignaller.fire()) and to listen to a signalller (someClass.loginPressedSignaller.bind(doSomethingWhenLoginPressed)).
So, with little further investigation I figured this would change my previous setup to:
Main:
public var appLaunchedSignaller = new Signaller();
Main constructor:
appLaunchedSignaller.fire();
LoginScreen:
public var loginPressedSignaller = new Signaller();
LoginScreen load():
niceBackground = !!! Question 2: how do we use Event Driven Programming to load our background here, while not being dependent on the custom loader class !!!
someButton = !!! same as for niceBackground, but for the customButton class !!!
someButton.onClick = buttonIsPressed;
LoginScreen buttonIsPressed():
loginPressedSignaller.fire(username, pass);
LoginScreenAuthenticator:
public var loginSuccessSignaller = new Signaller();
public var loginFailSignaller = new Signaller();
LoginScreenAuthenticator auth(username, pass):
socketConnection = !!! how do we use a socket connection here, if we cannot call a custom socket connection class !!!
socketConnection.write("login#auth#username#password");
This code is not finished yet, eg. I still have to listen for the server response, but you probably understand where I am getting stuck.
Question 2: Does this new structure make any sense? how should I solve the problems above mentioned in the !!! delimiters?
Then I heard about binders. So maybe I need to create a binder for each class, to connect everything together. Something like this:
MainBinder:
feature = new Main();
LoginScreenBinder:
feature = new LoginScreen();
MainBinder.feature.appLaunchedSignaller.bind(feature.load);
niceBackgroundLoader = loader.loadBitmap;
someButtonClass = gui.customButton();
etc... hopefully you understand what I mean. This post is getting a bit long so I have to wrap it up a bit.
Question 3: does this make any sense? Doesn't this make things unnecessarily complex?
Also, in the above "Binders" I only had to use classes which are instantiated once, eg. a login screen. What if there are multiple instances of a class, eg. a Player Class in a game of chess.
well, concerning the how, I would point out my 5 commandments to you. :)
For this question only 3 are really important:
single responsibility (SRP)
interface segregation (ISP)
dependency inversion (DIP)
Starting off with SRP, you have to ask yourself the question: "What is the responsibility of class X?".
The login screen is responsible for presenting an interface to the user to fill in and submit his login data. Thus
it makes sense for it to depend on the button class, because it needs the button.
it makes no sense it does all the networking etc.
First of all, you let's abstract the login service:
interface ILoginService {
function login(user:String, pwd:String, onDone:LoginResult->Void):Void;
//Rather than using signalers and what-not, I'll just rely on haXe's support for functional style,
//which renders these cumbersome idioms from more classic languages quite obsolete.
}
enum Result<T> {//this is a generic enum to return results from basically any kind of actions, that may fail
Fail(error:Int, reason:String);
Success(user:T);
}
typedef LoginResult = Result<IUser>;//IUser basically represent an authenticated user
From the point of view of the Main class, the login screen looks like this:
interface ILoginInterface {
function show(inputHandler:String->String->Void):Void;
function hide():Void;
function error(reason:String):Void;
}
performing login:
var server:ILoginService = ... //where ever it comes from. I will say a word about that later
var login:ILoginInterface = ... //same thing as with the service
login.show(function (user, pwd):Void {
server.login(user, pwd, function (result) {
switch (result) {
case Fail(_, reason):
login.error(reason);
case Success(user):
login.hide();
//proceed with the resulting user
}
});
});//for the sake of conciseness I used an anonymous function but usually, you'd put a method here of course
Now ILoginService looks a little titchy. But to be honest, it does all it needs to do. Now it can effectively be implemented by a class Server, that encapsulates all networking in a single class, having a method for each of the N calls your actual server provides, but first of all, ISP suggests, that many client specific interfaces are better than one general purpose interface. For the same reason ILoginInterface is really kept to its bare minimum.
No matter, how these two are actually implemented, you will not need to change Main (unless of course the interface changes). This is DIP being applied. Main doesn't depend on the concrete implementation, only on a very concise abstraction.
Now let's have some implementations:
class LoginScreen implements ILoginInterface {
public function show(inputHandler:String->String->Void):Void {
//render the UI on the screen
//wait for the button to be clicked
//when done, call inputHandler with the input values from the respective fields
}
public function hide():Void {
//hide UI
}
public function error(reason:String):Void {
//display error message
}
public static function getInstance():LoginScreen {
//classical singleton instantiation
}
}
class Server implements ILoginService {
function new(host:String, port:Int) {
//init connection here for example
}
public static function getInstance():Server {
//classical singleton instantiation
}
public function login(user:String, pwd:String, onDone:LoginResult->Void) {
//issue login over the connection
//invoke the handler with the retrieved result
}
//... possibly other methods here, that are used by other classes
}
Ok, that was pretty straight forward, I suppose. But just for the fun of it, let's do something really idiotic:
class MailLogin implements ILoginInterface {
public function new(mail:String) {
//save address
}
public function show(inputHandler:String->String->Void):Void {
//print some sort of "waiting for authentication"-notification on screen
//send an email to the given address: "please respond with username:password"
//keep polling you mail server for a response, parse it and invoke the input handler
}
public function hide():Void {
//remove the "waiting for authentication"-notification
//send an email to the given address: "login successful"
}
public function error(reason:String):Void {
//send an email to the given address: "login failed. reason: [reason] please retry."
}
}
As pedestrian as this authentication may be, from the point of view of the Main class,
this doesn't change anything and thus will work just as well.
A more likely scenario is actually, that your login service is on another server (possibly an HTTP server), that makes the authentication, and in case of success creates a session on the actual app server. Design-wise, this could be reflected in two separate classes.
Now, let's talk about the "..." I left in Main. Well, I'm lazy, so I can tell you, in my code you are likely to see
var server:ILoginService = Server.getInstance();
var login:ILoginInterface = LoginScreen.getInstance();
Of course, this is far from being the clean way to do it. The truth is, it's the easiest way to go and the dependency is limited to one occurrence, that can later be removed through dependency injection.
Just as a simple example for an IoC-Container in haXe:
class Injector {
static var providers = new Hash < Void->Dynamic > ;
public static function setProvider<T>(type:Class<T>, provider:Void->T):Void {
var name = Type.getClassName(type);
if (providers.exists(name))
throw "duplicate provider for " + name;
else
providers.set(name, provider);
}
public static function get<T>(type:Class<T>):T {
var name = Type.getClassName(type);
return
if (providers.exists(name))
providers.get(name);
else
throw "no provider for " + name;
}
}
elegant usage (with using keyword):
using Injector;
//wherever you would like to wire it up:
ILoginService.setProvider(Server.getInstance);
ILoginInterface.setProvider(LoginScreen.getInstance);
//and in Main:
var server = ILoginService.get();
var login = ILoginInterface.get();
This way, you practically have no coupling between the individual classes.
As to the question how to pass events between the button and the login screen:
this is just a matter of taste and implementation.
The point of event driven programming is that both the source and the observer are only coupled in the sense,
that the source must be sending some sort of notification and the target must be able to handle it.
someButton.onClick = handler; basically does exactly that, but it's just so elegant and concise you don't make a fuzz about it.
someButton.onClick(handler); probably is a little better, since you can have multiple handlers, although this is rarely required of UI components. But in the end, if you want signalers, go with signalers.
Now when it comes to AOP, it is not the right approach in this situation. It's not a clever hack to wire up components between one another, but about dealing with cross-cutting concerns, such as adding a log, a history or even things as a persistence layer across a multitude of modules.
In general, try not to modularize or split the little parts of your application.
It is ok to have some spaghetti in your codebase, as long as
the spaghetti segments are well encapsulated
the spaghetti segments are small enough to be understood or otherwise refactored/rewritten in a reasonable amount of time, without breaking the app (which point no. 1 should guarantee)
Try rather to split the whole application into autonomous parts, which interact through concise interfaces. If a part grows too big, refactor it just the same way.
edit:
In response to Tom's questions:
that's a matter of taste. in some frameworks people go as far as using external configuration files, but that makes little sense with haXe, since you need to instruct the compiler to force compilation of the dependencies you inject at runtime. Setting up the dependency in your code, in a central file, is just as much work and far simpler. For more structure, you can split the app into "modules", each module having a loader class responsible for registering the implementations it provides. In your main file, you load the modules.
That depends. I tend to declare them in the package of the class depending on them and later on refactor them to an extra package in case they prove to be needed elsewhere. By using anonymous types, you can also completely decouple things, but you'll have a slight performance hit on platforms as flash9.
I wouldn't abstract the button and then inject an implementation through IoC, but feel free to do so. I would explicitely create it, because in the end, it's just a button. It has a style, a caption, screen position and size and fires click events. I think, this is unnecessary modularization, as pointed out above.
Stick to SRP. If you do, no class will grow unneccessarily big. The role of the Main class is to initialize the app. When done, it should pass control to a login controller, and when that controller acquires a user object, it can pass it on to the main controller of the actual app and so forth. I suggest you read a bit about behavioral patterns to get some ideas.
greetz
back2dos
First of all, I'm not familiar with Haxe at all. However, I would answer that what is described here sounds remarkably similar to how I've learned to do things in .NET, so it sounds to me like this is good practice.
In .NET, you have an "Event" that fires when a user clicks a button to do something (like logon) and then a method executes to "handle" the event.
There will always be code that describes what method is executed in one class when an event in another class is fired. It is not unnecessarily complex, it is necessarily complex. In the Visual Studio IDE, much of this code is hidden in "designer" files, so I don't see it on a regular basis, but if your IDE doesn't have this functionality, you've got to write the code yourself.
As for how this works with your custom loader class, I hope someone here can provide you an answer.

How do I listen to all Seam contextual events with parameterized names?

Seam will fire different kinds of events that relate to particular scopes, tasks, or processes and appends the name of the scope, task or process to the end of the event.
How do I listen to all the events of a type?
E.g. for any <name> I'd like to listen to events such as these:
org.jboss.seam.createProcess.<name> — called when the process is created
org.jboss.seam.endProcess.<name> — called when the process ends
org.jboss.seam.initProcess.<name> — called when the process is associated with the conversation
org.jboss.seam.startTask.<name> — called when the task is started
org.jboss.seam.endTask.<name> — called when the task is ended
I need to do this despite not knowing the list of valid names up front... :-(
I hope to be using #Observer to create the observer, or something similar, and I'll listen to up to two event classes in the same component.
You can easily do this by replacing Seam's Events class with your own implementation. Then look for events that are raised that start with a particular string:
#Scope(ScopeType.STATELESS)
#BypassInterceptors
#Name("org.jboss.seam.core.events")
#Install(precedence=APPLICATION)
public class Events extends org.jboss.seam.core.Events
{
#Override
public void raiseEvent(String type, Object... parameters )
{
super.raiseEvent( type, parameters );
if ( type.startsWith( "org.jboss.seam.createProcess" ) )
{
super.raiseEvent( "org.jboss.seam.createProcess", parameters );
}
//etc.
}
}
You can now observe "org.jboss.seam.createProcess" to get all createProcess events.
Inside the if, you must write super.raiseEvent(...) otherwise you'll get an infinite loop.

Resources