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.

1275 lines
44KB

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