#implement inside .mm not being ran? - c++

I have a C++ file that runs Obj-C stuff also but the Obj-C stuff does not seem to be getting ran (it compiles fine) but I get an error saying that the stuff obj-c is suppose to do (in this case register for growl) did not get ran.
growlwrapper.mm
#import "growlwrapper.h"
#implementation GrowlWrapper
- (NSDictionary *) registrationDictionaryForGrowl {
return [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObject:#"Upload"], GROWL_NOTIFICATIONS_ALL,
[NSArray arrayWithObject:#"Upload"], GROWL_NOTIFICATIONS_DEFAULT
, nil];
}
#end
void showGrowlMessage(std::string title, std::string desc) {
std::cout << "[Growl] showGrowlMessage() called." << std::endl;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[GrowlApplicationBridge setGrowlDelegate: #""];
[GrowlApplicationBridge
notifyWithTitle: [NSString stringWithUTF8String:title.c_str()]
description: [NSString stringWithUTF8String:desc.c_str()]
notificationName: #"Upload"
iconData: nil
priority: 0
isSticky: YES
clickContext: nil
];
[pool drain];
}
int main() {
showGrowlMessage("Hello World!", "This is a test of the growl system");
return 0;
}
growlwrapper.h
#ifndef growlwrapper_h
#define growlwrapper_h
#include <string>
#include <iostream>
#include <Cocoa/Cocoa.h>
#include <Growl/Growl.h>
using namespace std;
void showGrowlMessage(std::string title, std::string desc);
int main();
#endif
#interface GrowlWrapper : NSObject <GrowlApplicationBridgeDelegate>
#end
Any idea why it is not being ran?

You are setting your growl delegate to an empty string instead of an instance of your GrowlWrapper class.

Related

How to get if an application has focus on macOS?

I have the need to gather which application has focus. For this, my approach is to: list windows, get the one with focus, and finally, check which process and application shows it. If there were some: getWindowWithFocus(), it would be fantastic.
Requirements:
The program is implemented in C++, but could interface with objective-C if needed.
The program will run with root privileges.
The list of windows listed must include all users applications.
The returned window allows to get properties, such as it process and if it has UI-focus.
Ideally, no 3rd party tool is used, only standard libraries (STL, Unix APIs and macOS APIs, eventually Qt/Boost).
Must support HSierra to Big-Sur.
I managed to list all windows, but now I am struggling in detecting if a window has or not the focus.
The question:
Which API function can be used to check if a window has focus or not? Any sample?
Any better approach to this problem?
Previous research:
I created a POC/sample which list all windows, including some of it properties.
CGWindowListCopyWindowInfo
https://developer.apple.com/documentation/coregraphics/1455137-cgwindowlistcopywindowinfo?language=objc
DISCLAIM: this is a POC, just for demonstration, and miss required code quality for proper projects. For example, CFObjects are not released with the consequent memory leak.
#include <CoreFoundation/CoreFoundation.h>
#include <CoreGraphics/CGWindow.h> // CoreGraphics
#include <iostream>
int main()
{
CFArrayRef ref = CGWindowListCopyWindowInfo(kCGNullWindowID, 0);
CFIndex nameCount = CFArrayGetCount( ref );
std::cout << "NumCounts: " << nameCount << " windows" << std::endl;
for( int i = 0; i < nameCount ; ++i )
{
std::cerr << " -------- " << std::endl;
CFDictionaryRef dict = (CFDictionaryRef)CFArrayGetValueAtIndex( ref, i );
auto printKeys = [](const void* key, const void* value, void* context)
{
CFShow(key);
std::cerr << " ";
CFShow(value);
};
CFDictionaryApplyFunction(dict, printKeys, nullptr);
// Process PID can be extracted with key:kCGWindowOwnerPID
// DOES THIS WINDOW HAS FOCUS?
}
}
Here is an example, based on this solution, wrapped in C++ (well, actually mostly C).
The only found problem with it is, it must run in main thread, which is not convenient, but this is another topic.
main.cpp:
#include "focus_oc_wrapper.hpp"
#include <thread>
int main(int argc, const char * argv[])
{
FocusDetector::AppFocus focus;
focus.run();
//std::thread threadListener(&FocusDetector::AppFocus::run, &focus); //Does not works
//if (threadListener.joinable())
//{
// threadListener.join();
//}
}
focus_oc_wrapper.hpp
namespace FocusDetector
{
struct AppFocusImpl;
struct AppFocus
{
AppFocusImpl* impl=nullptr;
AppFocus() noexcept;
~AppFocus();
void run();
};
}
focus_oc_wrapper.mm
#include "focus_oc_wrapper.hpp"
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import "focus_oc.h"
namespace FocusDetector
{
struct AppFocusImpl
{
OCAppFocus* wrapped=nullptr;
};
AppFocus::AppFocus() noexcept: impl(new AppFocusImpl)
{
impl->wrapped = [[OCAppFocus alloc] init];
}
AppFocus::~AppFocus()
{
if (impl)
{
[impl->wrapped release];
}
delete impl;
}
void AppFocus::run()
{
[NSApplication sharedApplication];
[NSApp setDelegate:impl->wrapped];
[NSApp run];
}
}
focus_oc.h
#import <Foundation/Foundation.h>
#interface OCAppFocus : NSObject <NSApplicationDelegate>
{
NSRunningApplication *currentApp;
}
#property (retain) NSRunningApplication *currentApp;
#end
#implementation OCAppFocus
#synthesize currentApp;
- (id)init
{
if ((self = [super init]))
{
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
selector:#selector(activeAppDidChange:)
name:NSWorkspaceDidActivateApplicationNotification object:nil];
}
return self;
}
- (void)dealloc
{
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[super dealloc];
}
- (void)activeAppDidChange:(NSNotification *)notification
{
self.currentApp = [[notification userInfo] objectForKey:NSWorkspaceApplicationKey];
NSLog(#"App: %#", [currentApp localizedName]);
NSLog(#"Bundle: %#", [currentApp bundleIdentifier]);
NSLog(#"Exec Url: %#", [currentApp executableURL]);
NSLog(#"PID: %d", [currentApp processIdentifier]);
}
#end
CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
set(CMAKE_OSX_DEPLOYMENT_TARGET "10.13" CACHE STRING "Minimum OS X deployment version")
project("focus_detection")
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -framework CoreFoundation -framework AppKit")
set ( TESTCPP main.cpp focus_oc_wrapper.mm )
add_executable( ${PROJECT_NAME} ${TESTCPP} )

Invoke a QML function from C++

I am using Qt on my RPI3.
I found a QML example which is Tesla Car instrument cluster. You can access full code from here or here.
I successfully created a project and debugged it. Now I am trying to change a value in the QML code from C++ side. There is a timer in my C++ code every 30 seconds I am trying to change speed value in the QML code with using QMetaObject::inokeMethod(): function. I read all examples in here.
Here is my C ++ code
#ifndef MYTIMER_H
#define MYTIMER_H
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlComponent>
#include <QTimer>
#include <QtDebug>
class MyTimer : public QObject
{
Q_OBJECT
public:
MyTimer();
QTimer *timer;
int i=0;
public slots:
void MySlot();
};
#endif // MYTIMER_H
#include "mytimer.h"
MyTimer::MyTimer()
{
timer = new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(MySlot()));
timer->start(10000);
}
void MyTimer::MySlot()
{
i++;
if(i==3)
{
i=0;
QQmlEngine engine;
QQmlComponent component(&engine,QUrl(QStringLiteral("qrc:/Speedometer.qml")));
QObject *object = component.create();
QVariant speeds=100;
QVariant returnedValue;
QMetaObject::invokeMethod(object,"speedNeedleValue",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, speeds));
qDebug() << "From QML"<< returnedValue.toString();
delete object;
}
}
Here is QML code:
import QtQuick 2.4
import QtGraphicalEffects 1.0
Rectangle {
color: "transparent"
SpeedNeedle {
id: speedoNeedle
anchors.verticalCenterOffset: 0
anchors.centerIn: parent
focus: true
Keys.onPressed: {
if (event.key == Qt.Key_A) {
speedNeedleValue(100)
drive()
}
}
function speedNeedleValue(speeds) {
speedoNeedle.value = speeds
return ": I am here"
}
}
If I press the "A" button my speedNeedleValue(); function is working. And in debug page I can get the return data return ": I am here".
Problem is I can't set the speeds argument with invoke function.
Here is the debug page:
"https://preview.ibb.co/kqpvWS/rpi.png"
Every time interrupt I can get "I am here". but I also get " JIT is disabled.... " warning too.
Thank you for your answers.

How to get IMEI number in blackberry 10 native

I am trying to get the Default information of Hardware device in blackberry 10 native, So basically i am trying to access IMEI or SERIAL NUMBER of the device.
I havetried using following code
main.cpp
#include "applicationui.hpp"
#include <bb/cascades/Application>
#include <bb/device/HardwareInfo>
#include <QLocale>
#include <QTranslator>
#include <Qt/qdeclarativedebug.h>
using namespace bb::cascades;
Q_DECL_EXPORT int main(int argc, char **argv)
{
qmlRegisterUncreatableType<bb::device::HardwareInfo>("bb.device", 1, 0, "HardwareInfo", "");
Application app(argc, argv);
ApplicationUI appui;
return Application::exec();
}
applicationui.cpp
#include "applicationui.hpp"
#include <bb/cascades/Application>
#include <bb/cascades/QmlDocument>
#include <bb/cascades/AbstractPane>
#include <bb/device/HardwareInfo>
#include <bb/cascades/Label>
using namespace bb::cascades;
using namespace bb::device;
ApplicationUI::ApplicationUI() :
QObject()
{
HardwareInfo hwInfo;
QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
qml->setContextProperty("_hardware", &hwInfo);
AbstractPane *root = qml->createRootObject<AbstractPane>();
Application::instance()->setScene(root);
}
main.qml
Page {
Container {
Label {
id: showIMEI
}
Button {
text: "Click me"
onClicked: {
showIMEI.text = "IMEI = " + _hardware.serialNumber;
//showIMEI.text = "IMEI = " + _hardware.imei;
}
}
}
}
but when i click a button i am not getting any data either IMEI or SerialNumber instead of imei or serial number. But always i am getting error like
'_hardware' [undefined] is not an object.
Note: i have already added following library in my .PRO
LIBS += -lbbsystem
LIBS += -lbbdevice
LIBS += -lbbdata
and following permission to my XML file.
read_device_identifying_information
I have also researched through many link like,
Link1, Link2, Link3 and i have also read the official document of Blackberry but i am not getting proper way to achieve my task.
Try this,
main.cpp
#include "applicationui.hpp"
#include <bb/cascades/Application>
#include <bb/device/HardwareInfo.hpp>
#include <QLocale>
#include <QTranslator>
#include <Qt/qdeclarativedebug.h>
using namespace bb::cascades;
using namespace bb::device;
Q_DECL_EXPORT int main(int argc, char **argv)
{
qmlRegisterType<HardwareInfo>("bb.device",1,0,"HardwareInfo");
Application app(argc, argv);
// Create the Application UI object, this is where the main.qml file
// is loaded and the application scene is set.
ApplicationUI appui;
// Enter the application main event loop.
return Application::exec();
}
main.qml
import bb.cascades 1.0
import bb.device 1.0
Page {
Container {
Label {
id: label
// Localized text with the dynamic translation and locale updates support
text: qsTr("Hello World") + Retranslate.onLocaleOrLanguageChanged
textStyle.base: SystemDefaults.TextStyles.BigText
multiline: true
}
Button {
onClicked: {
label.text=hardwareinfo.imei
console.debug("imei\t"+hardwareinfo.imei)
console.debug("serialNumber \t"+hardwareinfo.serialNumber)
}
}
}
attachedObjects:[
HardwareInfo {
id: hardwareinfo
}
]
}

How to fix error: linker command failed with exit code 1 (use -v to see invocation)?

I am new to objective-C, here I develop an iPhone application which contains both C++ and Objective-C files using xcode 5.1. When I try to use the populated value of mytoken from CommunicationHandler.m to CallViewController.mm. I get an error "linker command failed with exit code 1 (use -v to see invocation)". I also try to initialize mytoken with extern but value cannot display at UserToken (CallViewController.mm)*. Please help me to solve my this problem, your help will be highly appreciated.
The following are CommunicationHandler.m and CallViewController.mm files with its .h files.
CommunicationHandler.m
// CommunicationHandler.m
#import "CommunicationHandler.h"
...
#implementation CommunicationHandler
NSString* mytoken;
...
-(NSString*) getToken
{
mytoken=try;
return mytoken;
}
CommunicationHandler.h
//CommuniationHandler.h
#import <Foundation/Foundation.h>
#import "SecKeyWrapper.h"
#interface CommunicationHandler : NSObject {
}
...
- (NSString *) getToken;
#end
CallViewController.mm
// CallViewController.mm
#import "CallViewController.h"
...
#implementation CallViewController
...
+(BOOL) makeAudioCallWithRemoteParty:(NSString *)remoteUri andSipStack:(NgnSipStack *)sipStack andtoken:(NSString *)UserToken{
[sipStack addHeaderName:#"UserToken:" andValue:getToken];
if(![NgnStringUtils isNullOrEmpty:remoteUri]){
NgnAVSession* audioSession = [[NgnAVSession makeAudioCallWithRemoteParty: remoteUri
andSipStack: [[NgnEngine sharedInstance].sipService getSipStack]] retain];
if(audioSession){
[idoubs2AppDelegate sharedInstance].audioCallController.sessionId = audioSession.id;
[[idoubs2AppDelegate sharedInstance].tabBarController presentModalViewController: [idoubs2AppDelegate sharedInstance].audioCallController animated: YES];
[audioSession release];
return YES;
}
}
return NO;
}
CallViewController.h
#import <UIKit/UIKit.h>
#import "iOSNgnStack.h"
#import "CommunicationHandler.h"
extern NSString* mytoken;
...
Try
#ifdef __cplusplus
extern 'C' {
#endif
extern NSString* mytoken;
#ifdef __cplusplus
}
#endif
If your CallViewController.h header is only included in C++ or Objective-C++ files you can skip the ifdef.
`

Can't make call from C++ To Java using JNI

I have a little project with cocos2d-x libraries. I'm trying to use C++ to call a Java function but i get a signal 11 exception at line:
// Get Status
status = jvm->GetEnv((void **) &env, JNI_VERSION_1_6);
But i don't know why this is happening.
In my Java class Getsocial.java exist this function:
private void tweet()
{
String score = "123";
String tweetUrl = "https://twitter.com/intent/tweet?text=Hello ! I have just got " + score + " points in mygame for Android !!!!";
Uri uri = Uri.parse(tweetUrl);
startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
This function launch navigator to post a tweet. Called from Java works fine.
In my C++ InterfaceJNI.h I have:
#ifndef __INTERFACE_JNI_H__
#define __INTERFACE_JNI_H__
#include "cocos2d.h"
class InterfaceJNI
{
public:
static void postMessageToFB();
static void postMessageToTweet();
protected:
};
#endif // __INTERFACE_JNI_H__
And in InterfaceJNI.cpp:
#include "InterfaceJNI.h"
#include "platform/android/jni/JniHelper.h"
#include jni.h >
#include android/log.h >
using namespace cocos2d;
void InterfaceJNI::postMessageToTweet()
{
int status;
JNIEnv *env;
JavaVM *jvm;
jmethodID mid;
jclass mClass;
bool isAttached = false;
CCLog("Static postMessageToTweet");
// Get Status
status = jvm->GetEnv((void **) &env, JNI_VERSION_1_6);
CCLog("Status: %d", status);
if(status AttachCurrentThread(&env, NULL);
CCLog("Status 2: %d", status);
if(status GetStaticMethodID(mClass, "tweet", "()V");
CCLog("mID: %d", mid);
if (mid!=0)
env->CallStaticVoidMethod(mClass, mid);
//-----------------------------------------------------------
CCLog("Finish");
if(isAttached)
jvm->DetachCurrentThread();
return;
}
This interface is called from a part of the code using:
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
InterfaceJNI::postMessageToTweet();
#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
ObjCCalls::trySendATweet();
#endif
What is happening to return a null pointer on jvm->GetEnv((void **) &env, JNI_VERSION_1_6); ?
It looks like your jvm variable is null or garbage. The version of Cocos2D-x I use has a class called JniHelper with a static ::getJavaVM(); method that you might want to use.
JavaVM* vm = JniHelper::getJavaVM();
JNIEnv* env;
vm->GetEnv((void**)&env,JNI_VERSION_1_4); // mine uses JNI_VERSION_1_4
Also, remember to "refresh" your eclipse project every time you build with NDK. You probably do already, but it's worth checking.