The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

884 lines
38KB

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