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.

1338 lines
47KB

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