1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
|
/*
==============================================================================
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-8-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
==============================================================================
*/
namespace juce
{
/*
Note that a lot of methods that you'd expect to find in this file actually
live in juce_posix_SharedCode.h!
*/
#define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
FIELD (activityInfo, "activityInfo", "Landroid/content/pm/ActivityInfo;")
DECLARE_JNI_CLASS (AndroidResolveInfo, "android/content/pm/ResolveInfo")
#undef JNI_CLASS_MEMBERS
//==============================================================================
JavaVM* androidJNIJavaVM = nullptr;
jobject androidApkContext = nullptr;
//==============================================================================
JNIEnv* getEnv() noexcept
{
if (androidJNIJavaVM != nullptr)
{
JNIEnv* env;
androidJNIJavaVM->AttachCurrentThread (&env, nullptr);
return env;
}
// You did not call Thread::initialiseJUCE which must be called at least once in your apk
// before using any JUCE APIs. The Projucer will automatically generate java code
// which will invoke Thread::initialiseJUCE for you.
jassertfalse;
return nullptr;
}
static void JNICALL juce_JavainitialiseJUCE (JNIEnv* env, jobject /*jclass*/, jobject context)
{
JNIClassBase::initialiseAllClasses (env, context);
Thread::initialiseJUCE (env, context);
}
extern "C" jint JNIEXPORT JNI_OnLoad (JavaVM* vm, void*)
{
// Huh? JNI_OnLoad was called two times!
jassert (androidJNIJavaVM == nullptr);
androidJNIJavaVM = vm;
auto* env = getEnv();
// register the initialisation function
auto juceJavaClass = env->FindClass ("com/rmsl/juce/Java");
if (juceJavaClass != nullptr)
{
JNINativeMethod method {"initialiseJUCE", "(Landroid/content/Context;)V",
reinterpret_cast<void*> (juce_JavainitialiseJUCE)};
auto status = env->RegisterNatives (juceJavaClass, &method, 1);
jassert (status == 0);
}
else
{
// com.rmsl.juce.Java class not found. Apparently this project is a library
// or was not generated by the Projucer. That's ok, the user will have to
// call Thread::initialiseJUCE manually
env->ExceptionClear();
}
return JNI_VERSION_1_2;
}
//==============================================================================
class JuceActivityWatcher final : public ActivityLifecycleCallbacks
{
public:
JuceActivityWatcher()
{
checkActivityIsMain (androidApkContext);
}
void onActivityStarted (jobject activity) override
{
auto* env = getEnv();
checkActivityIsMain (activity);
ScopedLock lock (currentActivityLock);
if (currentActivity != nullptr)
{
// see Clarification June 2001 in JNI reference for why this is
// necessary
LocalRef<jobject> localStorage (env->NewLocalRef (currentActivity));
if (env->IsSameObject (localStorage.get(), activity) != 0)
return;
env->DeleteWeakGlobalRef (currentActivity);
currentActivity = nullptr;
}
if (activity != nullptr)
currentActivity = env->NewWeakGlobalRef (activity);
}
void onActivityStopped (jobject activity) override
{
auto* env = getEnv();
ScopedLock lock (currentActivityLock);
if (currentActivity != nullptr)
{
// important that the comparison happens in this order
// to avoid race condition where the weak reference becomes null
// just after the first check
if (env->IsSameObject (currentActivity, activity) != 0
|| env->IsSameObject (currentActivity, nullptr) != 0)
{
env->DeleteWeakGlobalRef (currentActivity);
currentActivity = nullptr;
}
}
}
LocalRef<jobject> getCurrent()
{
ScopedLock lock (currentActivityLock);
return LocalRef<jobject> (getEnv()->NewLocalRef (currentActivity));
}
LocalRef<jobject> getMain()
{
ScopedLock lock (currentActivityLock);
return LocalRef<jobject> (getEnv()->NewLocalRef (mainActivity));
}
static JuceActivityWatcher& getInstance()
{
static JuceActivityWatcher activityWatcher;
return activityWatcher;
}
private:
void checkActivityIsMain (jobject context)
{
auto* env = getEnv();
ScopedLock lock (currentActivityLock);
if (mainActivity != nullptr)
{
if (env->IsSameObject (mainActivity, nullptr) != 0)
{
env->DeleteWeakGlobalRef (mainActivity);
mainActivity = nullptr;
}
}
if (mainActivity == nullptr)
{
LocalRef<jobject> appContext (getAppContext());
auto mainActivityPath = getMainActivityClassPath();
if (mainActivityPath.isNotEmpty())
{
auto clasz = env->GetObjectClass (context);
auto activityPath = juceString (LocalRef<jstring> ((jstring) env->CallObjectMethod (clasz, JavaClass.getName)));
// This may be problematic for apps which use several activities with the same type. We just
// assume that the very first activity of this type is the main one
if (activityPath == mainActivityPath)
mainActivity = env->NewWeakGlobalRef (context);
}
}
}
static String getMainActivityClassPath()
{
static String mainActivityClassPath;
if (mainActivityClassPath.isEmpty())
{
LocalRef<jobject> appContext (getAppContext());
if (appContext != nullptr)
{
auto* env = getEnv();
LocalRef<jobject> pkgManager (env->CallObjectMethod (appContext.get(), AndroidContext.getPackageManager));
LocalRef<jstring> pkgName ((jstring) env->CallObjectMethod (appContext.get(), AndroidContext.getPackageName));
LocalRef<jobject> intent (env->NewObject (AndroidIntent, AndroidIntent.constructWithString,
javaString ("android.intent.action.MAIN").get()));
intent = LocalRef<jobject> (env->CallObjectMethod (intent.get(),
AndroidIntent.setPackage,
pkgName.get()));
LocalRef<jobject> resolveInfo (env->CallObjectMethod (pkgManager.get(), AndroidPackageManager.resolveActivity, intent.get(), 0));
if (resolveInfo != nullptr)
{
LocalRef<jobject> activityInfo (env->GetObjectField (resolveInfo.get(), AndroidResolveInfo.activityInfo));
LocalRef<jstring> jName ((jstring) env->GetObjectField (activityInfo.get(), AndroidPackageItemInfo.name));
LocalRef<jstring> jPackage ((jstring) env->GetObjectField (activityInfo.get(), AndroidPackageItemInfo.packageName));
mainActivityClassPath = juceString (jName);
}
}
}
return mainActivityClassPath;
}
CriticalSection currentActivityLock;
jweak currentActivity = nullptr;
jweak mainActivity = nullptr;
ActivityLifecycleCallbackForwarder forwarder { GlobalRef { getAppContext() }, this };
};
//==============================================================================
#if JUCE_MODULE_AVAILABLE_juce_events && JUCE_ANDROID
void juce_juceEventsAndroidStartApp();
#endif
void Thread::initialiseJUCE (void* jniEnv, void* context)
{
static CriticalSection cs;
ScopedLock lock (cs);
// jniEnv and context should not be null!
jassert (jniEnv != nullptr && context != nullptr);
auto* env = static_cast<JNIEnv*> (jniEnv);
if (androidJNIJavaVM == nullptr)
{
JavaVM* javaVM = nullptr;
auto status = env->GetJavaVM (&javaVM);
jassert (status == 0 && javaVM != nullptr);
androidJNIJavaVM = javaVM;
}
static bool firstCall = true;
if (firstCall)
{
firstCall = false;
// if we ever support unloading then this should probably be a weak reference
androidApkContext = env->NewGlobalRef (static_cast<jobject> (context));
JuceActivityWatcher::getInstance();
#if JUCE_MODULE_AVAILABLE_juce_events && JUCE_ANDROID
juce_juceEventsAndroidStartApp();
#endif
}
}
//==============================================================================
LocalRef<jobject> getAppContext() noexcept
{
auto* env = getEnv();
auto context = androidApkContext;
// You did not call Thread::initialiseJUCE which must be called at least once in your apk
// before using any JUCE APIs. The Projucer will automatically generate java code
// which will invoke Thread::initialiseJUCE for you.
jassert (env != nullptr && context != nullptr);
if (context == nullptr)
return LocalRef<jobject>();
if (env->IsInstanceOf (context, AndroidApplication) != 0)
return LocalRef<jobject> (env->NewLocalRef (context));
LocalRef<jobject> applicationContext (env->CallObjectMethod (context, AndroidContext.getApplicationContext));
if (applicationContext == nullptr)
return LocalRef<jobject> (env->NewLocalRef (context));
return applicationContext;
}
LocalRef<jobject> getCurrentActivity() noexcept
{
return JuceActivityWatcher::getInstance().getCurrent();
}
LocalRef<jobject> getMainActivity() noexcept
{
return JuceActivityWatcher::getInstance().getMain();
}
//==============================================================================
using RealtimeThreadFactory = pthread_t (*) (void* (*entry) (void*), void* userPtr);
// This is defined in the juce_audio_devices module, with different definitions depending on
// whether OpenSL/Oboe are enabled.
RealtimeThreadFactory getAndroidRealtimeThreadFactory();
#if ! JUCE_MODULE_AVAILABLE_juce_audio_devices
RealtimeThreadFactory getAndroidRealtimeThreadFactory() { return nullptr; }
#endif
extern JavaVM* androidJNIJavaVM;
static auto setPriorityOfThisThread (Thread::Priority p)
{
return setpriority (PRIO_PROCESS,
(id_t) gettid(),
ThreadPriorities::getNativePriority (p)) == 0;
}
bool Thread::createNativeThread (Priority)
{
const auto threadEntryProc = [] (void* userData) -> void*
{
auto* myself = static_cast<Thread*> (userData);
setPriorityOfThisThread (myself->priority);
juce_threadEntryPoint (myself);
if (androidJNIJavaVM != nullptr)
{
void* env = nullptr;
androidJNIJavaVM->GetEnv (&env, JNI_VERSION_1_2);
// only detach if we have actually been attached
if (env != nullptr)
androidJNIJavaVM->DetachCurrentThread();
}
return nullptr;
};
if (isRealtime())
{
if (const auto factory = getAndroidRealtimeThreadFactory())
{
threadHandle = (void*) factory (threadEntryProc, this);
threadId = (ThreadID) threadHandle.load();
return threadId != nullptr;
}
else
{
jassertfalse;
}
}
PosixThreadAttribute attr { threadStackSize };
threadId = threadHandle = makeThreadHandle (attr, this, threadEntryProc);
return threadId != nullptr;
}
void Thread::killThread()
{
if (threadHandle != nullptr)
jassertfalse; // pthread_cancel not available!
}
Thread::Priority Thread::getPriority() const
{
jassert (Thread::getCurrentThreadId() == getThreadId());
const auto native = getpriority (PRIO_PROCESS, (id_t) gettid());
return ThreadPriorities::getJucePriority (native);
}
bool Thread::setPriority (Priority priorityIn)
{
jassert (Thread::getCurrentThreadId() == getThreadId());
if (isRealtime())
return false;
const auto priorityToUse = priority = priorityIn;
return setPriorityOfThisThread (priorityToUse) == 0;
}
//==============================================================================
JUCE_API void JUCE_CALLTYPE Process::setPriority (ProcessPriority) {}
JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger() noexcept
{
StringArray lines;
File ("/proc/self/status").readLines (lines);
for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
if (lines[i].upToFirstOccurrenceOf (":", false, false).trim().equalsIgnoreCase ("TracerPid"))
return (lines[i].fromFirstOccurrenceOf (":", false, false).trim().getIntValue() > 0);
return false;
}
JUCE_API void JUCE_CALLTYPE Process::raisePrivilege() {}
JUCE_API void JUCE_CALLTYPE Process::lowerPrivilege() {}
} // namespace juce
|