Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

893 lines
38KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. //==============================================================================
  16. // This byte-code is generated from native/java/app/com/roli/juce/JuceContentProviderCursor.java with min sdk version 16
  17. // See juce_core/native/java/README.txt on how to generate this byte-code.
  18. static const uint8 javaJuceContentProviderCursor[] =
  19. { 31,139,8,8,138,122,94,94,0,3,74,117,99,101,67,111,110,116,101,110,116,80,114,111,118,105,100,101,114,67,117,114,115,111,114,
  20. 46,100,101,120,0,117,147,177,111,211,64,20,198,223,157,157,148,150,52,184,144,1,6,32,160,46,29,138,43,209,178,132,34,80,144,42,
  21. 89,6,85,10,164,82,59,93,109,211,184,77,124,145,237,68,17,98,0,4,91,6,6,38,38,64,133,153,255,0,33,133,255,131,137,149,133,177,3,
  22. 223,229,206,37,18,194,210,207,247,222,229,189,239,157,206,95,194,104,180,176,118,115,131,142,7,95,175,127,216,250,229,236,28,
  23. 61,169,85,222,124,219,126,234,140,155,159,157,142,184,107,17,245,137,104,212,94,63,79,230,121,207,137,28,210,251,37,240,5,216,
  24. 96,2,24,248,109,246,79,76,190,140,215,9,184,15,222,129,143,224,19,248,14,126,130,37,232,213,192,69,112,25,92,3,183,192,38,240,
  25. 64,4,142,192,144,107,61,203,204,83,51,230,205,106,153,179,149,77,252,10,133,115,38,30,35,62,99,226,183,136,33,67,139,211,179,
  26. 233,46,165,185,64,106,159,79,115,126,154,51,170,152,124,201,212,21,191,171,103,108,130,18,78,163,194,103,92,207,239,215,137,238,
  27. 209,46,238,171,138,9,122,202,107,174,207,42,29,134,218,22,42,250,107,232,98,213,127,116,237,105,110,83,249,118,156,196,249,29,
  28. 98,30,93,241,6,65,212,148,73,30,37,249,118,42,135,113,24,165,205,65,154,201,244,198,161,24,10,186,234,139,36,76,101,28,186,161,
  29. 200,197,190,200,34,247,129,200,211,120,164,139,26,180,226,7,178,231,166,178,27,187,135,144,114,255,171,215,32,214,38,222,246,
  30. 200,106,123,62,2,159,46,236,249,106,134,219,21,201,129,219,130,104,114,208,160,82,208,149,89,68,103,3,217,29,244,146,135,162,
  31. 23,101,116,41,208,130,173,142,72,11,185,166,42,11,201,238,200,44,167,121,245,126,36,31,163,209,206,59,113,70,21,126,174,50,87,
  32. 221,92,165,26,97,217,197,69,112,92,14,127,241,220,158,112,254,146,147,197,126,240,69,115,55,108,102,45,188,199,103,252,87,120,
  33. 98,98,214,89,31,22,94,44,207,248,145,213,117,191,242,36,115,254,122,134,215,181,190,242,169,101,106,212,119,165,186,238,157,126,
  34. 115,71,199,234,127,240,7,124,122,243,207,64,3,0,0,0,0 };
  35. // This byte-code is generated from native/java/app/com/roli/juce/JuceContentProviderFileObserver.java with min sdk version 16
  36. // See juce_core/native/java/README.txt on how to generate this byte-code.
  37. static const uint8 javaJuceContentProviderFileObserver[] =
  38. { 31,139,8,8,123,122,94,94,0,3,74,117,99,101,67,111,110,116,101,110,116,80,114,111,118,105,100,101,114,70,105,108,101,79,98,115,
  39. 101,114,118,101,114,46,100,101,120,0,133,147,205,107,19,65,24,198,223,249,72,98,91,93,210,84,4,17,36,130,130,32,186,145,218,
  40. 131,196,10,197,47,18,22,44,166,6,41,120,216,38,75,119,107,186,19,118,215,144,131,5,45,61,148,158,188,244,164,71,65,241,212,163,
  41. 40,138,136,224,213,91,253,3,60,250,7,120,211,103,118,166,116,61,25,248,205,251,206,251,206,60,59,59,251,164,31,140,39,27,179,
  42. 115,116,110,243,212,238,147,208,189,112,245,227,236,183,157,19,103,216,220,215,223,91,251,175,247,249,88,16,13,137,104,220,189,
  43. 82,35,251,251,193,137,142,147,169,151,193,103,32,117,29,48,112,132,153,121,149,153,121,3,195,121,236,89,68,220,3,239,192,7,
  44. 240,9,252,4,127,64,3,253,155,224,14,240,192,61,240,0,60,4,27,96,11,236,128,93,240,2,188,2,111,185,209,231,246,249,37,123,158,138,
  45. 62,131,157,111,99,193,132,205,159,35,159,180,249,75,228,83,54,127,131,92,64,201,201,181,68,254,142,34,87,53,245,163,121,36,
  46. 154,46,68,110,239,66,216,248,197,22,202,80,212,181,61,110,206,50,108,16,45,148,150,113,119,78,222,209,207,123,111,123,157,58,
  47. 250,75,156,248,101,199,234,201,124,47,179,239,99,114,153,119,14,222,177,124,45,138,163,236,58,177,22,177,54,157,109,63,238,5,
  48. 55,84,156,5,113,182,152,168,81,212,15,146,219,209,32,184,187,146,6,201,40,72,46,173,249,35,159,78,122,126,220,79,84,212,119,85,
  49. 234,22,219,77,114,189,158,90,119,19,53,136,220,53,72,185,255,209,107,82,205,211,146,238,192,143,87,221,78,150,68,241,106,147,
  50. 88,151,68,183,229,145,236,182,205,232,181,80,192,112,186,103,164,58,161,159,252,43,116,107,132,50,149,130,60,200,80,165,25,77,
  51. 232,113,73,221,79,3,146,235,126,250,136,42,42,54,203,228,208,207,66,146,89,24,165,52,37,170,51,211,21,103,254,34,213,184,51,
  52. 83,113,150,113,69,156,17,103,207,158,202,239,156,109,226,251,177,95,184,172,99,246,187,176,66,60,240,44,47,248,86,20,188,43,11,
  53. 254,45,209,161,135,203,116,232,99,86,55,251,181,151,89,213,172,209,30,227,117,163,175,253,45,236,26,237,1,170,155,189,185,63,
  54. 170,38,215,255,159,191,29,121,169,41,120,3,0,0,0,0 };
  55. //==============================================================================
  56. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  57. FIELD (authority, "authority", "Ljava/lang/String;")
  58. DECLARE_JNI_CLASS (AndroidProviderInfo, "android/content/pm/ProviderInfo")
  59. #undef JNI_CLASS_MEMBERS
  60. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  61. METHOD (constructor, "<init>", "(Landroid/os/ParcelFileDescriptor;JJ)V") \
  62. METHOD (createInputStream, "createInputStream", "()Ljava/io/FileInputStream;") \
  63. METHOD (getLength, "getLength", "()J")
  64. DECLARE_JNI_CLASS (AssetFileDescriptor, "android/content/res/AssetFileDescriptor")
  65. #undef JNI_CLASS_MEMBERS
  66. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  67. METHOD (close, "close", "()V")
  68. DECLARE_JNI_CLASS (JavaCloseable, "java/io/Closeable")
  69. #undef JNI_CLASS_MEMBERS
  70. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  71. STATICMETHOD (open, "open", "(Ljava/io/File;I)Landroid/os/ParcelFileDescriptor;")
  72. DECLARE_JNI_CLASS (ParcelFileDescriptor, "android/os/ParcelFileDescriptor")
  73. #undef JNI_CLASS_MEMBERS
  74. //==============================================================================
  75. class AndroidContentSharerCursor
  76. {
  77. public:
  78. class Owner
  79. {
  80. public:
  81. virtual ~Owner() {}
  82. virtual void cursorClosed (const AndroidContentSharerCursor&) = 0;
  83. };
  84. AndroidContentSharerCursor (Owner& ownerToUse, JNIEnv* env,
  85. const LocalRef<jobject>& contentProvider,
  86. const LocalRef<jobjectArray>& resultColumns)
  87. : owner (ownerToUse),
  88. cursor (GlobalRef (LocalRef<jobject> (env->NewObject (JuceContentProviderCursor,
  89. JuceContentProviderCursor.constructor,
  90. reinterpret_cast<jlong> (this),
  91. resultColumns.get()))))
  92. {
  93. // the content provider must be created first
  94. jassert (contentProvider.get() != nullptr);
  95. }
  96. jobject getNativeCursor() { return cursor.get(); }
  97. void cursorClosed()
  98. {
  99. MessageManager::callAsync ([this] { owner.cursorClosed (*this); });
  100. }
  101. void addRow (LocalRef<jobjectArray>& values)
  102. {
  103. auto* env = getEnv();
  104. env->CallVoidMethod (cursor.get(), JuceContentProviderCursor.addRow, values.get());
  105. }
  106. private:
  107. Owner& owner;
  108. GlobalRef cursor;
  109. //==============================================================================
  110. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  111. METHOD (addRow, "addRow", "([Ljava/lang/Object;)V") \
  112. METHOD (constructor, "<init>", "(J[Ljava/lang/String;)V") \
  113. CALLBACK (contentSharerCursorClosed, "contentSharerCursorClosed", "(J)V") \
  114. DECLARE_JNI_CLASS_WITH_BYTECODE (JuceContentProviderCursor, "com/roli/juce/JuceContentProviderCursor", 16, javaJuceContentProviderCursor, sizeof (javaJuceContentProviderCursor))
  115. #undef JNI_CLASS_MEMBERS
  116. static void JNICALL contentSharerCursorClosed (JNIEnv*, jobject, jlong host)
  117. {
  118. if (auto* myself = reinterpret_cast<AndroidContentSharerCursor*> (host))
  119. myself->cursorClosed();
  120. }
  121. };
  122. AndroidContentSharerCursor::JuceContentProviderCursor_Class AndroidContentSharerCursor::JuceContentProviderCursor;
  123. //==============================================================================
  124. class AndroidContentSharerFileObserver
  125. {
  126. public:
  127. class Owner
  128. {
  129. public:
  130. virtual ~Owner() {}
  131. virtual void fileHandleClosed (const AndroidContentSharerFileObserver&) = 0;
  132. };
  133. AndroidContentSharerFileObserver (Owner& ownerToUse, JNIEnv* env,
  134. const LocalRef<jobject>& contentProvider,
  135. const String& filepathToUse)
  136. : owner (ownerToUse),
  137. filepath (filepathToUse),
  138. fileObserver (GlobalRef (LocalRef<jobject> (env->NewObject (JuceContentProviderFileObserver,
  139. JuceContentProviderFileObserver.constructor,
  140. reinterpret_cast<jlong> (this),
  141. javaString (filepath).get(),
  142. open | access | closeWrite | closeNoWrite))))
  143. {
  144. // the content provider must be created first
  145. jassert (contentProvider.get() != nullptr);
  146. env->CallVoidMethod (fileObserver, JuceContentProviderFileObserver.startWatching);
  147. }
  148. void onFileEvent (int event, const LocalRef<jstring>& path)
  149. {
  150. ignoreUnused (path);
  151. if (event == open)
  152. {
  153. ++numOpenedHandles;
  154. }
  155. else if (event == access)
  156. {
  157. fileWasRead = true;
  158. }
  159. else if (event == closeNoWrite || event == closeWrite)
  160. {
  161. --numOpenedHandles;
  162. // numOpenedHandles may get negative if we don't receive open handle event.
  163. if (fileWasRead && numOpenedHandles <= 0)
  164. {
  165. MessageManager::callAsync ([this]
  166. {
  167. getEnv()->CallVoidMethod (fileObserver, JuceContentProviderFileObserver.stopWatching);
  168. owner.fileHandleClosed (*this);
  169. });
  170. }
  171. }
  172. }
  173. private:
  174. static constexpr int open = 32;
  175. static constexpr int access = 1;
  176. static constexpr int closeWrite = 8;
  177. static constexpr int closeNoWrite = 16;
  178. bool fileWasRead = false;
  179. int numOpenedHandles = 0;
  180. Owner& owner;
  181. String filepath;
  182. GlobalRef fileObserver;
  183. //==============================================================================
  184. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  185. METHOD (constructor, "<init>", "(JLjava/lang/String;I)V") \
  186. METHOD (startWatching, "startWatching", "()V") \
  187. METHOD (stopWatching, "stopWatching", "()V") \
  188. CALLBACK (contentSharerFileObserverEvent, "contentSharerFileObserverEvent", "(JILjava/lang/String;)V") \
  189. DECLARE_JNI_CLASS_WITH_BYTECODE (JuceContentProviderFileObserver, "com/roli/juce/JuceContentProviderFileObserver", 16, javaJuceContentProviderFileObserver, sizeof (javaJuceContentProviderFileObserver))
  190. #undef JNI_CLASS_MEMBERS
  191. static void JNICALL contentSharerFileObserverEvent (JNIEnv*, jobject /*fileObserver*/, jlong host, int event, jstring path)
  192. {
  193. if (auto* myself = reinterpret_cast<AndroidContentSharerFileObserver*> (host))
  194. myself->onFileEvent (event, LocalRef<jstring> (path));
  195. }
  196. };
  197. AndroidContentSharerFileObserver::JuceContentProviderFileObserver_Class AndroidContentSharerFileObserver::JuceContentProviderFileObserver;
  198. //==============================================================================
  199. class AndroidContentSharerPrepareFilesThread : private Thread
  200. {
  201. public:
  202. AndroidContentSharerPrepareFilesThread (AsyncUpdater& ownerToUse,
  203. const Array<URL>& fileUrlsToUse,
  204. const String& packageNameToUse,
  205. const String& uriBaseToUse)
  206. : Thread ("AndroidContentSharerPrepareFilesThread"),
  207. owner (ownerToUse),
  208. fileUrls (fileUrlsToUse),
  209. resultFileUris (GlobalRef (LocalRef<jobject> (getEnv()->NewObject (JavaArrayList,
  210. JavaArrayList.constructor,
  211. fileUrls.size())))),
  212. packageName (packageNameToUse),
  213. uriBase (uriBaseToUse)
  214. {
  215. startThread();
  216. }
  217. ~AndroidContentSharerPrepareFilesThread() override
  218. {
  219. signalThreadShouldExit();
  220. waitForThreadToExit (10000);
  221. for (auto& f : temporaryFilesFromAssetFiles)
  222. f.deleteFile();
  223. }
  224. jobject getResultFileUris() { return resultFileUris.get(); }
  225. const StringArray& getMimeTypes() const { return mimeTypes; }
  226. const StringArray& getFilePaths() const { return filePaths; }
  227. private:
  228. struct StreamCloser
  229. {
  230. StreamCloser (const LocalRef<jobject>& streamToUse)
  231. : stream (GlobalRef (streamToUse))
  232. {
  233. }
  234. ~StreamCloser()
  235. {
  236. if (stream.get() != nullptr)
  237. getEnv()->CallVoidMethod (stream, JavaCloseable.close);
  238. }
  239. GlobalRef stream;
  240. };
  241. void run() override
  242. {
  243. auto* env = getEnv();
  244. bool canSpecifyMimeTypes = true;
  245. for (auto f : fileUrls)
  246. {
  247. auto scheme = f.getScheme();
  248. // Only "file://" scheme or no scheme (for files in app bundle) are allowed!
  249. jassert (scheme.isEmpty() || scheme == "file");
  250. if (scheme.isEmpty())
  251. {
  252. // Raw resource names need to be all lower case
  253. jassert (f.toString (true).toLowerCase() == f.toString (true));
  254. // This will get us a file with file:// URI
  255. f = copyAssetFileToTemporaryFile (env, f.toString (true));
  256. if (f.isEmpty())
  257. continue;
  258. }
  259. if (threadShouldExit())
  260. return;
  261. auto filepath = URL::removeEscapeChars (f.toString (true).fromFirstOccurrenceOf ("file://", false, false));
  262. filePaths.add (filepath);
  263. auto filename = filepath.fromLastOccurrenceOf ("/", false, true);
  264. auto fileExtension = filename.fromLastOccurrenceOf (".", false, true);
  265. auto contentString = uriBase + String (filePaths.size() - 1) + "/" + filename;
  266. auto uri = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidUri, AndroidUri.parse,
  267. javaString (contentString).get()));
  268. if (canSpecifyMimeTypes)
  269. canSpecifyMimeTypes = fileExtension.isNotEmpty();
  270. if (canSpecifyMimeTypes)
  271. mimeTypes.addArray (getMimeTypesForFileExtension (fileExtension));
  272. else
  273. mimeTypes.clear();
  274. env->CallBooleanMethod (resultFileUris, JavaArrayList.add, uri.get());
  275. }
  276. owner.triggerAsyncUpdate();
  277. }
  278. URL copyAssetFileToTemporaryFile (JNIEnv* env, const String& filename)
  279. {
  280. auto resources = LocalRef<jobject> (env->CallObjectMethod (getAppContext().get(), AndroidContext.getResources));
  281. int fileId = env->CallIntMethod (resources, AndroidResources.getIdentifier, javaString (filename).get(),
  282. javaString ("raw").get(), javaString (packageName).get());
  283. // Raw resource not found. Please make sure that you include your file as a raw resource
  284. // and that you specify just the file name, without an extension.
  285. jassert (fileId != 0);
  286. if (fileId == 0)
  287. return {};
  288. auto assetFd = LocalRef<jobject> (env->CallObjectMethod (resources,
  289. AndroidResources.openRawResourceFd,
  290. fileId));
  291. auto inputStream = StreamCloser (LocalRef<jobject> (env->CallObjectMethod (assetFd,
  292. AssetFileDescriptor.createInputStream)));
  293. if (jniCheckHasExceptionOccurredAndClear())
  294. {
  295. // Failed to open file stream for resource
  296. jassertfalse;
  297. return {};
  298. }
  299. auto tempFile = File::createTempFile ({});
  300. tempFile.createDirectory();
  301. tempFile = tempFile.getChildFile (filename);
  302. auto outputStream = StreamCloser (LocalRef<jobject> (env->NewObject (JavaFileOutputStream,
  303. JavaFileOutputStream.constructor,
  304. javaString (tempFile.getFullPathName()).get())));
  305. if (jniCheckHasExceptionOccurredAndClear())
  306. {
  307. // Failed to open file stream for temporary file
  308. jassertfalse;
  309. return {};
  310. }
  311. auto buffer = LocalRef<jbyteArray> (env->NewByteArray (1024));
  312. int bytesRead = 0;
  313. for (;;)
  314. {
  315. if (threadShouldExit())
  316. return {};
  317. bytesRead = env->CallIntMethod (inputStream.stream, JavaFileInputStream.read, buffer.get());
  318. if (jniCheckHasExceptionOccurredAndClear())
  319. {
  320. // Failed to read from resource file.
  321. jassertfalse;
  322. return {};
  323. }
  324. if (bytesRead < 0)
  325. break;
  326. env->CallVoidMethod (outputStream.stream, JavaFileOutputStream.write, buffer.get(), 0, bytesRead);
  327. if (jniCheckHasExceptionOccurredAndClear())
  328. {
  329. // Failed to write to temporary file.
  330. jassertfalse;
  331. return {};
  332. }
  333. }
  334. temporaryFilesFromAssetFiles.add (tempFile);
  335. return URL (tempFile);
  336. }
  337. AsyncUpdater& owner;
  338. Array<URL> fileUrls;
  339. GlobalRef resultFileUris;
  340. String packageName;
  341. String uriBase;
  342. StringArray filePaths;
  343. Array<File> temporaryFilesFromAssetFiles;
  344. StringArray mimeTypes;
  345. };
  346. //==============================================================================
  347. class ContentSharer::ContentSharerNativeImpl : public ContentSharer::Pimpl,
  348. public AndroidContentSharerFileObserver::Owner,
  349. public AndroidContentSharerCursor::Owner,
  350. public AsyncUpdater,
  351. private Timer
  352. {
  353. public:
  354. ContentSharerNativeImpl (ContentSharer& cs)
  355. : owner (cs),
  356. packageName (juceString (LocalRef<jstring> ((jstring) getEnv()->CallObjectMethod (getAppContext().get(), AndroidContext.getPackageName)))),
  357. uriBase ("content://" + packageName + ".sharingcontentprovider/")
  358. {
  359. }
  360. ~ContentSharerNativeImpl() override
  361. {
  362. masterReference.clear();
  363. }
  364. void shareFiles (const Array<URL>& files) override
  365. {
  366. if (! isContentSharingEnabled())
  367. {
  368. // You need to enable "Content Sharing" in Projucer's Android exporter.
  369. jassertfalse;
  370. owner.sharingFinished (false, {});
  371. }
  372. prepareFilesThread.reset (new AndroidContentSharerPrepareFilesThread (*this, files, packageName, uriBase));
  373. }
  374. void shareText (const String& text) override
  375. {
  376. if (! isContentSharingEnabled())
  377. {
  378. // You need to enable "Content Sharing" in Projucer's Android exporter.
  379. jassertfalse;
  380. owner.sharingFinished (false, {});
  381. }
  382. auto* env = getEnv();
  383. auto intent = LocalRef<jobject> (env->NewObject (AndroidIntent, AndroidIntent.constructor));
  384. env->CallObjectMethod (intent, AndroidIntent.setAction,
  385. javaString ("android.intent.action.SEND").get());
  386. env->CallObjectMethod (intent, AndroidIntent.putExtra,
  387. javaString ("android.intent.extra.TEXT").get(),
  388. javaString (text).get());
  389. env->CallObjectMethod (intent, AndroidIntent.setType, javaString ("text/plain").get());
  390. auto chooserIntent = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidIntent, AndroidIntent.createChooser,
  391. intent.get(), javaString ("Choose share target").get()));
  392. WeakReference<ContentSharerNativeImpl> weakRef (this);
  393. startAndroidActivityForResult (chooserIntent, 1003,
  394. [weakRef] (int /*requestCode*/, int resultCode, LocalRef<jobject> /*intentData*/) mutable
  395. {
  396. if (weakRef != nullptr)
  397. weakRef->sharingFinished (resultCode);
  398. });
  399. }
  400. //==============================================================================
  401. void cursorClosed (const AndroidContentSharerCursor& cursor) override
  402. {
  403. cursors.removeObject (&cursor);
  404. }
  405. void fileHandleClosed (const AndroidContentSharerFileObserver&) override
  406. {
  407. decrementPendingFileCountAndNotifyOwnerIfReady();
  408. }
  409. //==============================================================================
  410. jobject openFile (const LocalRef<jobject>& contentProvider,
  411. const LocalRef<jobject>& uri, const LocalRef<jstring>& mode)
  412. {
  413. ignoreUnused (mode);
  414. WeakReference<ContentSharerNativeImpl> weakRef (this);
  415. if (weakRef == nullptr)
  416. return nullptr;
  417. auto* env = getEnv();
  418. auto uriElements = getContentUriElements (env, uri);
  419. if (uriElements.filepath.isEmpty())
  420. return nullptr;
  421. return getAssetFileDescriptor (env, contentProvider, uriElements.filepath);
  422. }
  423. jobject query (const LocalRef<jobject>& contentProvider, const LocalRef<jobject>& uri,
  424. const LocalRef<jobjectArray>& projection)
  425. {
  426. StringArray requestedColumns = javaStringArrayToJuce (projection);
  427. StringArray supportedColumns = getSupportedColumns();
  428. StringArray resultColumns;
  429. for (const auto& col : supportedColumns)
  430. {
  431. if (requestedColumns.contains (col))
  432. resultColumns.add (col);
  433. }
  434. // Unsupported columns were queried, file sharing may fail.
  435. if (resultColumns.isEmpty())
  436. return nullptr;
  437. auto resultJavaColumns = juceStringArrayToJava (resultColumns);
  438. auto* env = getEnv();
  439. auto cursor = cursors.add (new AndroidContentSharerCursor (*this, env, contentProvider,
  440. resultJavaColumns));
  441. auto uriElements = getContentUriElements (env, uri);
  442. if (uriElements.filepath.isEmpty())
  443. return cursor->getNativeCursor();
  444. auto values = LocalRef<jobjectArray> (env->NewObjectArray ((jsize) resultColumns.size(),
  445. JavaObject, nullptr));
  446. for (int i = 0; i < resultColumns.size(); ++i)
  447. {
  448. if (resultColumns.getReference (i) == "_display_name")
  449. {
  450. env->SetObjectArrayElement (values, i, javaString (uriElements.filename).get());
  451. }
  452. else if (resultColumns.getReference (i) == "_size")
  453. {
  454. auto javaFile = LocalRef<jobject> (env->NewObject (JavaFile, JavaFile.constructor,
  455. javaString (uriElements.filepath).get()));
  456. jlong fileLength = env->CallLongMethod (javaFile, JavaFile.length);
  457. env->SetObjectArrayElement (values, i, env->NewObject (JavaLong,
  458. JavaLong.constructor,
  459. fileLength));
  460. }
  461. }
  462. cursor->addRow (values);
  463. return cursor->getNativeCursor();
  464. }
  465. jobjectArray getStreamTypes (const LocalRef<jobject>& uri, const LocalRef<jstring>& mimeTypeFilter)
  466. {
  467. auto* env = getEnv();
  468. auto extension = getContentUriElements (env, uri).filename.fromLastOccurrenceOf (".", false, true);
  469. if (extension.isEmpty())
  470. return nullptr;
  471. return juceStringArrayToJava (filterMimeTypes (getMimeTypesForFileExtension (extension),
  472. juceString (mimeTypeFilter.get())));
  473. }
  474. void sharingFinished (int resultCode)
  475. {
  476. sharingActivityDidFinish = true;
  477. succeeded = resultCode == -1;
  478. // Give content sharer a chance to request file access.
  479. if (nonAssetFilesPendingShare.get() == 0)
  480. startTimer (2000);
  481. else
  482. notifyOwnerIfReady();
  483. }
  484. private:
  485. bool isContentSharingEnabled() const
  486. {
  487. auto* env = getEnv();
  488. LocalRef<jobject> packageManager (env->CallObjectMethod (getAppContext().get(), AndroidContext.getPackageManager));
  489. constexpr int getProviders = 8;
  490. auto packageInfo = LocalRef<jobject> (env->CallObjectMethod (packageManager,
  491. AndroidPackageManager.getPackageInfo,
  492. javaString (packageName).get(),
  493. getProviders));
  494. auto providers = LocalRef<jobjectArray> ((jobjectArray) env->GetObjectField (packageInfo,
  495. AndroidPackageInfo.providers));
  496. if (providers == nullptr)
  497. return false;
  498. auto sharingContentProviderAuthority = packageName + ".sharingcontentprovider";
  499. const int numProviders = env->GetArrayLength (providers.get());
  500. for (int i = 0; i < numProviders; ++i)
  501. {
  502. auto providerInfo = LocalRef<jobject> (env->GetObjectArrayElement (providers, i));
  503. auto authority = LocalRef<jstring> ((jstring) env->GetObjectField (providerInfo,
  504. AndroidProviderInfo.authority));
  505. if (juceString (authority) == sharingContentProviderAuthority)
  506. return true;
  507. }
  508. return false;
  509. }
  510. void handleAsyncUpdate() override
  511. {
  512. jassert (prepareFilesThread != nullptr);
  513. if (prepareFilesThread == nullptr)
  514. return;
  515. filesPrepared (prepareFilesThread->getResultFileUris(), prepareFilesThread->getMimeTypes());
  516. }
  517. void filesPrepared (jobject fileUris, const StringArray& mimeTypes)
  518. {
  519. auto* env = getEnv();
  520. auto intent = LocalRef<jobject> (env->NewObject (AndroidIntent, AndroidIntent.constructor));
  521. env->CallObjectMethod (intent, AndroidIntent.setAction,
  522. javaString ("android.intent.action.SEND_MULTIPLE").get());
  523. env->CallObjectMethod (intent, AndroidIntent.setType,
  524. javaString (getCommonMimeType (mimeTypes)).get());
  525. constexpr int grantReadPermission = 1;
  526. env->CallObjectMethod (intent, AndroidIntent.setFlags, grantReadPermission);
  527. env->CallObjectMethod (intent, AndroidIntent.putParcelableArrayListExtra,
  528. javaString ("android.intent.extra.STREAM").get(),
  529. fileUris);
  530. auto chooserIntent = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidIntent,
  531. AndroidIntent.createChooser,
  532. intent.get(),
  533. javaString ("Choose share target").get()));
  534. WeakReference<ContentSharerNativeImpl> weakRef (this);
  535. startAndroidActivityForResult (chooserIntent, 1003,
  536. [weakRef] (int /*requestCode*/, int resultCode, LocalRef<jobject> /*intentData*/) mutable
  537. {
  538. if (weakRef != nullptr)
  539. weakRef->sharingFinished (resultCode);
  540. });
  541. }
  542. void decrementPendingFileCountAndNotifyOwnerIfReady()
  543. {
  544. --nonAssetFilesPendingShare;
  545. notifyOwnerIfReady();
  546. }
  547. void notifyOwnerIfReady()
  548. {
  549. if (sharingActivityDidFinish && nonAssetFilesPendingShare.get() == 0)
  550. owner.sharingFinished (succeeded, {});
  551. }
  552. void timerCallback() override
  553. {
  554. stopTimer();
  555. notifyOwnerIfReady();
  556. }
  557. //==============================================================================
  558. struct ContentUriElements
  559. {
  560. String index;
  561. String filename;
  562. String filepath;
  563. };
  564. ContentUriElements getContentUriElements (JNIEnv* env, const LocalRef<jobject>& uri) const
  565. {
  566. jassert (prepareFilesThread != nullptr);
  567. if (prepareFilesThread == nullptr)
  568. return {};
  569. auto fullUri = juceString ((jstring) env->CallObjectMethod (uri.get(), AndroidUri.toString));
  570. auto index = fullUri.fromFirstOccurrenceOf (uriBase, false, false)
  571. .upToFirstOccurrenceOf ("/", false, true);
  572. auto filename = fullUri.fromLastOccurrenceOf ("/", false, true);
  573. return { index, filename, prepareFilesThread->getFilePaths()[index.getIntValue()] };
  574. }
  575. static StringArray getSupportedColumns()
  576. {
  577. return StringArray ("_display_name", "_size");
  578. }
  579. jobject getAssetFileDescriptor (JNIEnv* env, const LocalRef<jobject>& contentProvider,
  580. const String& filepath)
  581. {
  582. // This function can be called from multiple threads.
  583. {
  584. const ScopedLock sl (nonAssetFileOpenLock);
  585. if (! nonAssetFilePathsPendingShare.contains (filepath))
  586. {
  587. nonAssetFilePathsPendingShare.add (filepath);
  588. ++nonAssetFilesPendingShare;
  589. nonAssetFileObservers.add (new AndroidContentSharerFileObserver (*this, env,
  590. contentProvider,
  591. filepath));
  592. }
  593. }
  594. auto javaFile = LocalRef<jobject> (env->NewObject (JavaFile, JavaFile.constructor,
  595. javaString (filepath).get()));
  596. constexpr int modeReadOnly = 268435456;
  597. auto parcelFileDescriptor = LocalRef<jobject> (env->CallStaticObjectMethod (ParcelFileDescriptor,
  598. ParcelFileDescriptor.open,
  599. javaFile.get(), modeReadOnly));
  600. if (jniCheckHasExceptionOccurredAndClear())
  601. {
  602. // Failed to create file descriptor. Have you provided a valid file path/resource name?
  603. jassertfalse;
  604. return nullptr;
  605. }
  606. jlong startOffset = 0;
  607. jlong unknownLength = -1;
  608. assetFileDescriptors.add (GlobalRef (LocalRef<jobject> (env->NewObject (AssetFileDescriptor,
  609. AssetFileDescriptor.constructor,
  610. parcelFileDescriptor.get(),
  611. startOffset, unknownLength))));
  612. return assetFileDescriptors.getReference (assetFileDescriptors.size() - 1).get();
  613. }
  614. StringArray filterMimeTypes (const StringArray& mimeTypes, const String& filter)
  615. {
  616. String filterToUse (filter.removeCharacters ("*"));
  617. if (filterToUse.isEmpty() || filterToUse == "/")
  618. return mimeTypes;
  619. StringArray result;
  620. for (const auto& type : mimeTypes)
  621. if (String (type).contains (filterToUse))
  622. result.add (type);
  623. return result;
  624. }
  625. String getCommonMimeType (const StringArray& mimeTypes)
  626. {
  627. if (mimeTypes.isEmpty())
  628. return "*/*";
  629. auto commonMime = mimeTypes[0];
  630. bool lookForCommonGroup = false;
  631. for (int i = 1; i < mimeTypes.size(); ++i)
  632. {
  633. if (mimeTypes[i] == commonMime)
  634. continue;
  635. if (! lookForCommonGroup)
  636. {
  637. lookForCommonGroup = true;
  638. commonMime = commonMime.upToFirstOccurrenceOf ("/", true, false);
  639. }
  640. if (! mimeTypes[i].startsWith (commonMime))
  641. return "*/*";
  642. }
  643. return lookForCommonGroup ? commonMime + "*" : commonMime;
  644. }
  645. ContentSharer& owner;
  646. String packageName;
  647. String uriBase;
  648. std::unique_ptr<AndroidContentSharerPrepareFilesThread> prepareFilesThread;
  649. bool succeeded = false;
  650. String errorDescription;
  651. bool sharingActivityDidFinish = false;
  652. OwnedArray<AndroidContentSharerCursor> cursors;
  653. Array<GlobalRef> assetFileDescriptors;
  654. CriticalSection nonAssetFileOpenLock;
  655. StringArray nonAssetFilePathsPendingShare;
  656. Atomic<int> nonAssetFilesPendingShare { 0 };
  657. OwnedArray<AndroidContentSharerFileObserver> nonAssetFileObservers;
  658. WeakReference<ContentSharerNativeImpl>::Master masterReference;
  659. friend class WeakReference<ContentSharerNativeImpl>;
  660. //==============================================================================
  661. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  662. CALLBACK (contentSharerQuery, "contentSharerQuery", "(Landroid/net/Uri;[Ljava/lang/String;)Landroid/database/Cursor;") \
  663. CALLBACK (contentSharerOpenFile, "contentSharerOpenFile", "(Landroid/net/Uri;Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;") \
  664. CALLBACK (contentSharerGetStreamTypes, "contentSharerGetStreamTypes", "(Landroid/net/Uri;Ljava/lang/String;)[Ljava/lang/String;") \
  665. DECLARE_JNI_CLASS_WITH_MIN_SDK (JuceSharingContentProvider, "com/roli/juce/JuceSharingContentProvider", 16)
  666. #undef JNI_CLASS_MEMBERS
  667. static jobject JNICALL contentSharerQuery (JNIEnv*, jobject contentProvider, jobject uri, jobjectArray projection)
  668. {
  669. if (auto *pimpl = (ContentSharer::ContentSharerNativeImpl *) ContentSharer::getInstance ()->pimpl.get ())
  670. return pimpl->query (LocalRef<jobject> (static_cast<jobject> (contentProvider)),
  671. LocalRef<jobject> (static_cast<jobject> (uri)),
  672. LocalRef<jobjectArray> (static_cast<jobjectArray> (projection)));
  673. return nullptr;
  674. }
  675. static jobject JNICALL contentSharerOpenFile (JNIEnv*, jobject contentProvider, jobject uri, jstring mode)
  676. {
  677. if (auto* pimpl = (ContentSharer::ContentSharerNativeImpl*) ContentSharer::getInstance()->pimpl.get())
  678. return pimpl->openFile (LocalRef<jobject> (static_cast<jobject> (contentProvider)),
  679. LocalRef<jobject> (static_cast<jobject> (uri)),
  680. LocalRef<jstring> (static_cast<jstring> (mode)));
  681. return nullptr;
  682. }
  683. static jobjectArray JNICALL contentSharerGetStreamTypes (JNIEnv*, jobject /*contentProvider*/, jobject uri, jstring mimeTypeFilter)
  684. {
  685. if (auto* pimpl = (ContentSharer::ContentSharerNativeImpl*) ContentSharer::getInstance()->pimpl.get())
  686. return pimpl->getStreamTypes (LocalRef<jobject> (static_cast<jobject> (uri)),
  687. LocalRef<jstring> (static_cast<jstring> (mimeTypeFilter)));
  688. return nullptr;
  689. }
  690. };
  691. //==============================================================================
  692. ContentSharer::Pimpl* ContentSharer::createPimpl()
  693. {
  694. return new ContentSharerNativeImpl (*this);
  695. }
  696. ContentSharer::ContentSharerNativeImpl::JuceSharingContentProvider_Class ContentSharer::ContentSharerNativeImpl::JuceSharingContentProvider;
  697. } // namespace juce