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.

1329 lines
47KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. package com.juce;
  18. import android.app.Activity;
  19. import android.app.AlertDialog;
  20. import android.content.DialogInterface;
  21. import android.content.Context;
  22. import android.content.Intent;
  23. import android.content.res.Configuration;
  24. import android.content.pm.PackageInfo;
  25. import android.content.pm.PackageManager;
  26. import android.net.Uri;
  27. import android.os.Bundle;
  28. import android.os.Looper;
  29. import android.os.Handler;
  30. import android.os.ParcelUuid;
  31. import android.os.Environment;
  32. import android.view.*;
  33. import android.view.inputmethod.BaseInputConnection;
  34. import android.view.inputmethod.EditorInfo;
  35. import android.view.inputmethod.InputConnection;
  36. import android.view.inputmethod.InputMethodManager;
  37. import android.graphics.*;
  38. import android.text.ClipboardManager;
  39. import android.text.InputType;
  40. import android.util.DisplayMetrics;
  41. import android.util.Log;
  42. import android.util.Pair;
  43. import java.lang.Runnable;
  44. import java.lang.ref.WeakReference;
  45. import java.lang.reflect.*;
  46. import java.util.*;
  47. import java.io.*;
  48. import java.net.URL;
  49. import java.net.HttpURLConnection;
  50. import android.media.AudioManager;
  51. import android.Manifest;
  52. import java.util.concurrent.CancellationException;
  53. import java.util.concurrent.Future;
  54. import java.util.concurrent.Executors;
  55. import java.util.concurrent.ExecutorService;
  56. import java.util.concurrent.ExecutionException;
  57. import java.util.concurrent.TimeUnit;
  58. import java.util.concurrent.Callable;
  59. import java.util.concurrent.TimeoutException;
  60. import java.util.concurrent.locks.ReentrantLock;
  61. import java.util.concurrent.atomic.*;
  62. $$JuceAndroidMidiImports$$ // If you get an error here, you need to re-save your project with the Projucer!
  63. //==============================================================================
  64. public class JuceAppActivity extends Activity
  65. {
  66. //==============================================================================
  67. static
  68. {
  69. System.loadLibrary ("juce_jni");
  70. }
  71. //==============================================================================
  72. public boolean isPermissionDeclaredInManifest (int permissionID)
  73. {
  74. String permissionToCheck = getAndroidPermissionName(permissionID);
  75. try
  76. {
  77. PackageInfo info = getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
  78. if (info.requestedPermissions != null)
  79. for (String permission : info.requestedPermissions)
  80. if (permission.equals (permissionToCheck))
  81. return true;
  82. }
  83. catch (PackageManager.NameNotFoundException e)
  84. {
  85. Log.d ("JUCE", "isPermissionDeclaredInManifest: PackageManager.NameNotFoundException = " + e.toString());
  86. }
  87. Log.d ("JUCE", "isPermissionDeclaredInManifest: could not find requested permission " + permissionToCheck);
  88. return false;
  89. }
  90. //==============================================================================
  91. // these have to match the values of enum PermissionID in C++ class RuntimePermissions:
  92. private static final int JUCE_PERMISSIONS_RECORD_AUDIO = 1;
  93. private static final int JUCE_PERMISSIONS_BLUETOOTH_MIDI = 2;
  94. private static final int JUCE_PERMISSIONS_READ_EXTERNAL_STORAGE = 3;
  95. private static final int JUCE_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 4;
  96. private static String getAndroidPermissionName (int permissionID)
  97. {
  98. switch (permissionID)
  99. {
  100. case JUCE_PERMISSIONS_RECORD_AUDIO: return Manifest.permission.RECORD_AUDIO;
  101. case JUCE_PERMISSIONS_BLUETOOTH_MIDI: return Manifest.permission.ACCESS_COARSE_LOCATION;
  102. // use string value as this is not defined in SDKs < 16
  103. case JUCE_PERMISSIONS_READ_EXTERNAL_STORAGE: return "android.permission.READ_EXTERNAL_STORAGE";
  104. case JUCE_PERMISSIONS_WRITE_EXTERNAL_STORAGE: return Manifest.permission.WRITE_EXTERNAL_STORAGE;
  105. }
  106. // unknown permission ID!
  107. assert false;
  108. return new String();
  109. }
  110. public boolean isPermissionGranted (int permissionID)
  111. {
  112. return getApplicationContext().checkCallingOrSelfPermission (getAndroidPermissionName (permissionID)) == PackageManager.PERMISSION_GRANTED;
  113. }
  114. private Map<Integer, Long> permissionCallbackPtrMap;
  115. public void requestRuntimePermission (int permissionID, long ptrToCallback)
  116. {
  117. String permissionName = getAndroidPermissionName (permissionID);
  118. if (getApplicationContext().checkCallingOrSelfPermission (permissionName) != PackageManager.PERMISSION_GRANTED)
  119. {
  120. // remember callbackPtr, request permissions, and let onRequestPermissionResult call callback asynchronously
  121. permissionCallbackPtrMap.put (permissionID, ptrToCallback);
  122. requestPermissionsCompat (new String[]{permissionName}, permissionID);
  123. }
  124. else
  125. {
  126. // permissions were already granted before, we can call callback directly
  127. androidRuntimePermissionsCallback (true, ptrToCallback);
  128. }
  129. }
  130. private native void androidRuntimePermissionsCallback (boolean permissionWasGranted, long ptrToCallback);
  131. $$JuceAndroidRuntimePermissionsCode$$ // If you get an error here, you need to re-save your project with the Projucer!
  132. //==============================================================================
  133. public interface JuceMidiPort
  134. {
  135. boolean isInputPort();
  136. // start, stop does nothing on an output port
  137. void start();
  138. void stop();
  139. void close();
  140. // send will do nothing on an input port
  141. void sendMidi (byte[] msg, int offset, int count);
  142. }
  143. //==============================================================================
  144. $$JuceAndroidMidiCode$$ // If you get an error here, you need to re-save your project with the Projucer!
  145. //==============================================================================
  146. @Override
  147. public void onCreate (Bundle savedInstanceState)
  148. {
  149. super.onCreate (savedInstanceState);
  150. isScreenSaverEnabled = true;
  151. hideActionBar();
  152. viewHolder = new ViewHolder (this);
  153. setContentView (viewHolder);
  154. setVolumeControlStream (AudioManager.STREAM_MUSIC);
  155. permissionCallbackPtrMap = new HashMap<Integer, Long>();
  156. }
  157. @Override
  158. protected void onDestroy()
  159. {
  160. quitApp();
  161. super.onDestroy();
  162. clearDataCache();
  163. }
  164. @Override
  165. protected void onPause()
  166. {
  167. suspendApp();
  168. try
  169. {
  170. Thread.sleep (1000); // This is a bit of a hack to avoid some hard-to-track-down
  171. // openGL glitches when pausing/resuming apps..
  172. } catch (InterruptedException e) {}
  173. super.onPause();
  174. }
  175. @Override
  176. protected void onResume()
  177. {
  178. super.onResume();
  179. resumeApp();
  180. }
  181. @Override
  182. public void onConfigurationChanged (Configuration cfg)
  183. {
  184. super.onConfigurationChanged (cfg);
  185. setContentView (viewHolder);
  186. }
  187. private void callAppLauncher()
  188. {
  189. launchApp (getApplicationInfo().publicSourceDir,
  190. getApplicationInfo().dataDir);
  191. }
  192. private void hideActionBar()
  193. {
  194. // get "getActionBar" method
  195. java.lang.reflect.Method getActionBarMethod = null;
  196. try
  197. {
  198. getActionBarMethod = this.getClass().getMethod ("getActionBar");
  199. }
  200. catch (SecurityException e) { return; }
  201. catch (NoSuchMethodException e) { return; }
  202. if (getActionBarMethod == null) return;
  203. // invoke "getActionBar" method
  204. Object actionBar = null;
  205. try
  206. {
  207. actionBar = getActionBarMethod.invoke (this);
  208. }
  209. catch (java.lang.IllegalArgumentException e) { return; }
  210. catch (java.lang.IllegalAccessException e) { return; }
  211. catch (java.lang.reflect.InvocationTargetException e) { return; }
  212. if (actionBar == null) return;
  213. // get "hide" method
  214. java.lang.reflect.Method actionBarHideMethod = null;
  215. try
  216. {
  217. actionBarHideMethod = actionBar.getClass().getMethod ("hide");
  218. }
  219. catch (SecurityException e) { return; }
  220. catch (NoSuchMethodException e) { return; }
  221. if (actionBarHideMethod == null) return;
  222. // invoke "hide" method
  223. try
  224. {
  225. actionBarHideMethod.invoke (actionBar);
  226. }
  227. catch (java.lang.IllegalArgumentException e) {}
  228. catch (java.lang.IllegalAccessException e) {}
  229. catch (java.lang.reflect.InvocationTargetException e) {}
  230. }
  231. void requestPermissionsCompat (String[] permissions, int requestCode)
  232. {
  233. Method requestPermissionsMethod = null;
  234. try
  235. {
  236. requestPermissionsMethod = this.getClass().getMethod ("requestPermissions",
  237. String[].class, int.class);
  238. }
  239. catch (SecurityException e) { return; }
  240. catch (NoSuchMethodException e) { return; }
  241. if (requestPermissionsMethod == null) return;
  242. try
  243. {
  244. requestPermissionsMethod.invoke (this, permissions, requestCode);
  245. }
  246. catch (java.lang.IllegalArgumentException e) {}
  247. catch (java.lang.IllegalAccessException e) {}
  248. catch (java.lang.reflect.InvocationTargetException e) {}
  249. }
  250. //==============================================================================
  251. private native void launchApp (String appFile, String appDataDir);
  252. private native void quitApp();
  253. private native void suspendApp();
  254. private native void resumeApp();
  255. private native void setScreenSize (int screenWidth, int screenHeight, int dpi);
  256. private native void appActivityResult (int requestCode, int resultCode, Intent data);
  257. //==============================================================================
  258. private ViewHolder viewHolder;
  259. private MidiDeviceManager midiDeviceManager = null;
  260. private BluetoothManager bluetoothManager = null;
  261. private boolean isScreenSaverEnabled;
  262. private java.util.Timer keepAliveTimer;
  263. public final ComponentPeerView createNewView (boolean opaque, long host)
  264. {
  265. ComponentPeerView v = new ComponentPeerView (this, opaque, host);
  266. viewHolder.addView (v);
  267. return v;
  268. }
  269. public final void deleteView (ComponentPeerView view)
  270. {
  271. ViewGroup group = (ViewGroup) (view.getParent());
  272. if (group != null)
  273. group.removeView (view);
  274. }
  275. public final void deleteNativeSurfaceView (NativeSurfaceView view)
  276. {
  277. ViewGroup group = (ViewGroup) (view.getParent());
  278. if (group != null)
  279. group.removeView (view);
  280. }
  281. final class ViewHolder extends ViewGroup
  282. {
  283. public ViewHolder (Context context)
  284. {
  285. super (context);
  286. setDescendantFocusability (ViewGroup.FOCUS_AFTER_DESCENDANTS);
  287. setFocusable (false);
  288. }
  289. protected final void onLayout (boolean changed, int left, int top, int right, int bottom)
  290. {
  291. setScreenSize (getWidth(), getHeight(), getDPI());
  292. if (isFirstResize)
  293. {
  294. isFirstResize = false;
  295. callAppLauncher();
  296. }
  297. }
  298. private final int getDPI()
  299. {
  300. DisplayMetrics metrics = new DisplayMetrics();
  301. getWindowManager().getDefaultDisplay().getMetrics (metrics);
  302. return metrics.densityDpi;
  303. }
  304. private boolean isFirstResize = true;
  305. }
  306. public final void excludeClipRegion (android.graphics.Canvas canvas, float left, float top, float right, float bottom)
  307. {
  308. canvas.clipRect (left, top, right, bottom, android.graphics.Region.Op.DIFFERENCE);
  309. }
  310. //==============================================================================
  311. public final void setScreenSaver (boolean enabled)
  312. {
  313. if (isScreenSaverEnabled != enabled)
  314. {
  315. isScreenSaverEnabled = enabled;
  316. if (keepAliveTimer != null)
  317. {
  318. keepAliveTimer.cancel();
  319. keepAliveTimer = null;
  320. }
  321. if (enabled)
  322. {
  323. getWindow().clearFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  324. }
  325. else
  326. {
  327. getWindow().addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  328. // If no user input is received after about 3 seconds, the OS will lower the
  329. // task's priority, so this timer forces it to be kept active.
  330. keepAliveTimer = new java.util.Timer();
  331. keepAliveTimer.scheduleAtFixedRate (new TimerTask()
  332. {
  333. @Override
  334. public void run()
  335. {
  336. android.app.Instrumentation instrumentation = new android.app.Instrumentation();
  337. try
  338. {
  339. instrumentation.sendKeyDownUpSync (KeyEvent.KEYCODE_UNKNOWN);
  340. }
  341. catch (Exception e)
  342. {
  343. }
  344. }
  345. }, 2000, 2000);
  346. }
  347. }
  348. }
  349. public final boolean getScreenSaver()
  350. {
  351. return isScreenSaverEnabled;
  352. }
  353. //==============================================================================
  354. public final String getClipboardContent()
  355. {
  356. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  357. return clipboard.getText().toString();
  358. }
  359. public final void setClipboardContent (String newText)
  360. {
  361. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  362. clipboard.setText (newText);
  363. }
  364. //==============================================================================
  365. public final void showMessageBox (String title, String message, final long callback)
  366. {
  367. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  368. builder.setTitle (title)
  369. .setMessage (message)
  370. .setCancelable (true)
  371. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  372. {
  373. public void onClick (DialogInterface dialog, int id)
  374. {
  375. dialog.cancel();
  376. JuceAppActivity.this.alertDismissed (callback, 0);
  377. }
  378. });
  379. builder.create().show();
  380. }
  381. public final void showOkCancelBox (String title, String message, final long callback,
  382. String okButtonText, String cancelButtonText)
  383. {
  384. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  385. builder.setTitle (title)
  386. .setMessage (message)
  387. .setCancelable (true)
  388. .setPositiveButton (okButtonText.isEmpty() ? "OK" : okButtonText, new DialogInterface.OnClickListener()
  389. {
  390. public void onClick (DialogInterface dialog, int id)
  391. {
  392. dialog.cancel();
  393. JuceAppActivity.this.alertDismissed (callback, 1);
  394. }
  395. })
  396. .setNegativeButton (cancelButtonText.isEmpty() ? "Cancel" : cancelButtonText, new DialogInterface.OnClickListener()
  397. {
  398. public void onClick (DialogInterface dialog, int id)
  399. {
  400. dialog.cancel();
  401. JuceAppActivity.this.alertDismissed (callback, 0);
  402. }
  403. });
  404. builder.create().show();
  405. }
  406. public final void showYesNoCancelBox (String title, String message, final long callback)
  407. {
  408. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  409. builder.setTitle (title)
  410. .setMessage (message)
  411. .setCancelable (true)
  412. .setPositiveButton ("Yes", new DialogInterface.OnClickListener()
  413. {
  414. public void onClick (DialogInterface dialog, int id)
  415. {
  416. dialog.cancel();
  417. JuceAppActivity.this.alertDismissed (callback, 1);
  418. }
  419. })
  420. .setNegativeButton ("No", new DialogInterface.OnClickListener()
  421. {
  422. public void onClick (DialogInterface dialog, int id)
  423. {
  424. dialog.cancel();
  425. JuceAppActivity.this.alertDismissed (callback, 2);
  426. }
  427. })
  428. .setNeutralButton ("Cancel", new DialogInterface.OnClickListener()
  429. {
  430. public void onClick (DialogInterface dialog, int id)
  431. {
  432. dialog.cancel();
  433. JuceAppActivity.this.alertDismissed (callback, 0);
  434. }
  435. });
  436. builder.create().show();
  437. }
  438. public native void alertDismissed (long callback, int id);
  439. //==============================================================================
  440. public final class ComponentPeerView extends ViewGroup
  441. implements View.OnFocusChangeListener
  442. {
  443. public ComponentPeerView (Context context, boolean opaque_, long host)
  444. {
  445. super (context);
  446. this.host = host;
  447. setWillNotDraw (false);
  448. opaque = opaque_;
  449. setFocusable (true);
  450. setFocusableInTouchMode (true);
  451. setOnFocusChangeListener (this);
  452. requestFocus();
  453. // swap red and blue colours to match internal opengl texture format
  454. ColorMatrix colorMatrix = new ColorMatrix();
  455. float[] colorTransform = { 0, 0, 1.0f, 0, 0,
  456. 0, 1.0f, 0, 0, 0,
  457. 1.0f, 0, 0, 0, 0,
  458. 0, 0, 0, 1.0f, 0 };
  459. colorMatrix.set (colorTransform);
  460. paint.setColorFilter (new ColorMatrixColorFilter (colorMatrix));
  461. }
  462. //==============================================================================
  463. private native void handlePaint (long host, Canvas canvas, Paint paint);
  464. @Override
  465. public void onDraw (Canvas canvas)
  466. {
  467. handlePaint (host, canvas, paint);
  468. }
  469. @Override
  470. public boolean isOpaque()
  471. {
  472. return opaque;
  473. }
  474. private boolean opaque;
  475. private long host;
  476. private Paint paint = new Paint();
  477. //==============================================================================
  478. private native void handleMouseDown (long host, int index, float x, float y, long time);
  479. private native void handleMouseDrag (long host, int index, float x, float y, long time);
  480. private native void handleMouseUp (long host, int index, float x, float y, long time);
  481. @Override
  482. public boolean onTouchEvent (MotionEvent event)
  483. {
  484. int action = event.getAction();
  485. long time = event.getEventTime();
  486. switch (action & MotionEvent.ACTION_MASK)
  487. {
  488. case MotionEvent.ACTION_DOWN:
  489. handleMouseDown (host, event.getPointerId(0), event.getX(), event.getY(), time);
  490. return true;
  491. case MotionEvent.ACTION_CANCEL:
  492. case MotionEvent.ACTION_UP:
  493. handleMouseUp (host, event.getPointerId(0), event.getX(), event.getY(), time);
  494. return true;
  495. case MotionEvent.ACTION_MOVE:
  496. {
  497. int n = event.getPointerCount();
  498. for (int i = 0; i < n; ++i)
  499. handleMouseDrag (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  500. return true;
  501. }
  502. case MotionEvent.ACTION_POINTER_UP:
  503. {
  504. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  505. handleMouseUp (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  506. return true;
  507. }
  508. case MotionEvent.ACTION_POINTER_DOWN:
  509. {
  510. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  511. handleMouseDown (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  512. return true;
  513. }
  514. default:
  515. break;
  516. }
  517. return false;
  518. }
  519. //==============================================================================
  520. private native void handleKeyDown (long host, int keycode, int textchar);
  521. private native void handleKeyUp (long host, int keycode, int textchar);
  522. private native void handleBackButton (long host);
  523. public void showKeyboard (String type)
  524. {
  525. InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
  526. if (imm != null)
  527. {
  528. if (type.length() > 0)
  529. {
  530. imm.showSoftInput (this, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
  531. imm.setInputMethod (getWindowToken(), type);
  532. }
  533. else
  534. {
  535. imm.hideSoftInputFromWindow (getWindowToken(), 0);
  536. }
  537. }
  538. }
  539. @Override
  540. public boolean onKeyDown (int keyCode, KeyEvent event)
  541. {
  542. switch (keyCode)
  543. {
  544. case KeyEvent.KEYCODE_VOLUME_UP:
  545. case KeyEvent.KEYCODE_VOLUME_DOWN:
  546. return super.onKeyDown (keyCode, event);
  547. case KeyEvent.KEYCODE_BACK:
  548. {
  549. handleBackButton (host);
  550. return true;
  551. }
  552. default:
  553. break;
  554. }
  555. handleKeyDown (host, keyCode, event.getUnicodeChar());
  556. return true;
  557. }
  558. @Override
  559. public boolean onKeyUp (int keyCode, KeyEvent event)
  560. {
  561. handleKeyUp (host, keyCode, event.getUnicodeChar());
  562. return true;
  563. }
  564. @Override
  565. public boolean onKeyMultiple (int keyCode, int count, KeyEvent event)
  566. {
  567. if (keyCode != KeyEvent.KEYCODE_UNKNOWN || event.getAction() != KeyEvent.ACTION_MULTIPLE)
  568. return super.onKeyMultiple (keyCode, count, event);
  569. if (event.getCharacters() != null)
  570. {
  571. int utf8Char = event.getCharacters().codePointAt (0);
  572. handleKeyDown (host, utf8Char, utf8Char);
  573. return true;
  574. }
  575. return false;
  576. }
  577. // this is here to make keyboard entry work on a Galaxy Tab2 10.1
  578. @Override
  579. public InputConnection onCreateInputConnection (EditorInfo outAttrs)
  580. {
  581. outAttrs.actionLabel = "";
  582. outAttrs.hintText = "";
  583. outAttrs.initialCapsMode = 0;
  584. outAttrs.initialSelEnd = outAttrs.initialSelStart = -1;
  585. outAttrs.label = "";
  586. outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
  587. outAttrs.inputType = InputType.TYPE_NULL;
  588. return new BaseInputConnection (this, false);
  589. }
  590. //==============================================================================
  591. @Override
  592. protected void onSizeChanged (int w, int h, int oldw, int oldh)
  593. {
  594. super.onSizeChanged (w, h, oldw, oldh);
  595. viewSizeChanged (host);
  596. }
  597. @Override
  598. protected void onLayout (boolean changed, int left, int top, int right, int bottom)
  599. {
  600. for (int i = getChildCount(); --i >= 0;)
  601. requestTransparentRegion (getChildAt (i));
  602. }
  603. private native void viewSizeChanged (long host);
  604. @Override
  605. public void onFocusChange (View v, boolean hasFocus)
  606. {
  607. if (v == this)
  608. focusChanged (host, hasFocus);
  609. }
  610. private native void focusChanged (long host, boolean hasFocus);
  611. public void setViewName (String newName) {}
  612. public void setSystemUiVisibilityCompat (int visibility)
  613. {
  614. Method systemUIVisibilityMethod = null;
  615. try
  616. {
  617. systemUIVisibilityMethod = this.getClass().getMethod ("setSystemUiVisibility", int.class);
  618. }
  619. catch (SecurityException e) { return; }
  620. catch (NoSuchMethodException e) { return; }
  621. if (systemUIVisibilityMethod == null) return;
  622. try
  623. {
  624. systemUIVisibilityMethod.invoke (this, visibility);
  625. }
  626. catch (java.lang.IllegalArgumentException e) {}
  627. catch (java.lang.IllegalAccessException e) {}
  628. catch (java.lang.reflect.InvocationTargetException e) {}
  629. }
  630. public boolean isVisible() { return getVisibility() == VISIBLE; }
  631. public void setVisible (boolean b) { setVisibility (b ? VISIBLE : INVISIBLE); }
  632. public boolean containsPoint (int x, int y)
  633. {
  634. return true; //xxx needs to check overlapping views
  635. }
  636. }
  637. //==============================================================================
  638. public static class NativeSurfaceView extends SurfaceView
  639. implements SurfaceHolder.Callback
  640. {
  641. private long nativeContext = 0;
  642. NativeSurfaceView (Context context, long nativeContextPtr)
  643. {
  644. super (context);
  645. nativeContext = nativeContextPtr;
  646. }
  647. public Surface getNativeSurface()
  648. {
  649. Surface retval = null;
  650. SurfaceHolder holder = getHolder();
  651. if (holder != null)
  652. retval = holder.getSurface();
  653. return retval;
  654. }
  655. //==============================================================================
  656. @Override
  657. public void surfaceChanged (SurfaceHolder holder, int format, int width, int height)
  658. {
  659. surfaceChangedNative (nativeContext, holder, format, width, height);
  660. }
  661. @Override
  662. public void surfaceCreated (SurfaceHolder holder)
  663. {
  664. surfaceCreatedNative (nativeContext, holder);
  665. }
  666. @Override
  667. public void surfaceDestroyed (SurfaceHolder holder)
  668. {
  669. surfaceDestroyedNative (nativeContext, holder);
  670. }
  671. @Override
  672. protected void dispatchDraw (Canvas canvas)
  673. {
  674. super.dispatchDraw (canvas);
  675. dispatchDrawNative (nativeContext, canvas);
  676. }
  677. //==============================================================================
  678. @Override
  679. protected void onAttachedToWindow ()
  680. {
  681. super.onAttachedToWindow();
  682. getHolder().addCallback (this);
  683. }
  684. @Override
  685. protected void onDetachedFromWindow ()
  686. {
  687. super.onDetachedFromWindow();
  688. getHolder().removeCallback (this);
  689. }
  690. //==============================================================================
  691. private native void dispatchDrawNative (long nativeContextPtr, Canvas canvas);
  692. private native void surfaceCreatedNative (long nativeContextptr, SurfaceHolder holder);
  693. private native void surfaceDestroyedNative (long nativeContextptr, SurfaceHolder holder);
  694. private native void surfaceChangedNative (long nativeContextptr, SurfaceHolder holder,
  695. int format, int width, int height);
  696. }
  697. public NativeSurfaceView createNativeSurfaceView (long nativeSurfacePtr)
  698. {
  699. return new NativeSurfaceView (this, nativeSurfacePtr);
  700. }
  701. //==============================================================================
  702. public final int[] renderGlyph (char glyph1, char glyph2, Paint paint, android.graphics.Matrix matrix, Rect bounds)
  703. {
  704. Path p = new Path();
  705. char[] str = { glyph1, glyph2 };
  706. paint.getTextPath (str, 0, (glyph2 != 0 ? 2 : 1), 0.0f, 0.0f, p);
  707. RectF boundsF = new RectF();
  708. p.computeBounds (boundsF, true);
  709. matrix.mapRect (boundsF);
  710. boundsF.roundOut (bounds);
  711. bounds.left--;
  712. bounds.right++;
  713. final int w = bounds.width();
  714. final int h = Math.max (1, bounds.height());
  715. Bitmap bm = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
  716. Canvas c = new Canvas (bm);
  717. matrix.postTranslate (-bounds.left, -bounds.top);
  718. c.setMatrix (matrix);
  719. c.drawPath (p, paint);
  720. final int sizeNeeded = w * h;
  721. if (cachedRenderArray.length < sizeNeeded)
  722. cachedRenderArray = new int [sizeNeeded];
  723. bm.getPixels (cachedRenderArray, 0, w, 0, 0, w, h);
  724. bm.recycle();
  725. return cachedRenderArray;
  726. }
  727. private int[] cachedRenderArray = new int [256];
  728. //==============================================================================
  729. public static class NativeInvocationHandler implements InvocationHandler
  730. {
  731. public NativeInvocationHandler (long nativeContextRef)
  732. {
  733. nativeContext = nativeContextRef;
  734. }
  735. @Override
  736. public void finalize()
  737. {
  738. dispatchFinalize (nativeContext);
  739. }
  740. @Override
  741. public Object invoke (Object proxy, Method method, Object[] args) throws Throwable
  742. {
  743. return dispatchInvoke (nativeContext, proxy, method, args);
  744. }
  745. //==============================================================================
  746. private long nativeContext = 0;
  747. private native void dispatchFinalize (long nativeContextRef);
  748. private native Object dispatchInvoke (long nativeContextRef, Object proxy, Method method, Object[] args);
  749. }
  750. public static InvocationHandler createInvocationHandler (long nativeContextRef)
  751. {
  752. return new NativeInvocationHandler (nativeContextRef);
  753. }
  754. //==============================================================================
  755. public static class HTTPStream
  756. {
  757. public HTTPStream (HttpURLConnection connection_,
  758. int[] statusCode_,
  759. StringBuffer responseHeaders_)
  760. {
  761. connection = connection_;
  762. statusCode = statusCode_;
  763. responseHeaders = responseHeaders_;
  764. }
  765. private final InputStream getCancellableStream (final boolean isInput) throws ExecutionException
  766. {
  767. synchronized (createFutureLock)
  768. {
  769. if (hasBeenCancelled.get())
  770. return null;
  771. streamFuture = executor.submit (new Callable<BufferedInputStream>()
  772. {
  773. @Override
  774. public BufferedInputStream call() throws IOException
  775. {
  776. return new BufferedInputStream (isInput ? connection.getInputStream()
  777. : connection.getErrorStream());
  778. }
  779. });
  780. }
  781. try
  782. {
  783. if (connection.getConnectTimeout() > 0)
  784. return streamFuture.get (connection.getConnectTimeout(), TimeUnit.MILLISECONDS);
  785. else
  786. return streamFuture.get();
  787. }
  788. catch (InterruptedException e)
  789. {
  790. return null;
  791. }
  792. catch (TimeoutException e)
  793. {
  794. return null;
  795. }
  796. catch (CancellationException e)
  797. {
  798. return null;
  799. }
  800. }
  801. public final boolean connect()
  802. {
  803. try
  804. {
  805. try
  806. {
  807. synchronized (createStreamLock)
  808. {
  809. if (hasBeenCancelled.get())
  810. return false;
  811. inputStream = getCancellableStream (true);
  812. }
  813. }
  814. catch (ExecutionException e)
  815. {
  816. if (connection.getResponseCode() < 400)
  817. {
  818. statusCode[0] = connection.getResponseCode();
  819. connection.disconnect();
  820. return false;
  821. }
  822. }
  823. finally
  824. {
  825. statusCode[0] = connection.getResponseCode();
  826. }
  827. synchronized (createStreamLock)
  828. {
  829. if (hasBeenCancelled.get())
  830. return false;
  831. try
  832. {
  833. if (statusCode[0] >= 400)
  834. inputStream = getCancellableStream (false);
  835. else
  836. inputStream = getCancellableStream (true);
  837. }
  838. catch (ExecutionException e)
  839. {}
  840. }
  841. for (java.util.Map.Entry<String, java.util.List<String>> entry : connection.getHeaderFields().entrySet())
  842. if (entry.getKey() != null && entry.getValue() != null)
  843. responseHeaders.append (entry.getKey() + ": "
  844. + android.text.TextUtils.join (",", entry.getValue()) + "\n");
  845. return true;
  846. }
  847. catch (IOException e)
  848. {
  849. return false;
  850. }
  851. }
  852. public final void release()
  853. {
  854. hasBeenCancelled.set (true);
  855. try
  856. {
  857. if (! createStreamLock.tryLock())
  858. {
  859. synchronized (createFutureLock)
  860. {
  861. if (streamFuture != null)
  862. streamFuture.cancel (true);
  863. }
  864. createStreamLock.lock();
  865. }
  866. if (inputStream != null)
  867. inputStream.close();
  868. }
  869. catch (IOException e)
  870. {}
  871. finally
  872. {
  873. createStreamLock.unlock();
  874. }
  875. connection.disconnect();
  876. }
  877. public final int read (byte[] buffer, int numBytes)
  878. {
  879. int num = 0;
  880. try
  881. {
  882. synchronized (createStreamLock)
  883. {
  884. if (inputStream != null)
  885. num = inputStream.read (buffer, 0, numBytes);
  886. }
  887. }
  888. catch (IOException e)
  889. {}
  890. if (num > 0)
  891. position += num;
  892. return num;
  893. }
  894. public final long getPosition() { return position; }
  895. public final long getTotalLength() { return -1; }
  896. public final boolean isExhausted() { return false; }
  897. public final boolean setPosition (long newPos) { return false; }
  898. private HttpURLConnection connection;
  899. private int[] statusCode;
  900. private StringBuffer responseHeaders;
  901. private InputStream inputStream;
  902. private long position;
  903. private final ReentrantLock createStreamLock = new ReentrantLock();
  904. private final Object createFutureLock = new Object();
  905. private AtomicBoolean hasBeenCancelled = new AtomicBoolean();
  906. private final ExecutorService executor = Executors.newCachedThreadPool (Executors.defaultThreadFactory());
  907. Future<BufferedInputStream> streamFuture;
  908. }
  909. public static final HTTPStream createHTTPStream (String address, boolean isPost, byte[] postData,
  910. String headers, int timeOutMs, int[] statusCode,
  911. StringBuffer responseHeaders, int numRedirectsToFollow,
  912. String httpRequestCmd)
  913. {
  914. // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL)
  915. if (timeOutMs < 0)
  916. timeOutMs = 0;
  917. else if (timeOutMs == 0)
  918. timeOutMs = 30000;
  919. // headers - if not empty, this string is appended onto the headers that are used for the request. It must therefore be a valid set of HTML header directives, separated by newlines.
  920. // So convert headers string to an array, with an element for each line
  921. String headerLines[] = headers.split("\\n");
  922. for (;;)
  923. {
  924. try
  925. {
  926. HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());
  927. if (connection != null)
  928. {
  929. try
  930. {
  931. connection.setInstanceFollowRedirects (false);
  932. connection.setConnectTimeout (timeOutMs);
  933. connection.setReadTimeout (timeOutMs);
  934. // Set request headers
  935. for (int i = 0; i < headerLines.length; ++i)
  936. {
  937. int pos = headerLines[i].indexOf (":");
  938. if (pos > 0 && pos < headerLines[i].length())
  939. {
  940. String field = headerLines[i].substring (0, pos);
  941. String value = headerLines[i].substring (pos + 1);
  942. if (value.length() > 0)
  943. connection.setRequestProperty (field, value);
  944. }
  945. }
  946. connection.setRequestMethod (httpRequestCmd);
  947. if (isPost)
  948. {
  949. connection.setDoOutput (true);
  950. if (postData != null)
  951. {
  952. OutputStream out = connection.getOutputStream();
  953. out.write(postData);
  954. out.flush();
  955. }
  956. }
  957. HTTPStream httpStream = new HTTPStream (connection, statusCode, responseHeaders);
  958. // Process redirect & continue as necessary
  959. int status = statusCode[0];
  960. if (--numRedirectsToFollow >= 0
  961. && (status == 301 || status == 302 || status == 303 || status == 307))
  962. {
  963. // Assumes only one occurrence of "Location"
  964. int pos1 = responseHeaders.indexOf ("Location:") + 10;
  965. int pos2 = responseHeaders.indexOf ("\n", pos1);
  966. if (pos2 > pos1)
  967. {
  968. String newLocation = responseHeaders.substring(pos1, pos2);
  969. // Handle newLocation whether it's absolute or relative
  970. URL baseUrl = new URL (address);
  971. URL newUrl = new URL (baseUrl, newLocation);
  972. String transformedNewLocation = newUrl.toString();
  973. if (transformedNewLocation != address)
  974. {
  975. address = transformedNewLocation;
  976. // Clear responseHeaders before next iteration
  977. responseHeaders.delete (0, responseHeaders.length());
  978. continue;
  979. }
  980. }
  981. }
  982. return httpStream;
  983. }
  984. catch (Throwable e)
  985. {
  986. connection.disconnect();
  987. }
  988. }
  989. }
  990. catch (Throwable e) {}
  991. return null;
  992. }
  993. }
  994. public final void launchURL (String url)
  995. {
  996. startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse (url)));
  997. }
  998. public static final String getLocaleValue (boolean isRegion)
  999. {
  1000. java.util.Locale locale = java.util.Locale.getDefault();
  1001. return isRegion ? locale.getCountry()
  1002. : locale.getLanguage();
  1003. }
  1004. private static final String getFileLocation (String type)
  1005. {
  1006. return Environment.getExternalStoragePublicDirectory (type).getAbsolutePath();
  1007. }
  1008. public static final String getDocumentsFolder() { return Environment.getDataDirectory().getAbsolutePath(); }
  1009. public static final String getPicturesFolder() { return getFileLocation (Environment.DIRECTORY_PICTURES); }
  1010. public static final String getMusicFolder() { return getFileLocation (Environment.DIRECTORY_MUSIC); }
  1011. public static final String getMoviesFolder() { return getFileLocation (Environment.DIRECTORY_MOVIES); }
  1012. public static final String getDownloadsFolder() { return getFileLocation (Environment.DIRECTORY_DOWNLOADS); }
  1013. //==============================================================================
  1014. @Override
  1015. protected void onActivityResult (int requestCode, int resultCode, Intent data)
  1016. {
  1017. appActivityResult (requestCode, resultCode, data);
  1018. }
  1019. //==============================================================================
  1020. public final Typeface getTypeFaceFromAsset (String assetName)
  1021. {
  1022. try
  1023. {
  1024. return Typeface.createFromAsset (this.getResources().getAssets(), assetName);
  1025. }
  1026. catch (Throwable e) {}
  1027. return null;
  1028. }
  1029. final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
  1030. public static String bytesToHex (byte[] bytes)
  1031. {
  1032. char[] hexChars = new char[bytes.length * 2];
  1033. for (int j = 0; j < bytes.length; ++j)
  1034. {
  1035. int v = bytes[j] & 0xff;
  1036. hexChars[j * 2] = hexArray[v >>> 4];
  1037. hexChars[j * 2 + 1] = hexArray[v & 0x0f];
  1038. }
  1039. return new String (hexChars);
  1040. }
  1041. final private java.util.Map dataCache = new java.util.HashMap();
  1042. synchronized private final File getDataCacheFile (byte[] data)
  1043. {
  1044. try
  1045. {
  1046. java.security.MessageDigest digest = java.security.MessageDigest.getInstance ("MD5");
  1047. digest.update (data);
  1048. String key = bytesToHex (digest.digest());
  1049. if (dataCache.containsKey (key))
  1050. return (File) dataCache.get (key);
  1051. File f = new File (this.getCacheDir(), "bindata_" + key);
  1052. f.delete();
  1053. FileOutputStream os = new FileOutputStream (f);
  1054. os.write (data, 0, data.length);
  1055. dataCache.put (key, f);
  1056. return f;
  1057. }
  1058. catch (Throwable e) {}
  1059. return null;
  1060. }
  1061. private final void clearDataCache()
  1062. {
  1063. java.util.Iterator it = dataCache.values().iterator();
  1064. while (it.hasNext())
  1065. {
  1066. File f = (File) it.next();
  1067. f.delete();
  1068. }
  1069. }
  1070. public final Typeface getTypeFaceFromByteArray (byte[] data)
  1071. {
  1072. try
  1073. {
  1074. File f = getDataCacheFile (data);
  1075. if (f != null)
  1076. return Typeface.createFromFile (f);
  1077. }
  1078. catch (Exception e)
  1079. {
  1080. Log.e ("JUCE", e.toString());
  1081. }
  1082. return null;
  1083. }
  1084. public final int getAndroidSDKVersion()
  1085. {
  1086. return android.os.Build.VERSION.SDK_INT;
  1087. }
  1088. public final String audioManagerGetProperty (String property)
  1089. {
  1090. Object obj = getSystemService (AUDIO_SERVICE);
  1091. if (obj == null)
  1092. return null;
  1093. java.lang.reflect.Method method;
  1094. try
  1095. {
  1096. method = obj.getClass().getMethod ("getProperty", String.class);
  1097. }
  1098. catch (SecurityException e) { return null; }
  1099. catch (NoSuchMethodException e) { return null; }
  1100. if (method == null)
  1101. return null;
  1102. try
  1103. {
  1104. return (String) method.invoke (obj, property);
  1105. }
  1106. catch (java.lang.IllegalArgumentException e) {}
  1107. catch (java.lang.IllegalAccessException e) {}
  1108. catch (java.lang.reflect.InvocationTargetException e) {}
  1109. return null;
  1110. }
  1111. public final boolean hasSystemFeature (String property)
  1112. {
  1113. return getPackageManager().hasSystemFeature (property);
  1114. }
  1115. }