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.

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