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.

1215 lines
43KB

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