I'm trying to use QDBusPendingCallWatcher to watch an async call. Some sample code like this:
{
// interface = new QDBusInterface(...);
QDBusPendingCall pcall = interface->asyncCall("query");
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this);
QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(handler(QDBusPendingCallWatcher*)));
}
and handler function:
void Client::handler(QDBusPendingCallWatcher* call)
{
QDBusPendingReply<QString> reply = *call;
// do something
}
My questions are:
It looks like QDBusPendingCallWatcher uses shared data pointer inside, is it safe to not manually delete the watcher pointer? Just leave the scope and forget it?
If I can let the smart pointer of pendingcall to do all the tricks, can I use just one QDBusPendingCallWatcher pointer in my class to watch all the async calls? Like this:
{
QDBusPendingCall pcall = interface->asyncCall("query");
watcher = new QDBusPendingCallWatcher(pcall, this);
QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(handleOne(QDBusPendingCallWatcher*)));
pcall = interface->asyncCall("anotherQuery");
watcher = new QDBusPendingCallWatcher(pcall, this);
QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(handleTwo(QDBusPendingCallWatcher*)));
}
Will this makes a disaster? Or should I use multiple pointers for each call?
Thanks!
Take a closer look at the QDBusPendingCallWatcher documentation:
The slot connected to by the above code could be something similar to the following:
void MyClass::callFinishedSlot(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<QString, QByteArray> reply = *call;
if (reply.isError()) {
showError();
} else {
QString text = reply.argumentAt<0>();
QByteArray data = reply.argumentAt<1>();
showReply(text, data);
}
call->deleteLater();
}
The call of QObject::deleteLater is the key: This means Qt will delete the Object as soon as execution returns to the event loop.
As long as you call deleteLater inside Client::handler(...), you don't need to - more precisely you musn't - call delete watcher; anywhere. The only thing you have to ensure is that noone uses the object behind call after the slot returns.
Related
I am trying to port an Xamarin.Forms app to .NET MAUI but have run into the deprecation of Device.StartTimer, whilst this obviously currently still works in MAUI, I am interested to find out what the alternative is?
Currently I have a wrapper class as follows:
public void Start()
{
if (IsRunning)
{
return;
}
var wrapper = new TaskWrapper(Task, IsRecurring, true);
Tasks.Add(wrapper);
Device.StartTimer(Interval, wrapper.RunTask);
}
I tried replacing this with a System.Timers.Timer however this led to the issue of not being able to modify UI elements due to being on the wrong thread? The timer wrapper itself is used in multiple places so I can't use binding for example in this case either.
Is there actually a direct replacement for Device.StartTimer? Any assistance is greatly appreciated.
The Device timer is obsolete in MAUI.
You can create an IDispatcherTimer instance and subscribe to the Tick event like this:
var timer = Application.Current.Dispatcher.CreateTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += (s,e) => DoSomething();
timer.Start();
Depending on the context that you're using the timer in, you should use the MainThread.BeginInvokeOnMainThread() method to update UI elements:
void DoSomething()
{
MainThread.BeginInvokeOnMainThread(() =>
{
//Update view here
});
}
More info on UI main thread:
https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/appmodel/main-thread
IDispatcherTimer timer;
timer = Dispatcher.CreateTimer();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += (s, e) =>
{
label.Text = DateTime.Now.ToString();
};
timer.Start();
https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/button#press-and-release-the-button
I want to save an alredy-existing QSettings object into some INI file for backup.
The QSettings comes from the application's global settings, ie. it can be registry, ini file, etc.
In case it helps, my context is:
class Params
{
// All params as data members
// ...
void loadGlobal ()
{
Qettings s; // Global parameters, paths set by application
// Fill data members: s.value (...);
}
};
class Algo
{
Result run (Params p)
{
Result r = F(p);
return r;
}
};
int main (...)
{
Params p;
p.loadGlobal ();
Algo a;
Result r = a.run (p);
// At this point, save Result and Params into a specific directory
// Is there a way to do:
p.saveToIni ("myparams.ini"); // <-- WRONG
}
A solution would be to add a saveTo (QSetting & s) method into the Params class:
class Params
{
void saveTo (QSettings & s)
{
s.setValue (...);
}
};
int main (...)
{
Params p;
p.loadGlobal ();
QSettings bak ("myparams.ini", ...);
p.saveTo (bak);
}
But I am looking for a solution without modifying the Params class.
Well, no, QT Doesn't really support this directly. I think your best bet is writing a helper class...something like:
void copySettings( QSettings &dst, QSettings &src )
{
QStringList keys = src.allKeys();
for( QStringList::iterator i = keys.begin(); i != keys.end(); i++ )
{
dst.setValue( *i, src.value( *i ) );
}
}
I think there are 2 issues:
QSettings does not have a copy constructor or assignment operator (that I know of), so you'll probably have to write your own copy using allKeys().
You can't save QSettings to an arbitrary file, but what you can do is set the path used for a specific format and scope using the static method QSettings::setPath(). Note that you need to do that before your backup QSettings object is created (and you would use format IniFormat).
If you're OK not having complete control over the resulting path, this should be sufficient. If not, you could still do the above, then get the file name using fileName() and use a system call to copy/move the file to the desired final location.
I would like to descend a directory, and examine the name of every file I see there against a regular expression. Basically, a version of the common unix find command, only written in Node.js. I don't care about the order of the files, but I do want to make sure I get all of them.
I have the following code, which is close (I think) to what I want. It takes a startdir, a regexp, and a callback; for each file it analyzes it increments the value of sentinel by one, and when it is done with the analysis it decrements the sentinel. My concern is that if there's one file, and a deeply nested collection of directories, it will analyze that file and trigger the callback long before it finds a second file, and possible the callback will be called twice.
Obviously, I could prevent the callback from being called twice by having a fired variable to restrain it from firing a second time. But that still would give me erroneous data. What am I doing wrong here, and is there a more node-appropriate way to do it?
fs = require('fs')
path = require('path')
function get_all_files(startdir, regexp, callback) {
var sentinel = 0;
var results = [];
function check_sentinel() {
sentinel--;
if (sentinel === 0) {
callback(results);
}
}
function check_file(dir, filename) {
var fname;
sentinel++;
if (regexp.test(filename)) {
results.push(path.join(dir, filename));
}
check_sentinel();
}
function check_directory(dir) {
fs.readdir(path.join(this.rootpath, dirpath), function(err, files) {
var fname, i, len, npath;
if (err) {
throw err
}
for (i = 0, len = files.length; i < len; i++) {
fname = files[i];
npath = path.join(dir, fname);
fs.stat(npath, function(err, stats) {
if (stats.isFile()) {
check_file(dir, fname);
} else {
if (stats.isDirectory()) {
check_directory(npath);
}
}
});
}
});
}
check_directory(startdir);
}
A couple of thoughts...
I have never used it, but the simplest way to do what you are asking might be to use the async.js walkfiles function. See the tests for an example here.
Otherwise, I would consider building an array of function calls and returning the array from your recursive directory walking function (rather than using a sentinel, etc). In other words, check_directory returns an array of function calls matching the files you are looking for. If there is no file, the array is empty.
Finally, combine the array at the top of the recursion and use the async library (not the same as async.js) to execute the array of functions all at once using the parallel function (see this thread for an example using "series").
This question doesn't relate only to MouseEvent.CLICK event type but to all event types that already exist in AS3. I read a lot about custom events but until now I couldn't figure it out how to do what I want to do. I'm going to try to explain, I hope you understand:
Here is a illustration of my situation:
for(var i:Number; i < 10; i++){
var someVar = i;
myClips[i].addEventListener(MouseEvent.CLICK, doSomething);
}
function doSomething(e:MouseEvent){ /* */ }
But I want to be able to pass someVar as a parameter to doSomething. So I tried this:
for(var i:Number; i < 10; i++){
var someVar = i;
myClips[i].addEventListener(MouseEvent.CLICK, function(){
doSomething(someVar);
});
}
function doSomething(index){ trace(index); }
This kind of works but not as I expect. Due to the function closures, when the MouseEvent.CLICK events are actually fired the for loop is already over and someVar is holding the last value, the number 9 in the example. So every click in each movie clip will call doSomething passing 9 as the parameter. And it's not what I want.
I thought that creating a custom event should work, but then I couldn't find a way to fire a custom event when the MouseEvent.CLICK event is fired and pass the parameter to it. Now I don't know if it is the right answer.
What should I do and how?
You really need to extend the event class to create your own event with extra parameters. Placing functions inside the addEventListener (anonymous functions) is a recipe for memory leaks, which is not good.
Take a look at the following.
import flash.events.Event;
//custom event class to enable the passing of strings along with the actual event
public class TestEvent extends Event
{
public static const TYPE1 :String = "type1";
public static const TYPE2 :String = "type2";
public static const TYPE3 :String = "type3";
public var parameterText:String;
public function TestEvent (type:String, searchText:String)
{
this.parameterText = searchText;
super(type);
}
}
when you create a new event such as
dispatchEvent(new TestEvent(TestEvent.TYPE1, 'thisIsTheParameterText'))" ;
you can then listen for that event like this
someComponent.addEventListener(TestEvent.TYPE1, listenerFunction, true , 0, true);
and inside the function 'listenerFunction' event.parameterText will contain your parameter.
so inside your myClips component you would fire off the custom event and listen for that event and not the Click event.
Without knowing more about your application, it seems more like you should use the target to pass parameters, or extend MouseEvent. The former would be more in line with common practice, though. So for example, if you exposed an integer public property on your "clip" object (whatever it is):
public class MyClip
{
public var myPublicProperty:int;
public function MyClip() { //... }
}
for (var i:int = 0; i < 10; i++)
{
myClips[i].myPublicProperty = i;
myClips[i].addEventListener(MouseEvent.CLICK, doSomething);
}
... and then, in your event listener, you could retrieve that property using either the target or currentTarget property of the event (probably currentTarget, in your case):
function doSomething(event:MouseEvent):void
{
trace(event.currentTarget.myPublicProperty.toString());
}
That ought to do it! Good luck.
private function myCallbackFunction(e:Event, parameter:String):void
{
//voila, here's your parameter
}
private function addArguments(method:Function, additionalArguments:Array):Function
{
return function(event:Event):void {method.apply(null, [event].concat(additionalArguments));}
}
var parameter:String = "A sentence I want to pass along";
movieClip.addEventListener(Event.COMPLETE, addArguments(myCallbackFunction, [parameter] ) );
Take advantage of the dynamic function construction in AS3.
You can accomplish this by getting your handler out of a function that gives the variable closure, like this:
for (var i=0; i<5; i++) {
myClips[i].addEventListener( MouseEvent.CLICK, getHandler(i) );
}
function getHandler(i) {
return function( e:MouseEvent ) {
test(i);
}
}
function test( j ) {
trace("foo "+j);
}
Also, as for why this creates a new closure, you might want to check the explanation in the accepted answer to this similar question.
Thanks so much for this usefull tips, this technique is better to understand than classes explanation.
for me I just started new code algorithm using this technique to solve link relation between timers array and viewports array, and update status by change text inside them frequently, by passing ID's with timers events.
like this:
var view:Object=[];
for(var i:uint=0;i<Camera.names.length;i++){
view[i]=getChildByName("Cam"+i);
//_________ Add Text _________
var tf:TextField = new TextField();
tf.autoSize = TextFieldAutoSize.LEFT;
tf.textColor=0xffffff;
view[i].tf=view[i].addChild(tf);
//_________ Add Timer _________
var t:Timer = new Timer(1000);
view[i].timer=t;
view[i].timer.start();
view[i].timer.addEventListener(TimerEvent.TIMER, addArg(i));
}
function addArg(adi:uint):Function {
return function(event:TimerEvent):void {
updatecamstatus(adi);
}
}
function updatecamstatus(vH:uint):void {
with (view[vH]){
tf.text="Cam" + vH + "\n";
tf.appendText("activityLevel: " + videosource.activityLevel + "\n");
tf.appendText("motionLevel: " + videosource.motionLevel + "\n");
}
}
I see your main goal isn't actually to create a custom MouseEvent.CLICK, but to pass a parameter to the function. You don't need to complicatedly create or extend anything. There's a simple and closure-trouble-free way to do it.
Just make your function like this:
function doSomething(index:Number):Function {
return function(e:MouseEvent):void {
// Use "e" and "index" here. They'll be unique for each addEventListener()
trace(index);
}
}
This technique can relate to any AS3 event type you can use addEventListener on.
And now you can add it like this:
var functionsDoSomething:Object;
for (var i:Number = 0; i < 10; i++) {
var someVar:Number = i;
functionsDoSomething[i] = doSomething(someVar);
myClips[i].addEventListener(MouseEvent.CLICK, functionsDoSomething[i]);
}
The doSomething(someVar) can be used directly on addEventListener(), but it's better to keep it in a variable because you'll be able to remove it later the same fashion you added it:
for (i = 0; i < 10; i++) {
myClips[i].removeEventListener(MouseEvent.CLICK, functionsDoSomething[i]);
}
The commonly used e.currentTarget.someCustomProperty works for dynamic objects (i.e. MovieClip), but will let you down at anything else (i.e. Sprite), forcing you to build a whole custom extended object/event for every type.
This solution deals with every "listenable" object and event. And this answer has more details and examples on it.
With ActionScript3 for Flash Player 9+, what is the nicest way to call a "once-off" function after exactly one frame?
I am aware of the Timer class and it's uses, and the callLater method on Flex UIComponents (which, glancing through the source, doesn't look very efficient in this scenario). I'm also aware of setTimeout (in flash.utils).
The Timer class and setTimeout utility are both time based, so how would we guarantee that our function will get called after exactly one frame?
From my limited testing it seems that functions passed to setTimeout only execute after at least one frame (try setting the delay to 0). But this is not guaranteed.
Of course, we could listen for Event.ENTER_FRAME events from a DisplayObject, but that seems like overkill for a once-off delayed function call.
Flex was intended to abstract away the frame-based nature of the Flash Player so you will not find much to help you with your problem. The best approach is to listen for ENTER_FRAME as you suggest. If that's overkill (and I'm not sure why you think it is), you could create a helper class which takes a DisplayObject and Function as arguments which will automatically add/remove the ENTER_FRAME event listener for you.
public class NextFrameCommand() {
private var functionToCall : Function;
public function NextFrameCommand(dObj: DisplayObject, func : Function) {
functionToCall = func;
}
public function start() : void {
dObj.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e : Event) : void {
e.target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
functionToCall.call();
}
}
I haven't tested that code but hopefully you get the idea....
Playing with the solutions provided by Theo and brd6644 I came us with this. It allows multiple functions (with parameters) to be queued and executed in order at the next frame.
public class DelayedFunctionQueue
{
protected var queue:Array;
protected var dispatcher:Sprite;
public function DelayedFunctionQueue()
{
queue = new Array();
dispatcher = new Sprite();
}
public function add( func:Function, ... args ):void
{
var delegateFn:Function = function():void
{
func.apply( null, args );
}
queue.push( delegateFn );
if ( queue.length == 1 )
{
dispatcher.addEventListener( Event.ENTER_FRAME, onEF, false, 0, true );
}
}
protected function onEF( event:Event ):void
{
dispatcher.removeEventListener( Event.ENTER_FRAME, onEF, false );
queue = queue.reverse();
while ( queue.length > 0 )
{
var delegateFn:Function = queue.pop();
delegateFn();
}
}
}
Might be useful to someone.
One way would be to see how many frames per second your project is set for and let the setTimeout function delay for 1 frame time within that setting.
So if your project is set at 24 frames per second, you delay for 42 millisec in setTimeout.
var timerSprite:Sprite = new Sprite();
timerSprite.addEventListener(Event.ENTER_FRAME, oneFrameHandeler);
function oneFrameHandeler(e:Event):void
{
timerSprite.removeEventListener(Event.ENTER_FRAME, oneFrameHandeler);
timerSprite = null;
trace("one frame later!")
}
ENTER_FRAME is not overkill - something like this is short and easy
addEventListener(Event.ENTER_FRAME, function(e:Event):void
{
removeEventListener(Event.ENTER_FRAME, arguments["callee"]);
onceOffFunction();
}