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.

1321 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. //==============================================================================
  257. private ViewHolder viewHolder;
  258. private MidiDeviceManager midiDeviceManager = null;
  259. private BluetoothManager bluetoothManager = null;
  260. private boolean isScreenSaverEnabled;
  261. private java.util.Timer keepAliveTimer;
  262. public final ComponentPeerView createNewView (boolean opaque, long host)
  263. {
  264. ComponentPeerView v = new ComponentPeerView (this, opaque, host);
  265. viewHolder.addView (v);
  266. return v;
  267. }
  268. public final void deleteView (ComponentPeerView view)
  269. {
  270. ViewGroup group = (ViewGroup) (view.getParent());
  271. if (group != null)
  272. group.removeView (view);
  273. }
  274. public final void deleteNativeSurfaceView (NativeSurfaceView view)
  275. {
  276. ViewGroup group = (ViewGroup) (view.getParent());
  277. if (group != null)
  278. group.removeView (view);
  279. }
  280. final class ViewHolder extends ViewGroup
  281. {
  282. public ViewHolder (Context context)
  283. {
  284. super (context);
  285. setDescendantFocusability (ViewGroup.FOCUS_AFTER_DESCENDANTS);
  286. setFocusable (false);
  287. }
  288. protected final void onLayout (boolean changed, int left, int top, int right, int bottom)
  289. {
  290. setScreenSize (getWidth(), getHeight(), getDPI());
  291. if (isFirstResize)
  292. {
  293. isFirstResize = false;
  294. callAppLauncher();
  295. }
  296. }
  297. private final int getDPI()
  298. {
  299. DisplayMetrics metrics = new DisplayMetrics();
  300. getWindowManager().getDefaultDisplay().getMetrics (metrics);
  301. return metrics.densityDpi;
  302. }
  303. private boolean isFirstResize = true;
  304. }
  305. public final void excludeClipRegion (android.graphics.Canvas canvas, float left, float top, float right, float bottom)
  306. {
  307. canvas.clipRect (left, top, right, bottom, android.graphics.Region.Op.DIFFERENCE);
  308. }
  309. //==============================================================================
  310. public final void setScreenSaver (boolean enabled)
  311. {
  312. if (isScreenSaverEnabled != enabled)
  313. {
  314. isScreenSaverEnabled = enabled;
  315. if (keepAliveTimer != null)
  316. {
  317. keepAliveTimer.cancel();
  318. keepAliveTimer = null;
  319. }
  320. if (enabled)
  321. {
  322. getWindow().clearFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  323. }
  324. else
  325. {
  326. getWindow().addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  327. // If no user input is received after about 3 seconds, the OS will lower the
  328. // task's priority, so this timer forces it to be kept active.
  329. keepAliveTimer = new java.util.Timer();
  330. keepAliveTimer.scheduleAtFixedRate (new TimerTask()
  331. {
  332. @Override
  333. public void run()
  334. {
  335. android.app.Instrumentation instrumentation = new android.app.Instrumentation();
  336. try
  337. {
  338. instrumentation.sendKeyDownUpSync (KeyEvent.KEYCODE_UNKNOWN);
  339. }
  340. catch (Exception e)
  341. {
  342. }
  343. }
  344. }, 2000, 2000);
  345. }
  346. }
  347. }
  348. public final boolean getScreenSaver()
  349. {
  350. return isScreenSaverEnabled;
  351. }
  352. //==============================================================================
  353. public final String getClipboardContent()
  354. {
  355. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  356. return clipboard.getText().toString();
  357. }
  358. public final void setClipboardContent (String newText)
  359. {
  360. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  361. clipboard.setText (newText);
  362. }
  363. //==============================================================================
  364. public final void showMessageBox (String title, String message, final long callback)
  365. {
  366. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  367. builder.setTitle (title)
  368. .setMessage (message)
  369. .setCancelable (true)
  370. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  371. {
  372. public void onClick (DialogInterface dialog, int id)
  373. {
  374. dialog.cancel();
  375. JuceAppActivity.this.alertDismissed (callback, 0);
  376. }
  377. });
  378. builder.create().show();
  379. }
  380. public final void showOkCancelBox (String title, String message, final long callback,
  381. String okButtonText, String cancelButtonText)
  382. {
  383. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  384. builder.setTitle (title)
  385. .setMessage (message)
  386. .setCancelable (true)
  387. .setPositiveButton (okButtonText.isEmpty() ? "OK" : okButtonText, new DialogInterface.OnClickListener()
  388. {
  389. public void onClick (DialogInterface dialog, int id)
  390. {
  391. dialog.cancel();
  392. JuceAppActivity.this.alertDismissed (callback, 1);
  393. }
  394. })
  395. .setNegativeButton (cancelButtonText.isEmpty() ? "Cancel" : cancelButtonText, new DialogInterface.OnClickListener()
  396. {
  397. public void onClick (DialogInterface dialog, int id)
  398. {
  399. dialog.cancel();
  400. JuceAppActivity.this.alertDismissed (callback, 0);
  401. }
  402. });
  403. builder.create().show();
  404. }
  405. public final void showYesNoCancelBox (String title, String message, final long callback)
  406. {
  407. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  408. builder.setTitle (title)
  409. .setMessage (message)
  410. .setCancelable (true)
  411. .setPositiveButton ("Yes", new DialogInterface.OnClickListener()
  412. {
  413. public void onClick (DialogInterface dialog, int id)
  414. {
  415. dialog.cancel();
  416. JuceAppActivity.this.alertDismissed (callback, 1);
  417. }
  418. })
  419. .setNegativeButton ("No", new DialogInterface.OnClickListener()
  420. {
  421. public void onClick (DialogInterface dialog, int id)
  422. {
  423. dialog.cancel();
  424. JuceAppActivity.this.alertDismissed (callback, 2);
  425. }
  426. })
  427. .setNeutralButton ("Cancel", new DialogInterface.OnClickListener()
  428. {
  429. public void onClick (DialogInterface dialog, int id)
  430. {
  431. dialog.cancel();
  432. JuceAppActivity.this.alertDismissed (callback, 0);
  433. }
  434. });
  435. builder.create().show();
  436. }
  437. public native void alertDismissed (long callback, int id);
  438. //==============================================================================
  439. public final class ComponentPeerView extends ViewGroup
  440. implements View.OnFocusChangeListener
  441. {
  442. public ComponentPeerView (Context context, boolean opaque_, long host)
  443. {
  444. super (context);
  445. this.host = host;
  446. setWillNotDraw (false);
  447. opaque = opaque_;
  448. setFocusable (true);
  449. setFocusableInTouchMode (true);
  450. setOnFocusChangeListener (this);
  451. requestFocus();
  452. // swap red and blue colours to match internal opengl texture format
  453. ColorMatrix colorMatrix = new ColorMatrix();
  454. float[] colorTransform = { 0, 0, 1.0f, 0, 0,
  455. 0, 1.0f, 0, 0, 0,
  456. 1.0f, 0, 0, 0, 0,
  457. 0, 0, 0, 1.0f, 0 };
  458. colorMatrix.set (colorTransform);
  459. paint.setColorFilter (new ColorMatrixColorFilter (colorMatrix));
  460. }
  461. //==============================================================================
  462. private native void handlePaint (long host, Canvas canvas, Paint paint);
  463. @Override
  464. public void onDraw (Canvas canvas)
  465. {
  466. handlePaint (host, canvas, paint);
  467. }
  468. @Override
  469. public boolean isOpaque()
  470. {
  471. return opaque;
  472. }
  473. private boolean opaque;
  474. private long host;
  475. private Paint paint = new Paint();
  476. //==============================================================================
  477. private native void handleMouseDown (long host, int index, float x, float y, long time);
  478. private native void handleMouseDrag (long host, int index, float x, float y, long time);
  479. private native void handleMouseUp (long host, int index, float x, float y, long time);
  480. @Override
  481. public boolean onTouchEvent (MotionEvent event)
  482. {
  483. int action = event.getAction();
  484. long time = event.getEventTime();
  485. switch (action & MotionEvent.ACTION_MASK)
  486. {
  487. case MotionEvent.ACTION_DOWN:
  488. handleMouseDown (host, event.getPointerId(0), event.getX(), event.getY(), time);
  489. return true;
  490. case MotionEvent.ACTION_CANCEL:
  491. case MotionEvent.ACTION_UP:
  492. handleMouseUp (host, event.getPointerId(0), event.getX(), event.getY(), time);
  493. return true;
  494. case MotionEvent.ACTION_MOVE:
  495. {
  496. int n = event.getPointerCount();
  497. for (int i = 0; i < n; ++i)
  498. handleMouseDrag (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  499. return true;
  500. }
  501. case MotionEvent.ACTION_POINTER_UP:
  502. {
  503. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  504. handleMouseUp (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  505. return true;
  506. }
  507. case MotionEvent.ACTION_POINTER_DOWN:
  508. {
  509. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  510. handleMouseDown (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  511. return true;
  512. }
  513. default:
  514. break;
  515. }
  516. return false;
  517. }
  518. //==============================================================================
  519. private native void handleKeyDown (long host, int keycode, int textchar);
  520. private native void handleKeyUp (long host, int keycode, int textchar);
  521. private native void handleBackButton (long host);
  522. public void showKeyboard (String type)
  523. {
  524. InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
  525. if (imm != null)
  526. {
  527. if (type.length() > 0)
  528. {
  529. imm.showSoftInput (this, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
  530. imm.setInputMethod (getWindowToken(), type);
  531. }
  532. else
  533. {
  534. imm.hideSoftInputFromWindow (getWindowToken(), 0);
  535. }
  536. }
  537. }
  538. @Override
  539. public boolean onKeyDown (int keyCode, KeyEvent event)
  540. {
  541. switch (keyCode)
  542. {
  543. case KeyEvent.KEYCODE_VOLUME_UP:
  544. case KeyEvent.KEYCODE_VOLUME_DOWN:
  545. return super.onKeyDown (keyCode, event);
  546. case KeyEvent.KEYCODE_BACK:
  547. {
  548. handleBackButton (host);
  549. return true;
  550. }
  551. default:
  552. break;
  553. }
  554. handleKeyDown (host, keyCode, event.getUnicodeChar());
  555. return true;
  556. }
  557. @Override
  558. public boolean onKeyUp (int keyCode, KeyEvent event)
  559. {
  560. handleKeyUp (host, keyCode, event.getUnicodeChar());
  561. return true;
  562. }
  563. @Override
  564. public boolean onKeyMultiple (int keyCode, int count, KeyEvent event)
  565. {
  566. if (keyCode != KeyEvent.KEYCODE_UNKNOWN || event.getAction() != KeyEvent.ACTION_MULTIPLE)
  567. return super.onKeyMultiple (keyCode, count, event);
  568. if (event.getCharacters() != null)
  569. {
  570. int utf8Char = event.getCharacters().codePointAt (0);
  571. handleKeyDown (host, utf8Char, utf8Char);
  572. return true;
  573. }
  574. return false;
  575. }
  576. // this is here to make keyboard entry work on a Galaxy Tab2 10.1
  577. @Override
  578. public InputConnection onCreateInputConnection (EditorInfo outAttrs)
  579. {
  580. outAttrs.actionLabel = "";
  581. outAttrs.hintText = "";
  582. outAttrs.initialCapsMode = 0;
  583. outAttrs.initialSelEnd = outAttrs.initialSelStart = -1;
  584. outAttrs.label = "";
  585. outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
  586. outAttrs.inputType = InputType.TYPE_NULL;
  587. return new BaseInputConnection (this, false);
  588. }
  589. //==============================================================================
  590. @Override
  591. protected void onSizeChanged (int w, int h, int oldw, int oldh)
  592. {
  593. super.onSizeChanged (w, h, oldw, oldh);
  594. viewSizeChanged (host);
  595. }
  596. @Override
  597. protected void onLayout (boolean changed, int left, int top, int right, int bottom)
  598. {
  599. for (int i = getChildCount(); --i >= 0;)
  600. requestTransparentRegion (getChildAt (i));
  601. }
  602. private native void viewSizeChanged (long host);
  603. @Override
  604. public void onFocusChange (View v, boolean hasFocus)
  605. {
  606. if (v == this)
  607. focusChanged (host, hasFocus);
  608. }
  609. private native void focusChanged (long host, boolean hasFocus);
  610. public void setViewName (String newName) {}
  611. public void setSystemUiVisibilityCompat (int visibility)
  612. {
  613. Method systemUIVisibilityMethod = null;
  614. try
  615. {
  616. systemUIVisibilityMethod = this.getClass().getMethod ("setSystemUiVisibility", int.class);
  617. }
  618. catch (SecurityException e) { return; }
  619. catch (NoSuchMethodException e) { return; }
  620. if (systemUIVisibilityMethod == null) return;
  621. try
  622. {
  623. systemUIVisibilityMethod.invoke (this, visibility);
  624. }
  625. catch (java.lang.IllegalArgumentException e) {}
  626. catch (java.lang.IllegalAccessException e) {}
  627. catch (java.lang.reflect.InvocationTargetException e) {}
  628. }
  629. public boolean isVisible() { return getVisibility() == VISIBLE; }
  630. public void setVisible (boolean b) { setVisibility (b ? VISIBLE : INVISIBLE); }
  631. public boolean containsPoint (int x, int y)
  632. {
  633. return true; //xxx needs to check overlapping views
  634. }
  635. }
  636. //==============================================================================
  637. public static class NativeSurfaceView extends SurfaceView
  638. implements SurfaceHolder.Callback
  639. {
  640. private long nativeContext = 0;
  641. NativeSurfaceView (Context context, long nativeContextPtr)
  642. {
  643. super (context);
  644. nativeContext = nativeContextPtr;
  645. }
  646. public Surface getNativeSurface()
  647. {
  648. Surface retval = null;
  649. SurfaceHolder holder = getHolder();
  650. if (holder != null)
  651. retval = holder.getSurface();
  652. return retval;
  653. }
  654. //==============================================================================
  655. @Override
  656. public void surfaceChanged (SurfaceHolder holder, int format, int width, int height)
  657. {
  658. surfaceChangedNative (nativeContext, holder, format, width, height);
  659. }
  660. @Override
  661. public void surfaceCreated (SurfaceHolder holder)
  662. {
  663. surfaceCreatedNative (nativeContext, holder);
  664. }
  665. @Override
  666. public void surfaceDestroyed (SurfaceHolder holder)
  667. {
  668. surfaceDestroyedNative (nativeContext, holder);
  669. }
  670. @Override
  671. protected void dispatchDraw (Canvas canvas)
  672. {
  673. super.dispatchDraw (canvas);
  674. dispatchDrawNative (nativeContext, canvas);
  675. }
  676. //==============================================================================
  677. @Override
  678. protected void onAttachedToWindow ()
  679. {
  680. super.onAttachedToWindow();
  681. getHolder().addCallback (this);
  682. }
  683. @Override
  684. protected void onDetachedFromWindow ()
  685. {
  686. super.onDetachedFromWindow();
  687. getHolder().removeCallback (this);
  688. }
  689. //==============================================================================
  690. private native void dispatchDrawNative (long nativeContextPtr, Canvas canvas);
  691. private native void surfaceCreatedNative (long nativeContextptr, SurfaceHolder holder);
  692. private native void surfaceDestroyedNative (long nativeContextptr, SurfaceHolder holder);
  693. private native void surfaceChangedNative (long nativeContextptr, SurfaceHolder holder,
  694. int format, int width, int height);
  695. }
  696. public NativeSurfaceView createNativeSurfaceView (long nativeSurfacePtr)
  697. {
  698. return new NativeSurfaceView (this, nativeSurfacePtr);
  699. }
  700. //==============================================================================
  701. public final int[] renderGlyph (char glyph1, char glyph2, Paint paint, android.graphics.Matrix matrix, Rect bounds)
  702. {
  703. Path p = new Path();
  704. char[] str = { glyph1, glyph2 };
  705. paint.getTextPath (str, 0, (glyph2 != 0 ? 2 : 1), 0.0f, 0.0f, p);
  706. RectF boundsF = new RectF();
  707. p.computeBounds (boundsF, true);
  708. matrix.mapRect (boundsF);
  709. boundsF.roundOut (bounds);
  710. bounds.left--;
  711. bounds.right++;
  712. final int w = bounds.width();
  713. final int h = Math.max (1, bounds.height());
  714. Bitmap bm = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
  715. Canvas c = new Canvas (bm);
  716. matrix.postTranslate (-bounds.left, -bounds.top);
  717. c.setMatrix (matrix);
  718. c.drawPath (p, paint);
  719. final int sizeNeeded = w * h;
  720. if (cachedRenderArray.length < sizeNeeded)
  721. cachedRenderArray = new int [sizeNeeded];
  722. bm.getPixels (cachedRenderArray, 0, w, 0, 0, w, h);
  723. bm.recycle();
  724. return cachedRenderArray;
  725. }
  726. private int[] cachedRenderArray = new int [256];
  727. //==============================================================================
  728. public static class NativeInvocationHandler implements InvocationHandler
  729. {
  730. public NativeInvocationHandler (long nativeContextRef)
  731. {
  732. nativeContext = nativeContextRef;
  733. }
  734. @Override
  735. public void finalize()
  736. {
  737. dispatchFinalize (nativeContext);
  738. }
  739. @Override
  740. public Object invoke (Object proxy, Method method, Object[] args) throws Throwable
  741. {
  742. return dispatchInvoke (nativeContext, proxy, method, args);
  743. }
  744. //==============================================================================
  745. private long nativeContext = 0;
  746. private native void dispatchFinalize (long nativeContextRef);
  747. private native Object dispatchInvoke (long nativeContextRef, Object proxy, Method method, Object[] args);
  748. }
  749. public static InvocationHandler createInvocationHandler (long nativeContextRef)
  750. {
  751. return new NativeInvocationHandler (nativeContextRef);
  752. }
  753. //==============================================================================
  754. public static class HTTPStream
  755. {
  756. public HTTPStream (HttpURLConnection connection_,
  757. int[] statusCode_,
  758. StringBuffer responseHeaders_)
  759. {
  760. connection = connection_;
  761. statusCode = statusCode_;
  762. responseHeaders = responseHeaders_;
  763. }
  764. private final InputStream getCancellableStream (final boolean isInput) throws ExecutionException
  765. {
  766. synchronized (createFutureLock)
  767. {
  768. if (hasBeenCancelled.get())
  769. return null;
  770. streamFuture = executor.submit (new Callable<BufferedInputStream>()
  771. {
  772. @Override
  773. public BufferedInputStream call() throws IOException
  774. {
  775. return new BufferedInputStream (isInput ? connection.getInputStream()
  776. : connection.getErrorStream());
  777. }
  778. });
  779. }
  780. try
  781. {
  782. if (connection.getConnectTimeout() > 0)
  783. return streamFuture.get (connection.getConnectTimeout(), TimeUnit.MILLISECONDS);
  784. else
  785. return streamFuture.get();
  786. }
  787. catch (InterruptedException e)
  788. {
  789. return null;
  790. }
  791. catch (TimeoutException e)
  792. {
  793. return null;
  794. }
  795. catch (CancellationException e)
  796. {
  797. return null;
  798. }
  799. }
  800. public final boolean connect()
  801. {
  802. try
  803. {
  804. try
  805. {
  806. synchronized (createStreamLock)
  807. {
  808. if (hasBeenCancelled.get())
  809. return false;
  810. inputStream = getCancellableStream (true);
  811. }
  812. }
  813. catch (ExecutionException e)
  814. {
  815. if (connection.getResponseCode() < 400)
  816. {
  817. statusCode[0] = connection.getResponseCode();
  818. connection.disconnect();
  819. return false;
  820. }
  821. }
  822. finally
  823. {
  824. statusCode[0] = connection.getResponseCode();
  825. }
  826. synchronized (createStreamLock)
  827. {
  828. if (hasBeenCancelled.get())
  829. return false;
  830. try
  831. {
  832. if (statusCode[0] >= 400)
  833. inputStream = getCancellableStream (false);
  834. else
  835. inputStream = getCancellableStream (true);
  836. }
  837. catch (ExecutionException e)
  838. {}
  839. }
  840. for (java.util.Map.Entry<String, java.util.List<String>> entry : connection.getHeaderFields().entrySet())
  841. if (entry.getKey() != null && entry.getValue() != null)
  842. responseHeaders.append (entry.getKey() + ": "
  843. + android.text.TextUtils.join (",", entry.getValue()) + "\n");
  844. return true;
  845. }
  846. catch (IOException e)
  847. {
  848. return false;
  849. }
  850. }
  851. public final void release()
  852. {
  853. hasBeenCancelled.set (true);
  854. try
  855. {
  856. if (! createStreamLock.tryLock())
  857. {
  858. synchronized (createFutureLock)
  859. {
  860. if (streamFuture != null)
  861. streamFuture.cancel (true);
  862. }
  863. createStreamLock.lock();
  864. }
  865. if (inputStream != null)
  866. inputStream.close();
  867. }
  868. catch (IOException e)
  869. {}
  870. finally
  871. {
  872. createStreamLock.unlock();
  873. }
  874. connection.disconnect();
  875. }
  876. public final int read (byte[] buffer, int numBytes)
  877. {
  878. int num = 0;
  879. try
  880. {
  881. synchronized (createStreamLock)
  882. {
  883. if (inputStream != null)
  884. num = inputStream.read (buffer, 0, numBytes);
  885. }
  886. }
  887. catch (IOException e)
  888. {}
  889. if (num > 0)
  890. position += num;
  891. return num;
  892. }
  893. public final long getPosition() { return position; }
  894. public final long getTotalLength() { return -1; }
  895. public final boolean isExhausted() { return false; }
  896. public final boolean setPosition (long newPos) { return false; }
  897. private HttpURLConnection connection;
  898. private int[] statusCode;
  899. private StringBuffer responseHeaders;
  900. private InputStream inputStream;
  901. private long position;
  902. private final ReentrantLock createStreamLock = new ReentrantLock();
  903. private final Object createFutureLock = new Object();
  904. private AtomicBoolean hasBeenCancelled = new AtomicBoolean();
  905. private final ExecutorService executor = Executors.newCachedThreadPool (Executors.defaultThreadFactory());
  906. Future<BufferedInputStream> streamFuture;
  907. }
  908. public static final HTTPStream createHTTPStream (String address, boolean isPost, byte[] postData,
  909. String headers, int timeOutMs, int[] statusCode,
  910. StringBuffer responseHeaders, int numRedirectsToFollow,
  911. String httpRequestCmd)
  912. {
  913. // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL)
  914. if (timeOutMs < 0)
  915. timeOutMs = 0;
  916. else if (timeOutMs == 0)
  917. timeOutMs = 30000;
  918. // 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.
  919. // So convert headers string to an array, with an element for each line
  920. String headerLines[] = headers.split("\\n");
  921. for (;;)
  922. {
  923. try
  924. {
  925. HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());
  926. if (connection != null)
  927. {
  928. try
  929. {
  930. connection.setInstanceFollowRedirects (false);
  931. connection.setConnectTimeout (timeOutMs);
  932. connection.setReadTimeout (timeOutMs);
  933. // Set request headers
  934. for (int i = 0; i < headerLines.length; ++i)
  935. {
  936. int pos = headerLines[i].indexOf (":");
  937. if (pos > 0 && pos < headerLines[i].length())
  938. {
  939. String field = headerLines[i].substring (0, pos);
  940. String value = headerLines[i].substring (pos + 1);
  941. if (value.length() > 0)
  942. connection.setRequestProperty (field, value);
  943. }
  944. }
  945. connection.setRequestMethod (httpRequestCmd);
  946. if (isPost)
  947. {
  948. connection.setDoOutput (true);
  949. if (postData != null)
  950. {
  951. OutputStream out = connection.getOutputStream();
  952. out.write(postData);
  953. out.flush();
  954. }
  955. }
  956. HTTPStream httpStream = new HTTPStream (connection, statusCode, responseHeaders);
  957. // Process redirect & continue as necessary
  958. int status = statusCode[0];
  959. if (--numRedirectsToFollow >= 0
  960. && (status == 301 || status == 302 || status == 303 || status == 307))
  961. {
  962. // Assumes only one occurrence of "Location"
  963. int pos1 = responseHeaders.indexOf ("Location:") + 10;
  964. int pos2 = responseHeaders.indexOf ("\n", pos1);
  965. if (pos2 > pos1)
  966. {
  967. String newLocation = responseHeaders.substring(pos1, pos2);
  968. // Handle newLocation whether it's absolute or relative
  969. URL baseUrl = new URL (address);
  970. URL newUrl = new URL (baseUrl, newLocation);
  971. String transformedNewLocation = newUrl.toString();
  972. if (transformedNewLocation != address)
  973. {
  974. address = transformedNewLocation;
  975. // Clear responseHeaders before next iteration
  976. responseHeaders.delete (0, responseHeaders.length());
  977. continue;
  978. }
  979. }
  980. }
  981. return httpStream;
  982. }
  983. catch (Throwable e)
  984. {
  985. connection.disconnect();
  986. }
  987. }
  988. }
  989. catch (Throwable e) {}
  990. return null;
  991. }
  992. }
  993. public final void launchURL (String url)
  994. {
  995. startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse (url)));
  996. }
  997. public static final String getLocaleValue (boolean isRegion)
  998. {
  999. java.util.Locale locale = java.util.Locale.getDefault();
  1000. return isRegion ? locale.getCountry()
  1001. : locale.getLanguage();
  1002. }
  1003. private static final String getFileLocation (String type)
  1004. {
  1005. return Environment.getExternalStoragePublicDirectory (type).getAbsolutePath();
  1006. }
  1007. public static final String getDocumentsFolder() { return Environment.getDataDirectory().getAbsolutePath(); }
  1008. public static final String getPicturesFolder() { return getFileLocation (Environment.DIRECTORY_PICTURES); }
  1009. public static final String getMusicFolder() { return getFileLocation (Environment.DIRECTORY_MUSIC); }
  1010. public static final String getMoviesFolder() { return getFileLocation (Environment.DIRECTORY_MOVIES); }
  1011. public static final String getDownloadsFolder() { return getFileLocation (Environment.DIRECTORY_DOWNLOADS); }
  1012. //==============================================================================
  1013. public final Typeface getTypeFaceFromAsset (String assetName)
  1014. {
  1015. try
  1016. {
  1017. return Typeface.createFromAsset (this.getResources().getAssets(), assetName);
  1018. }
  1019. catch (Throwable e) {}
  1020. return null;
  1021. }
  1022. final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
  1023. public static String bytesToHex (byte[] bytes)
  1024. {
  1025. char[] hexChars = new char[bytes.length * 2];
  1026. for (int j = 0; j < bytes.length; ++j)
  1027. {
  1028. int v = bytes[j] & 0xff;
  1029. hexChars[j * 2] = hexArray[v >>> 4];
  1030. hexChars[j * 2 + 1] = hexArray[v & 0x0f];
  1031. }
  1032. return new String (hexChars);
  1033. }
  1034. final private java.util.Map dataCache = new java.util.HashMap();
  1035. synchronized private final File getDataCacheFile (byte[] data)
  1036. {
  1037. try
  1038. {
  1039. java.security.MessageDigest digest = java.security.MessageDigest.getInstance ("MD5");
  1040. digest.update (data);
  1041. String key = bytesToHex (digest.digest());
  1042. if (dataCache.containsKey (key))
  1043. return (File) dataCache.get (key);
  1044. File f = new File (this.getCacheDir(), "bindata_" + key);
  1045. f.delete();
  1046. FileOutputStream os = new FileOutputStream (f);
  1047. os.write (data, 0, data.length);
  1048. dataCache.put (key, f);
  1049. return f;
  1050. }
  1051. catch (Throwable e) {}
  1052. return null;
  1053. }
  1054. private final void clearDataCache()
  1055. {
  1056. java.util.Iterator it = dataCache.values().iterator();
  1057. while (it.hasNext())
  1058. {
  1059. File f = (File) it.next();
  1060. f.delete();
  1061. }
  1062. }
  1063. public final Typeface getTypeFaceFromByteArray (byte[] data)
  1064. {
  1065. try
  1066. {
  1067. File f = getDataCacheFile (data);
  1068. if (f != null)
  1069. return Typeface.createFromFile (f);
  1070. }
  1071. catch (Exception e)
  1072. {
  1073. Log.e ("JUCE", e.toString());
  1074. }
  1075. return null;
  1076. }
  1077. public final int getAndroidSDKVersion()
  1078. {
  1079. return android.os.Build.VERSION.SDK_INT;
  1080. }
  1081. public final String audioManagerGetProperty (String property)
  1082. {
  1083. Object obj = getSystemService (AUDIO_SERVICE);
  1084. if (obj == null)
  1085. return null;
  1086. java.lang.reflect.Method method;
  1087. try
  1088. {
  1089. method = obj.getClass().getMethod ("getProperty", String.class);
  1090. }
  1091. catch (SecurityException e) { return null; }
  1092. catch (NoSuchMethodException e) { return null; }
  1093. if (method == null)
  1094. return null;
  1095. try
  1096. {
  1097. return (String) method.invoke (obj, property);
  1098. }
  1099. catch (java.lang.IllegalArgumentException e) {}
  1100. catch (java.lang.IllegalAccessException e) {}
  1101. catch (java.lang.reflect.InvocationTargetException e) {}
  1102. return null;
  1103. }
  1104. public final boolean hasSystemFeature (String property)
  1105. {
  1106. return getPackageManager().hasSystemFeature (property);
  1107. }
  1108. }