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.

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