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.

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