I have created a CGEventTap like this:
GetCurrentProcess(psn);
var mask = 1 << kCGEventLeftMouseDown | // CGEventMaskBit(kCGEventLeftMouseDown)
1 << kCGEventLeftMouseUp |
1 << kCGEventRightMouseDown |
1 << kCGEventRightMouseUp |
1 << kCGEventOtherMouseDown |
1 << kCGEventOtherMouseUp |
1 << kCGEventScrollWheel;
mouseEventTap = CGEventTapCreateForPSN(&psn, kCGHeadInsertEventTap, kCGEventTapOptionDefault, mask, null);
if (!mouseEventTap.isNull()) {
aRLS = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, mouseEventTap, 0);
CFRelease(mouseEventTap);
if (!aRLS.isNull()) {
aLoop = CFRunLoopGetCurrent();
CFRunLoopAddSource(aLoop, aRLS, kCFRunLoopCommonModes);
CFRelease(aRLS);
CFRelease(aLoop);
rez = CFRunLoopRunInMode(ostypes.CONST.kCFRunLoopCommonModes, 10, false); // figure out how to make this run indefinitely
// rez is 1 :(
}
}
My CFRunLoopRun is exiting immediately, instead of running for 10seconds. And it says code is 1 which means no sources are in that mode. But I clearly did a CFRunLoopAddSource to the common modes option kCFRunLoopRunFinished. The run loop mode mode has no sources or timers.. Anyone know whats up? This is on not-main thread.
You can't run a run loop in kCFRunLoopCommonModes. This is clearly stated in the documentation for CFRunLoopRunInMode().
kCFRunLoopCommonModes is a virtual mode. It's basically a set of other modes. It can only be used when adding (or removing) a source to a run loop to say "monitor this source when the run loop is run in any of the modes in the set". But when you run a run loop, you have to run it in a specific, real mode, not this virtual mode which represents a set of other modes.
I recommend that, when you're working on a private thread and only want to monitor private sources, that you add the source to a custom mode and run the run loop in that mode. A custom mode is just a string with a unique value. For example, something like "com.yourcompany.yourproject.yourmodespurpose". Using a custom mode makes sure that the run loop never does anything unexpected, like firing a source added by the frameworks.
You must not release aLoop. Functions that don't have "Create" or "Copy" in their name do not give you ownership.
You will need a loop around your call to CFRunLoopRunInMode() because it will return every time it handles an event from your source (kCFRunLoopRunHandledSource == 4) or hits the timeout (kCFRunLoopRunTimedOut == 3). You should break out of the loop if it ever returns anything else.
Related
Lets say you have a coroutine returning a task (using winrt to illustrate)
winrt::Windows::foundation::IAsyncOperation<int> my_coroutine(int i)
{
co_await winrt::resume_background();
Sleep(std::max(4 - i, 0));
co_return i;
}
and you want to in RxCpp like this:
range(0, 4)
| map(&my_coroutine)
| observe_on(observe_on_event_loop())
| subscribe<string>(println(cout))
;
// Output: 3 2 1 0
So the obvious problem is that we don't want map to pass an IAsyncOperation<int> to observe_on::on_next but rather we would have the coroutine call observe_on::on_next passing an int, when it returns its value.
Perhaps we could convert IAsyncOperation<int> to rxcpp::Observable<int> and use flat_map although it seams a bit wasteful to use a range-like monad when we only have a future monad.
Is there a easy way to do this with RxCpp? If it's rather complicated, I'm happy to know that so I can move on.
P.S. I'm actually co_awaiting winrt::resume_on_signal, so maybe RxCpp provides some similar functionality with event HANDLEs.
Edit: I suppose the obvious thing to do is just poll the futures on the event loop, pushing them (i.e. calling on_next) only when they have completed.
I have decided to give up on RxCpp, and am instead pursuing writing my pipeline with templates to take advantage of type deduction from lambda arguments (static polymorphism for refactoring rather than reuse).
I think the correct thing to do is just to not have the future at all
int my_function(int i)
{
Sleep(std::max(4 - i, 0));
return i;
}
and run this function on a thread pool
range(0, 4)
| observe_on(observe_on_thread_pool()) // doesn't actually exist
| map(&my_function)
| observe_on(observe_on_event_loop())
| subscribe<string>(println(cout))
;
// Output: 3 2 1 0
making sure that the observer it calls next on is thread safe.
And in rxcppv3 it shouldn't be too hard to write a custom operator in place of observe_on(observe_on_thread_pool()) | map:
const auto map_on_thread_pool = [](auto func){
return make_lifter([=](auto r){
return make_observer(r, [=](auto& r, auto v){
auto f = [=](){ r.next(func(v)); };
//On the windows thread pool
TrySubmitThreadpoolCallback(..); // what ever hacks are needed to run f
});
});
};
Recently I've updated my system and tried to recompile my Vulkan app (which uses Vulkan cpp binding) and got almost no output from vk::DebugUtilsMessengerEXT (except the string "Added messenger"). I set it up to std::cout every kind of callback, and it printed lots of information strings (before update). Does anyone know, what to do to bring back debug output?
Here is my debug messenger code:
// ...
vk::DebugUtilsMessengerCreateInfoEXT messengerInfo;
messengerInfo.setMessageSeverity(
vk::DebugUtilsMessageSeverityFlagBitsEXT::eError |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo |
vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose);
messengerInfo.setMessageType(
vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral |
vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation |
vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance);
messengerInfo.setPfnUserCallback(callback);
messengerInfo.setPUserData(nullptr);
if(instance.createDebugUtilsMessengerEXT(&messengerInfo, nullptr, &debugMessenger, loader) != vk::Result::eSuccess) throw std::runtime_error("Failed to create debug messenger!\n");
}
VKAPI_ATTR VkBool32 VKAPI_CALL System::callback(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, VkDebugUtilsMessageTypeFlagsEXT messageType, const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData)
{
std::cout << pCallbackData->pMessage << '\n';
return false;
}
"loader" is vk::DispatchLoaderDynamic
Seems like the trouble is not only with Vulkan-Hpp, but also with C Vulkan.
Did some testing and the callbacks seem to be working correctly. I'm thinking the issue here might be the removal of some old INFO messages for performance reasons -- see Vulkan-ValidationLayers commits 18BF5C637 and 523D9C775. If INFORMATION_BIT messages were enabled in SDK releases previous to 1.1.108, you'd have seen a ton of spew. If expected validation errors are not making it to your callback, please create a github issue in the VVL repo and we'll address it immediately.
How I'm doing it and it works, albeit not the latest SDK:
void VulkanContext::createInstance()
{
// create the list of required extensions
uint32_t glfwExtensionCount = 0;
const char **glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char *> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
auto layers = std::vector<const char *>();
if ( enableValidationLayers )
{
extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
layers.push_back("VK_LAYER_LUNARG_standard_validation");
}
vk::ApplicationInfo appInfo("Vulkan test", 1, "test", 1, VK_API_VERSION_1_1);
auto createInfo = vk::InstanceCreateInfo(
vk::InstanceCreateFlags(),
&appInfo,
static_cast<uint32_t>(layers.size()),
layers.empty() ? nullptr : layers.data(),
static_cast<uint32_t>(extensions.size()),
extensions.empty() ? nullptr : extensions.data()
);
instance = vk::createInstanceUnique(createInfo);
dispatcher = vk::DispatchLoaderDynamic(instance.get(), vkGetInstanceProcAddr);
if ( enableValidationLayers )
{
auto severityFlags = vk::DebugUtilsMessageSeverityFlagBitsEXT::eError
| vk::DebugUtilsMessageSeverityFlagBitsEXT::eWarning
| vk::DebugUtilsMessageSeverityFlagBitsEXT::eVerbose
| vk::DebugUtilsMessageSeverityFlagBitsEXT::eInfo;
auto typeFlags = vk::DebugUtilsMessageTypeFlagBitsEXT::eGeneral
| vk::DebugUtilsMessageTypeFlagBitsEXT::eValidation
| vk::DebugUtilsMessageTypeFlagBitsEXT::ePerformance;
messenger = instance->createDebugUtilsMessengerEXTUnique(
{{}, severityFlags, typeFlags, debugCallback},
nullptr,
dispatcher
);
}
}
Make sure you're enabling the debug extensions and validation layers.
Check that your loader/dispatcher is initialized correctly.
Try some of the other commands for creating the messenger, not sure but maybe the API changed and the severity flags are passed in the wrong place.
Make sure the validation layers are installed correctly, don't recall dealing with that myself but saw mentions that it can be an issue.
I am trying to model one of my project in promela for model checking. In that, i have N no of nodes in network. So, for each node I am making a process. Something like this:
init {
byte proc;
atomic {
proc = 0;
do
:: proc < N ->
run node (q[proc],proc);
proc++
:: proc >= N ->
break
od
}
}
So, basically, here each 'node' is process that will simulate each node in my network. Now, Node Process has 3 threads which run parallelly in my original implementation and within these three threads i have lock at some part so that three threads don't access Critical Section at the same time. So, for this in promela, i have done something like this:
proctype node (chan inp;byte ppid)
{
run recv_A()
run send_B()
run do_C()
}
So here recv_A, send_B and do_C are the three threads running parallelly at each node in the network. Now, the problem is, if i put lock in recv_A, send_B, do_C using atomic then it will put lock lock over all 3*N processes whereas i want a lock such that the lock is applied over groups of three. That is, if process1's(main node process from which recv_A is made to run) recv_A is in its CS then only process1's send_B and do_C should be prohibited to enter into CS and not process2's recv_A, send_B, do_C. Is there a way to do this?
Your have several options, and all revolve around implementing some kind of mutual exclusion algorithm among N processes:
Peterson Algorithm
Eisenberg & McGuire Algorithm
Lamport's bakery Algorithm
SzymaĆski's Algorithm
...
An implementation of the Black & White Bakery Algorithm is available here. Note, however, that these algorithms -maybe with the exception of Peterson's one- tend to be complicated and might make the verification of your system impractical.
A somewhat simple approach is to resort on the Test & Set Algorithm which, however, still uses atomic in the trying section. Here is an example implementation taken from here.
bool lock = false;
int counter = 0;
active [3] proctype mutex()
{
bool tmp = false;
trying:
do
:: atomic {
tmp = lock;
lock = true;
} ->
if
:: tmp;
:: else -> break;
fi;
od;
critical:
printf("Process %d entered critical section.\n", _pid);
counter++;
assert(counter == 1);
counter--;
exit:
lock = false;
printf("Process %d exited critical section.\n", _pid);
goto trying;
}
#define c0 (mutex[0]#critical)
#define c1 (mutex[1]#critical)
#define c2 (mutex[2]#critical)
#define t0 (mutex[0]#trying)
#define t1 (mutex[1]#trying)
#define t2 (mutex[2]#trying)
#define l0 (_last == 0)
#define l1 (_last == 1)
#define l2 (_last == 2)
#define f0 ([] <> l0)
#define f1 ([] <> l1)
#define f2 ([] <> l2)
ltl p1 { [] !(c0 && c1) && !(c0 && c2) && !(c1 && c2)}
ltl p2 { []((t0 || t1 || t2) -> <> (c0 || c1 || c2)) }
ltl p3 {
(f0 -> [](t0 -> <> c0))
&&
(f1 -> [](t1 -> <> c1))
&&
(f2 -> [](t2 -> <> c2))
};
In your code, you should use a different lock variable for every group of 3 related threads. The lock contention would still happen at a global level, but some process working inside the critical section would not cause other processes to wait other than those who belong to the same thread group.
Another idea is that to exploit channels to achieve mutual exclusion: have each group of threads share a common asynchronous channel which initially contains one token message. Whenever one of these threads wants to access the critical section, it reads from the channel. If the token is not inside the channel, it waits until it becomes available. Otherwise, it can go forward in the critical section and when it finishes it puts the token back inside the shared channel.
proctype node (chan inp; byte ppid)
{
chan lock = [1] of { bool };
lock!true;
run recv_A(lock);
run send_B(lock);
run do_C(lock);
};
proctype recv_A(chan lock)
{
bool token;
do
:: true ->
// non-critical section code
// ...
// acquire lock
lock?token ->
// critical section
// ...
// release lock
lock!token
// non-critical section code
// ...
od;
};
...
This approach might be the simplest to start with, so I would pick this one first. Note however that I have no idea on how that affects performance during verification time, and this might very well depend on how channels are internally handled by Spin. A complete code example of this solution can be found here in the file channel_mutex.pml.
To conclude, note that you might want to add mutual exclusion, progress and lockout-freedom LTL properties to your model to ensure that it behaves correctly. An example of the definition of these properties is available here and a code example is available here.
I currently use addLocalMonitorForEventsMatchingMask to monitor mouse events and I call it from main thread. It works great. However I now want to move it to off the main thread. Is there an alternative like something like creating a hidden window from a thread and doing NSRunLoop?
I read on the docs: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/MonitoringEvents/MonitoringEvents.html
The handlers are always called on the main thread. Both class methods return the monitor object, which the calling object does not own (and thus has no need to retain or release).
Is there any alternative that I can do from off main thread?
I can't setup callbacks on the mainthread from another thread. I'm using an FFI and its not capable of that right now.
Here is my code in case it helps, but I'm hoping for alternative to this for off main thread please:
myHandler_js = function(c_arg1__self, objc_arg1__aNSEventPtr) {
var cType = ostypes.API('objc_msgSend')(objc_arg1__aNSEventPtr, ostypes.HELPER.sel('type'));
cType = ctypes.cast(cType, ostypes.TYPE.NSEventType);
return objc_arg1__aNSEventPtr; // return null to block
};
myHandler_c = ostypes.TYPE.IMP_for_EventMonitorCallback.ptr(myHandler_js);
myBlock_c = ostypes.HELPER.createBlock(myHandler_c);
var rez_add = ostypes.API('objc_msgSend')(ostypes.HELPER.class('NSEvent'), ostypes.HELPER.sel('addLocalMonitorForEventsMatchingMask:handler:'), ostypes.TYPE.NSEventMask(ostypes.CONST.NSKeyDownMask), myBlock_c.address());
Solution is to use CGEventTap.
This one is having issues but Ill update it as soon as its ready:
GetCurrentProcess(psn);
var mask = 1 << kCGEventLeftMouseDown | // CGEventMaskBit(kCGEventLeftMouseDown)
1 << kCGEventLeftMouseUp |
1 << kCGEventRightMouseDown |
1 << kCGEventRightMouseUp |
1 << kCGEventOtherMouseDown |
1 << kCGEventOtherMouseUp |
1 << kCGEventScrollWheel;
mouseEventTap = CGEventTapCreateForPSN(&psn, kCGHeadInsertEventTap, kCGEventTapOptionDefault, mask, null);
if (!mouseEventTap.isNull()) {
aRLS = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, mouseEventTap, 0);
CFRelease(mouseEventTap);
if (!aRLS.isNull()) {
aLoop = CFRunLoopGetCurrent();
CFRunLoopAddSource(aLoop, aRLS, kCFRunLoopCommonModes);
CFRelease(aRLS);
CFRelease(aLoop);
rez = CFRunLoopRunInMode(ostypes.CONST.kCFRunLoopCommonModes, 10, false); // figure out how to make this run indefinitely
// rez is 1 :(
}
}
I am using NSDataDetector with NSTextCheckingTypeLink to search a string for links (e.g. https://stackoverflow.com/questions) within it. Generally, it works fine, but when the string contains certain very long links (200+ chars) followed by a space and another word, I get this assertion:
> DDRequire failed: the following assertion will only be logged once
>
> assertion on
> /SourceCache/MobileDataDetectorsCore/MobileDataDetectorsCore-154/Sources/PushDown/DDTokenCache.c:310
> "delta >= 0" failed :Bad shift in
> DDTokenCacheMoveStreamOffset, aborting
This is the kind of text that causes this:
> blog.somethingorother.com/2011/storynameetcmorestuff/utm_source/eedburnerutmmediumfeedutmcampaign/FeedanutmcontentGooglFeedfetcherutmcampaign/FeedanutmcontentGooglFeedfetcher/eedburnerutm_mediumfeedutmcampaign/FeedanutmcontentGooglFeedfetcherutmcampaign HEY
Does anyone know what's behind this or have any other insight into this?
Resolved: Problem is with UITextView data detectors.
Please go through UIDataDetectorTypes:
typedef NS_OPTIONS(NSUInteger, UIDataDetectorTypes) {
UIDataDetectorTypePhoneNumber = 1 << 0, // Phone number detection
UIDataDetectorTypeLink = 1 << 1, // URL detection
#if __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
UIDataDetectorTypeAddress = 1 << 2, // Street address detection
UIDataDetectorTypeCalendarEvent = 1 << 3, // Event detection
#endif
UIDataDetectorTypeNone = 0, // No detection at all
UIDataDetectorTypeAll = NSUIntegerMax // All types
};
If you set UIDataDetectorTypeAll or UIDataDetectorTypeAddress or UIDataDetectorTypeCalendarEvent then iOS creates problems on iOS5.0 and Above.
textview.dataDetectorTypes=UIDataDetectorTypeAll;
Or
textview.dataDetectorTypes=UIDataDetectorTypeAddress | UIDataDetectorTypeCalendarEvent;
Then sometimes it creates problem on iOS5.0 and above.
So you need to set data detectors explicitly :
textview.dataDetectorTypes = UIDataDetectorTypeLink | UIDataDetectorTypePhoneNumber;
You could preprocess the text replacing those links that make trouble.