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.

1502 lines
53KB

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