usage of copy_Path after stroke() or fill() - gtk

How is it possible to copy a path after a call to stroke() or fill() ?
I've setup a caching mecanism which looks like that
high end visual object class:
override void DrawDirect(canvas aCanvas)
{
aCanvas.Line(...)
aCanvas.Rectangle(...)
// etc.
MyCache = aCanvas.GetPath(); // = canvas.Context.copy_Path()
IsCached = true;
}
override void DrawCache(canvas aCanvas)
{
aCanvas.DrawPath(MyCache); // = canvas.Context.appendPath...
}
and the super class has this method:
voidDraw(canvas aCanvas)
{
if(IsCached) DrawCache();
else DrawDirect;
}
the canvas defines this kind of methods:
void Line(...)
{
Context.moveTo(...)
Context.lineTo(...)
Context.stroke();
}
when I call GetPath, MyCache.numData is equal to 0 unless I comment the calls to stroke() and to fill().
But as a side effect the DrawDirect methods do (visually) nothing.
One other subsequent question would be: is calling appendPath (really) faster than calling the basic "direct" methods ? (you can comment about this, I'll only accept answers about the copy_Path stuff).

Cairo has stroke() which deletes the path after stroking and stroke_preserve() which does not touch the path and leaves it as-is.
I don't really know if appendPath() is faster than re-creating the path directly, but I really cannot imagine that something like this should be a performance issue. It likely depends on your paths anyway and you should just benchmark this yourself.

Related

VSCode extension API: simple local Quick Diff

Trying to understand how to implement simple source control management in my language extension.
I need to show a Quick Diff for a single file (my extension doesn't work with folders) compared with some special one.
Let's say i have this TextDocumentContentProvider and QuickDiffProvider:
class MyLangDocumentContentProvider implements vscode.TextDocumentContentProvider
{
provideTextDocumentContent(uri: vscode.Uri)
{
return getFileText(uri); // returns text of provided file uri
}
}
class MyLangRepository implements vscode.QuickDiffProvider
{
provideOriginalResource(uri: vscode.Uri)
{
return getOriginalFileUri(uri); // returns uri of the special file to compare with
}
}
Then in activate method of extension i initialize them:
const docProvider = new MyLangDocumentContentProvider();
const gitSCM = vscode.scm.createSourceControl('git', 'Git');
gitSCM.quickDiffProvider = new MyLangRepository();
const workingTree = gitSCM.createResourceGroup('workingTree', 'Changes');
workingTree.resourceStates = [
{ resourceUri: vscode.window.activeTextEditor.document.uri }
];
Then i need to call registerTextDocumentContentProvider with some custom uri scheme. So why do i need custom uri scheme? And what else should i do to track changes of current file relative to the special one?
I was looking at vscode-extension-samples/source-control-sample, but it looks more complicated then my case.
Thanks for any advices!
Though my question was rather sily, let me save here some kind of instruction, how I've done this.
to make QuickDif work you don't need neither ResourceGroups nor TextDocumentContentProvider, this is a separate functionality.
SourceControl (and also its quickDiffProvider) will work if you pass some root directory in constructor (I've got no luck without thoug I don't need it for my purpose).

Multicast Delegates - C++

I would like to receive a multicast event from the LeapMotion plugin in C++. From their documentation, they mention the following things:
> On Hand Grabbed Event called when a leap hand grab gesture is
> detected. Signature: const FLeapHandData&, Hand, see FLeapHandData
>
> FLeapHandSignature OnHandGrabbed;
So in my .cpp file I added the following:
ALeapMotionGesture::ALeapMotionGesture()
{
PrimaryActorTick.bCanEverTick = true;
Leap = CreateDefaultSubobject<ULeapComponent>(TEXT("Leap"));
}
void ALeapMotionGesture::BeginPlay()
{
Super::BeginPlay();
if (Leap != nullptr) {
FScriptDelegate Delegate;
Delegate.BindUFunction(this, FName("HandGrabbed"));
Leap->OnHandGrabbed.Add(Delegate);
}
}
void ALeapMotionGesture::HandGrabbed(const FLeapHandData& Hand) {
UE_LOG(LogTemp, Warning, TEXT("Hand Grabbed"));
}
As it is the first time I'm using delegates in Unreal/C++, I would like to know how I could make it work?
It compiles fine however I do not receive any events.
Add UFUNCTION() on your function HandGrabbed
Short Answer
Replace:
void ALeapMotionGesture::BeginPlay()
{
Super::BeginPlay();
if (Leap != nullptr) {
FScriptDelegate Delegate;
Delegate.BindUFunction(this, FName("HandGrabbed"));
Leap->OnHandGrabbed.Add(Delegate);
}
}
with:
void ALeapMotionGesture::BeginPlay()
{
Super::BeginPlay();
if (Leap != nullptr) {
Leap->OnHandGrabbed.AddDynamic(this, &ALeapMotionGesture::HandGrabbed);
}
}
Long Answer
ULeapComponent::OnHandGrabbed is a FLeapHandSignature which is declared with DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam.
The LeapMotion README says to consult the Multi-cast documentation, but they are using dynamic delegates, so you actually need to read the Dynamic Delegates documentation. There you will see you should use the AddDynamic helper macro which generates the function name string for you.
Dynamic Delegates make use of helper macros that take care of generating the function name string for you.
From the Dynamic Delegates doc:
Dynamic Delegate Binding
BindDynamic( UserObject, FuncName )
Helper macro for calling BindDynamic() on dynamic delegates.
Automatically generates the function name string.
AddDynamic( UserObject, FuncName )
Helper macro for calling AddDynamic() on dynamic multi-cast delegates.
Automatically generates the function name string.
RemoveDynamic( UserObject, FuncName )
Helper macro for calling RemoveDynamic() on dynamic multi-cast
delegates. Automatically generates the function name string.
Side Note
Dynamic delegates are serialized, which sometimes results in unexpected behavior. For example, you can have delegate functions being called even though your code is no longer calling AddDynamic (because a serialized/saved actor serialized the results of your old code) or you might call AddDynamic even though the deserialization process already did that for you. To be safe, you probably should call RemoveDynamic before AddDynamic. Here's a snippet from FoliageComponent.cpp:
// Ensure delegate is bound (just once)
CapsuleComponent->OnComponentBeginOverlap.RemoveDynamic(this, &AInteractiveFoliageActor::CapsuleTouched);
CapsuleComponent->OnComponentBeginOverlap.AddDynamic(this, &AInteractiveFoliageActor::CapsuleTouched);

How can I chain promises in Swift inside a loop?

I'm building a Swift-based iOS application that uses PromiseKit to handle promises (although I'm open to switching promise library if it makes my problem easier to solve). There's a section of code designed to handle questions about overwriting files.
I have code that looks approximately like this:
let fileList = [list, of, files, could, be, any, length, ...]
for file in fileList {
if(fileAlreadyExists) {
let overwrite = Promise<Bool> { fulfill, reject in
let alert = UIAlertController(message: "Overwrite the file?")
alert.addAction(UIAlertAction(title: "Yes", handler: { action in
fulfill(true)
}
alert.addAction(UIAlertAction(title: "No", handler: { action in
fulfill(false)
}
} else {
fulfill(true)
}
}
overwrite.then { result -> Promise<Void> in
Promise<Void> { fulfill, reject in
if(result) {
// Overwrite the file
} else {
// Don't overwrite the file
}
}
}
However, this doesn't have the desired effect; the for loop "completes" as quickly as it takes to iterate over the list, which means that UIAlertController gets confused as it tries to overlay one question on another. What I want is for the promises to chain, so that only once the user has selected "Yes" or "No" (and the subsequent "overwrite" or "don't overwrite" code has executed) does the next iteration of the for loop happen. Essentially, I want the whole sequence to be sequential.
How can I chain these promises, considering the array is of indeterminate length? I feel as if I'm missing something obvious.
Edit: one of the answers below suggests recursion. That sounds reasonable, although I'm not sure about the implications for Swift's stack (this is inside an iOS app) if the list grows long. Ideal would be if there was a construct to do this more naturally by chaining onto the promise.
One approach: create a function that takes a list of the objects remaining. Use that as the callback in the then. In pseudocode:
function promptOverwrite(objects) {
if (objects is empty)
return
let overwrite = [...] // same as your code
overwrite.then {
do positive or negative action
// Recur on the rest of the objects
promptOverwrite(objects[1:])
}
}
Now, we might also be interested in doing this without recursion, just to avoid blowing the call stack if we have tens of thousands of promises. (Suppose that the promises don't require user interaction, and that they all resolve on the order of a few milliseconds, so that the scenario is realistic).
Note first that the callback—in the then—happens in the context of a closure, so it can't interact with any of the outer control flow, as expected. If we don't want to use recursion, we'll likely have to take advantage of some other native features.
The reason you're using promises in the first place, presumably, is that you (wisely) don't want to block the main thread. Consider, then, spinning off a second thread whose sole purpose is to orchestrate these promises. If your library allows to explicitly wait for a promise, just do something like
function promptOverwrite(objects) {
spawn an NSThread with target _promptOverwriteInternal(objects)
}
function _promptOverwriteInternal(objects) {
for obj in objects {
let overwrite = [...] // same as your code
overwrite.then(...) // same as your code
overwrite.awaitCompletion()
}
}
If your promises library doesn't let you do this, you could work around it by using a lock:
function _promptOverwriteInternal(objects) {
semaphore = createSemaphore(0)
for obj in objects {
let overwrite = [...] // same as your code
overwrite.then(...) // same as your code
overwrite.always {
semaphore.release(1)
}
semaphore.acquire(1) // wait for completion
}
}

D: Delegates or callbacks?

I found conception of Delegates pretty hard for me. I really do not understand why I can't simply pass one function to another and need to wrap it to Delegate. I read in docs that there is some cases when I do not know it's name and Delegate is only way to call it.
But now I have trouble in understanding conception of callbacks. I tried to find more information, but I can't understand is it's simply call of other function or what is it.
Could you show examples of D callbacks and explain where they can be helpful?
import vibe.d;
shared static this()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, &handleRequest);
}
void handleRequest(HTTPServerRequest req,
HTTPServerResponse res)
{
if (req.path == "/")
res.writeBody("Hello, World!", "text/plain");
}
&handleRequest is it callback? How it's work and at what moment it's start?
So within memory a function is just a pile of bytes. Like an array, you can take a pointer to it. This is a function pointer. It has a type of RETT function(ARGST) in D. Where RETT is the return type and ARGST are the argument types. Of course attributes can be applied like any function declaration.
Now delegates are a function pointer with a context pointer. A context pointer can be anything from a single integer (argument), call frame (function inside of another) or lastly a class/struct.
A delegate is very similar to a function pointer type at RETT delegate(ARGST). They are not interchangeable, but you can turn a function pointer into a delegate pointer pretty easily.
The concept of a callback is to say, hey I know you will know about X so when that happens please tell me about X by calling this function/delegate.
To answer your question about &handleRequest, yes it is a callback.
You can pass functions to other functions to later be called.
void test(){}
void receiver(void function() fn){
// call it like a normal function with 'fn()'
// or pass it around, save it, or ignore it
}
// main
receiver(&test); // 'test' will be available as 'fn' in 'receiver'
You need to prepend the function name as argument with & to clarify you want to pass a function pointer. If you don't do that, it will instead call that function due to UFCS (calling without braces). It is not a delegate yet.
The function that receives your callable may do whatever it wants with it. A common example is in your question, a web service callback. First you tell the framework what should be done in case a request is received (by defining actions in a function and making that function available for the framework), and in your example enter a loop with listenHTTP which calls your code when it receives a request. If you want to read more on this topic: https://en.wikipedia.org/wiki/Event_(computing)#Event_handler
Delegates are function pointers with context information attached. Say you want to add handlers that act on other elements available in the current context. Like a button that turns an indicator red. Example:
class BuildGui {
Indicator indicator;
Button button;
this(){
... init
button.clickHandler({ // curly braces: implicit delegate in this case
indicator.color = "red"; // notice access of BuildGui member
});
button.clickHandler(&otherClickHandler); // methods of instances can be delegates too
}
void otherClickHandler(){
writeln("other click handler");
}
}
In this imaginary Button class all click handlers are saved to a list and called when it is clicked.
There were several questions in the OP. I am going to try to answer the following two:
Q: Could you show examples of D callbacks and explain where they can be helpful?
A: They are commonly used in all languages that support delegates (C# for an example) as event handlers. - You give a delegate to be called whenever an event is triggered. Languages that do not support delegates use either classes, or callback functions for this purpose. Example how to use callbacks in C++ using the FLTK 2.0 library: http://www.fltk.org/doc-2.0/html/group__example2.html. Delegates are perfect for this as they can directly access the context. When you use callbacks for this purpose you have to pass along all the objects you want to modify in the callback... Check the mentioned FLTK link as an example - there we have to pass a pointer to the fltk::Window object to the window_callback function in order to manipulate it. (The reason why FLTK does this is that back FLTK was born C++ did not have lambdas, otherwise they would use them instead of callbacks)
Example D use: http://dlang.org/phobos/std_signals.html
Q: Why I can't simply pass one function to another and need to wrap it to Delegate?
A: You do not have to wrap to delegates - it depends what you want to accomplish... Sometimes passing callbacks will just work for you. You can't access context in which you may want to call the callback, but delegates can. You can, however pass the context along (and that is what some C/C++ libraries do).
I think what you are asking is explained in the D language reference
Quote 1:
A function pointer can point to a static nested function
Quote 2:
A delegate can be set to a non-static nested function
Take a look at the last example in that section and notice how a delegate can be a method:
struct Foo
{
int a = 7;
int bar() { return a; }
}
int foo(int delegate() dg)
{
return dg() + 1;
}
void test()
{
int x = 27;
int abc() { return x; }
Foo f;
int i;
i = foo(&abc); // i is set to 28
i = foo(&f.bar); // i is set to 8
}
There are already excellent answers. I just want to try to make simple summary.
Simply: delegate allows you to use methods as callbacks.
In C, you do the same by explicitly passing the object (many times named context) as void* and cast it to (hopefully) right type:
void callback(void *context, ...) {
/* Do operations with context, which is usually a struct */
doSomething((struct DATA*)context, ...);
doSomethingElse((struct DATA*)context, ...);
}
In C++, you do the same when wanting to use method as callback. You make a function taking the object pointer explicitly as void*, cast it to (hopefully) right type, and call method:
void callback(void* object, ...) {
((MyObject*)object)->method(...);
}
Delegate makes this all implicitly.

why not using method call instead of using properties?

I'm studying Swift language, and in github.com, i found SwiftHelper.
In it's IntHelper.swift file, I found below code:
extension Int {
var isEven: Bool {
let remainder = self % 2
return remainder == 0
}
var isOdd: Bool {
return !isEven
}
}
why isEven and isOdd were written as properties, not method calls?
In this situation, Using property has any advantage over using method calls?
In purely technical terms, there are no advantages or disadvantages to using a property over a method or vice versa* : the only difference is in readability.
In this particular case, I think that using an extension property makes for better readability than using a method call, because it reads better. Compare
if myInt.isOdd {
... // Do something
}
vs.
if myInt.isOdd() {
... // Do something
}
vs.
if isOdd(myInt) {
... // Do something
}
The first (property) and second (method) code fragments keeps words in the same order as they are in English, contributing to somewhat better readability. However, the second one adds an unnecessary pair of parentheses. For completeness, the third way of accomplishing the same task (a function) is less readable than the other two.
* This also applies to other languages that support properties, for example, Objective-C and C#.
The properties used in the extension are what's known as 'computed properties' - which in a lot of ways are like a method :) in that they don't store any state themselves, but rather return some computed value.
The choice between implementing a 'property' vs. a 'method' for something like this can be thought of in semantic terms; here, although the value is being computed, it simply serves to represent some information about the state of the object (technically 'struct' in the case of Int) in the way that you would expect a property to, and asking for that state isn't asking it to modify either itself or any of its dependencies.
In terms of readability, methods in Swift (even those without arguments) still require parens - you can see the difference that makes in this example:
// as a property
if 4.isEven { println("all is right in the world") }
// as a method
if 5.isEven() { println("we have a problem") }