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.

1637 lines
58KB

  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.http.SslError;
  27. import android.net.Uri;
  28. import android.os.Bundle;
  29. import android.os.Looper;
  30. import android.os.Handler;
  31. import android.os.Message;
  32. import android.os.ParcelUuid;
  33. import android.os.Environment;
  34. import android.view.*;
  35. import android.view.inputmethod.BaseInputConnection;
  36. import android.view.inputmethod.EditorInfo;
  37. import android.view.inputmethod.InputConnection;
  38. import android.view.inputmethod.InputMethodManager;
  39. import android.graphics.*;
  40. import android.text.ClipboardManager;
  41. import android.text.InputType;
  42. import android.util.DisplayMetrics;
  43. import android.util.Log;
  44. import android.util.Pair;
  45. import android.webkit.SslErrorHandler;
  46. import android.webkit.WebChromeClient;
  47. $$JuceAndroidWebViewImports$$ // If you get an error here, you need to re-save your project with the Projucer!
  48. import android.webkit.WebView;
  49. import android.webkit.WebViewClient;
  50. import java.lang.Runnable;
  51. import java.lang.ref.WeakReference;
  52. import java.lang.reflect.*;
  53. import java.util.*;
  54. import java.io.*;
  55. import java.net.URL;
  56. import java.net.HttpURLConnection;
  57. import android.media.AudioManager;
  58. import android.Manifest;
  59. import java.util.concurrent.CancellationException;
  60. import java.util.concurrent.Future;
  61. import java.util.concurrent.Executors;
  62. import java.util.concurrent.ExecutorService;
  63. import java.util.concurrent.ExecutionException;
  64. import java.util.concurrent.TimeUnit;
  65. import java.util.concurrent.Callable;
  66. import java.util.concurrent.TimeoutException;
  67. import java.util.concurrent.locks.ReentrantLock;
  68. import java.util.concurrent.atomic.*;
  69. $$JuceAndroidMidiImports$$ // If you get an error here, you need to re-save your project with the Projucer!
  70. //==============================================================================
  71. public class JuceAppActivity extends Activity
  72. {
  73. //==============================================================================
  74. static
  75. {
  76. System.loadLibrary ("juce_jni");
  77. }
  78. //==============================================================================
  79. public boolean isPermissionDeclaredInManifest (int permissionID)
  80. {
  81. String permissionToCheck = getAndroidPermissionName(permissionID);
  82. try
  83. {
  84. PackageInfo info = getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
  85. if (info.requestedPermissions != null)
  86. for (String permission : info.requestedPermissions)
  87. if (permission.equals (permissionToCheck))
  88. return true;
  89. }
  90. catch (PackageManager.NameNotFoundException e)
  91. {
  92. Log.d ("JUCE", "isPermissionDeclaredInManifest: PackageManager.NameNotFoundException = " + e.toString());
  93. }
  94. Log.d ("JUCE", "isPermissionDeclaredInManifest: could not find requested permission " + permissionToCheck);
  95. return false;
  96. }
  97. //==============================================================================
  98. // these have to match the values of enum PermissionID in C++ class RuntimePermissions:
  99. private static final int JUCE_PERMISSIONS_RECORD_AUDIO = 1;
  100. private static final int JUCE_PERMISSIONS_BLUETOOTH_MIDI = 2;
  101. private static final int JUCE_PERMISSIONS_READ_EXTERNAL_STORAGE = 3;
  102. private static final int JUCE_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 4;
  103. private static String getAndroidPermissionName (int permissionID)
  104. {
  105. switch (permissionID)
  106. {
  107. case JUCE_PERMISSIONS_RECORD_AUDIO: return Manifest.permission.RECORD_AUDIO;
  108. case JUCE_PERMISSIONS_BLUETOOTH_MIDI: return Manifest.permission.ACCESS_COARSE_LOCATION;
  109. // use string value as this is not defined in SDKs < 16
  110. case JUCE_PERMISSIONS_READ_EXTERNAL_STORAGE: return "android.permission.READ_EXTERNAL_STORAGE";
  111. case JUCE_PERMISSIONS_WRITE_EXTERNAL_STORAGE: return Manifest.permission.WRITE_EXTERNAL_STORAGE;
  112. }
  113. // unknown permission ID!
  114. assert false;
  115. return new String();
  116. }
  117. public boolean isPermissionGranted (int permissionID)
  118. {
  119. return getApplicationContext().checkCallingOrSelfPermission (getAndroidPermissionName (permissionID)) == PackageManager.PERMISSION_GRANTED;
  120. }
  121. private Map<Integer, Long> permissionCallbackPtrMap;
  122. public void requestRuntimePermission (int permissionID, long ptrToCallback)
  123. {
  124. String permissionName = getAndroidPermissionName (permissionID);
  125. if (getApplicationContext().checkCallingOrSelfPermission (permissionName) != PackageManager.PERMISSION_GRANTED)
  126. {
  127. // remember callbackPtr, request permissions, and let onRequestPermissionResult call callback asynchronously
  128. permissionCallbackPtrMap.put (permissionID, ptrToCallback);
  129. requestPermissionsCompat (new String[]{permissionName}, permissionID);
  130. }
  131. else
  132. {
  133. // permissions were already granted before, we can call callback directly
  134. androidRuntimePermissionsCallback (true, ptrToCallback);
  135. }
  136. }
  137. private native void androidRuntimePermissionsCallback (boolean permissionWasGranted, long ptrToCallback);
  138. $$JuceAndroidRuntimePermissionsCode$$ // If you get an error here, you need to re-save your project with the Projucer!
  139. //==============================================================================
  140. public interface JuceMidiPort
  141. {
  142. boolean isInputPort();
  143. // start, stop does nothing on an output port
  144. void start();
  145. void stop();
  146. void close();
  147. // send will do nothing on an input port
  148. void sendMidi (byte[] msg, int offset, int count);
  149. }
  150. //==============================================================================
  151. $$JuceAndroidMidiCode$$ // If you get an error here, you need to re-save your project with the Projucer!
  152. //==============================================================================
  153. @Override
  154. public void onCreate (Bundle savedInstanceState)
  155. {
  156. super.onCreate (savedInstanceState);
  157. isScreenSaverEnabled = true;
  158. hideActionBar();
  159. viewHolder = new ViewHolder (this);
  160. setContentView (viewHolder);
  161. setVolumeControlStream (AudioManager.STREAM_MUSIC);
  162. permissionCallbackPtrMap = new HashMap<Integer, Long>();
  163. }
  164. @Override
  165. protected void onDestroy()
  166. {
  167. quitApp();
  168. super.onDestroy();
  169. clearDataCache();
  170. }
  171. @Override
  172. protected void onPause()
  173. {
  174. suspendApp();
  175. try
  176. {
  177. Thread.sleep (1000); // This is a bit of a hack to avoid some hard-to-track-down
  178. // openGL glitches when pausing/resuming apps..
  179. } catch (InterruptedException e) {}
  180. super.onPause();
  181. }
  182. @Override
  183. protected void onResume()
  184. {
  185. super.onResume();
  186. resumeApp();
  187. // Ensure that navigation/status bar visibility is correctly restored.
  188. for (int i = 0; i < viewHolder.getChildCount(); ++i)
  189. ((ComponentPeerView) viewHolder.getChildAt (i)).appResumed();
  190. }
  191. @Override
  192. public void onConfigurationChanged (Configuration cfg)
  193. {
  194. super.onConfigurationChanged (cfg);
  195. setContentView (viewHolder);
  196. }
  197. private void callAppLauncher()
  198. {
  199. launchApp (getApplicationInfo().publicSourceDir,
  200. getApplicationInfo().dataDir);
  201. }
  202. //==============================================================================
  203. private void hideActionBar()
  204. {
  205. // get "getActionBar" method
  206. java.lang.reflect.Method getActionBarMethod = null;
  207. try
  208. {
  209. getActionBarMethod = this.getClass().getMethod ("getActionBar");
  210. }
  211. catch (SecurityException e) { return; }
  212. catch (NoSuchMethodException e) { return; }
  213. if (getActionBarMethod == null) return;
  214. // invoke "getActionBar" method
  215. Object actionBar = null;
  216. try
  217. {
  218. actionBar = getActionBarMethod.invoke (this);
  219. }
  220. catch (java.lang.IllegalArgumentException e) { return; }
  221. catch (java.lang.IllegalAccessException e) { return; }
  222. catch (java.lang.reflect.InvocationTargetException e) { return; }
  223. if (actionBar == null) return;
  224. // get "hide" method
  225. java.lang.reflect.Method actionBarHideMethod = null;
  226. try
  227. {
  228. actionBarHideMethod = actionBar.getClass().getMethod ("hide");
  229. }
  230. catch (SecurityException e) { return; }
  231. catch (NoSuchMethodException e) { return; }
  232. if (actionBarHideMethod == null) return;
  233. // invoke "hide" method
  234. try
  235. {
  236. actionBarHideMethod.invoke (actionBar);
  237. }
  238. catch (java.lang.IllegalArgumentException e) {}
  239. catch (java.lang.IllegalAccessException e) {}
  240. catch (java.lang.reflect.InvocationTargetException e) {}
  241. }
  242. void requestPermissionsCompat (String[] permissions, int requestCode)
  243. {
  244. Method requestPermissionsMethod = null;
  245. try
  246. {
  247. requestPermissionsMethod = this.getClass().getMethod ("requestPermissions",
  248. String[].class, int.class);
  249. }
  250. catch (SecurityException e) { return; }
  251. catch (NoSuchMethodException e) { return; }
  252. if (requestPermissionsMethod == null) return;
  253. try
  254. {
  255. requestPermissionsMethod.invoke (this, permissions, requestCode);
  256. }
  257. catch (java.lang.IllegalArgumentException e) {}
  258. catch (java.lang.IllegalAccessException e) {}
  259. catch (java.lang.reflect.InvocationTargetException e) {}
  260. }
  261. //==============================================================================
  262. private native void launchApp (String appFile, String appDataDir);
  263. private native void quitApp();
  264. private native void suspendApp();
  265. private native void resumeApp();
  266. private native void setScreenSize (int screenWidth, int screenHeight, int dpi);
  267. private native void appActivityResult (int requestCode, int resultCode, Intent data);
  268. private native void appNewIntent (Intent intent);
  269. //==============================================================================
  270. private ViewHolder viewHolder;
  271. private MidiDeviceManager midiDeviceManager = null;
  272. private BluetoothManager bluetoothManager = null;
  273. private boolean isScreenSaverEnabled;
  274. private java.util.Timer keepAliveTimer;
  275. public final ComponentPeerView createNewView (boolean opaque, long host)
  276. {
  277. ComponentPeerView v = new ComponentPeerView (this, opaque, host);
  278. viewHolder.addView (v);
  279. return v;
  280. }
  281. public final void deleteView (ComponentPeerView view)
  282. {
  283. view.host = 0;
  284. ViewGroup group = (ViewGroup) (view.getParent());
  285. if (group != null)
  286. group.removeView (view);
  287. }
  288. public final void deleteNativeSurfaceView (NativeSurfaceView view)
  289. {
  290. ViewGroup group = (ViewGroup) (view.getParent());
  291. if (group != null)
  292. group.removeView (view);
  293. }
  294. final class ViewHolder extends ViewGroup
  295. {
  296. public ViewHolder (Context context)
  297. {
  298. super (context);
  299. setDescendantFocusability (ViewGroup.FOCUS_AFTER_DESCENDANTS);
  300. setFocusable (false);
  301. }
  302. protected final void onLayout (boolean changed, int left, int top, int right, int bottom)
  303. {
  304. setScreenSize (getWidth(), getHeight(), getDPI());
  305. if (isFirstResize)
  306. {
  307. isFirstResize = false;
  308. callAppLauncher();
  309. }
  310. }
  311. private final int getDPI()
  312. {
  313. DisplayMetrics metrics = new DisplayMetrics();
  314. getWindowManager().getDefaultDisplay().getMetrics (metrics);
  315. return metrics.densityDpi;
  316. }
  317. private boolean isFirstResize = true;
  318. }
  319. public final void excludeClipRegion (android.graphics.Canvas canvas, float left, float top, float right, float bottom)
  320. {
  321. canvas.clipRect (left, top, right, bottom, android.graphics.Region.Op.DIFFERENCE);
  322. }
  323. //==============================================================================
  324. public final void setScreenSaver (boolean enabled)
  325. {
  326. if (isScreenSaverEnabled != enabled)
  327. {
  328. isScreenSaverEnabled = enabled;
  329. if (keepAliveTimer != null)
  330. {
  331. keepAliveTimer.cancel();
  332. keepAliveTimer = null;
  333. }
  334. if (enabled)
  335. {
  336. getWindow().clearFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  337. }
  338. else
  339. {
  340. getWindow().addFlags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  341. // If no user input is received after about 3 seconds, the OS will lower the
  342. // task's priority, so this timer forces it to be kept active.
  343. keepAliveTimer = new java.util.Timer();
  344. keepAliveTimer.scheduleAtFixedRate (new TimerTask()
  345. {
  346. @Override
  347. public void run()
  348. {
  349. android.app.Instrumentation instrumentation = new android.app.Instrumentation();
  350. try
  351. {
  352. instrumentation.sendKeyDownUpSync (KeyEvent.KEYCODE_UNKNOWN);
  353. }
  354. catch (Exception e)
  355. {
  356. }
  357. }
  358. }, 2000, 2000);
  359. }
  360. }
  361. }
  362. public final boolean getScreenSaver()
  363. {
  364. return isScreenSaverEnabled;
  365. }
  366. //==============================================================================
  367. public final String getClipboardContent()
  368. {
  369. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  370. return clipboard.getText().toString();
  371. }
  372. public final void setClipboardContent (String newText)
  373. {
  374. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  375. clipboard.setText (newText);
  376. }
  377. //==============================================================================
  378. public final void showMessageBox (String title, String message, final long callback)
  379. {
  380. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  381. builder.setTitle (title)
  382. .setMessage (message)
  383. .setCancelable (true)
  384. .setOnCancelListener (new DialogInterface.OnCancelListener()
  385. {
  386. public void onCancel (DialogInterface dialog)
  387. {
  388. JuceAppActivity.this.alertDismissed (callback, 0);
  389. }
  390. })
  391. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  392. {
  393. public void onClick (DialogInterface dialog, int id)
  394. {
  395. dialog.dismiss();
  396. JuceAppActivity.this.alertDismissed (callback, 0);
  397. }
  398. });
  399. builder.create().show();
  400. }
  401. public final void showOkCancelBox (String title, String message, final long callback,
  402. String okButtonText, String cancelButtonText)
  403. {
  404. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  405. builder.setTitle (title)
  406. .setMessage (message)
  407. .setCancelable (true)
  408. .setOnCancelListener (new DialogInterface.OnCancelListener()
  409. {
  410. public void onCancel (DialogInterface dialog)
  411. {
  412. JuceAppActivity.this.alertDismissed (callback, 0);
  413. }
  414. })
  415. .setPositiveButton (okButtonText.isEmpty() ? "OK" : okButtonText, new DialogInterface.OnClickListener()
  416. {
  417. public void onClick (DialogInterface dialog, int id)
  418. {
  419. dialog.dismiss();
  420. JuceAppActivity.this.alertDismissed (callback, 1);
  421. }
  422. })
  423. .setNegativeButton (cancelButtonText.isEmpty() ? "Cancel" : cancelButtonText, new DialogInterface.OnClickListener()
  424. {
  425. public void onClick (DialogInterface dialog, int id)
  426. {
  427. dialog.dismiss();
  428. JuceAppActivity.this.alertDismissed (callback, 0);
  429. }
  430. });
  431. builder.create().show();
  432. }
  433. public final void showYesNoCancelBox (String title, String message, final long callback)
  434. {
  435. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  436. builder.setTitle (title)
  437. .setMessage (message)
  438. .setCancelable (true)
  439. .setOnCancelListener (new DialogInterface.OnCancelListener()
  440. {
  441. public void onCancel (DialogInterface dialog)
  442. {
  443. JuceAppActivity.this.alertDismissed (callback, 0);
  444. }
  445. })
  446. .setPositiveButton ("Yes", new DialogInterface.OnClickListener()
  447. {
  448. public void onClick (DialogInterface dialog, int id)
  449. {
  450. dialog.dismiss();
  451. JuceAppActivity.this.alertDismissed (callback, 1);
  452. }
  453. })
  454. .setNegativeButton ("No", new DialogInterface.OnClickListener()
  455. {
  456. public void onClick (DialogInterface dialog, int id)
  457. {
  458. dialog.dismiss();
  459. JuceAppActivity.this.alertDismissed (callback, 2);
  460. }
  461. })
  462. .setNeutralButton ("Cancel", new DialogInterface.OnClickListener()
  463. {
  464. public void onClick (DialogInterface dialog, int id)
  465. {
  466. dialog.dismiss();
  467. JuceAppActivity.this.alertDismissed (callback, 0);
  468. }
  469. });
  470. builder.create().show();
  471. }
  472. public native void alertDismissed (long callback, int id);
  473. //==============================================================================
  474. public final class ComponentPeerView extends ViewGroup
  475. implements View.OnFocusChangeListener
  476. {
  477. public ComponentPeerView (Context context, boolean opaque_, long host)
  478. {
  479. super (context);
  480. this.host = host;
  481. setWillNotDraw (false);
  482. opaque = opaque_;
  483. setFocusable (true);
  484. setFocusableInTouchMode (true);
  485. setOnFocusChangeListener (this);
  486. // swap red and blue colours to match internal opengl texture format
  487. ColorMatrix colorMatrix = new ColorMatrix();
  488. float[] colorTransform = { 0, 0, 1.0f, 0, 0,
  489. 0, 1.0f, 0, 0, 0,
  490. 1.0f, 0, 0, 0, 0,
  491. 0, 0, 0, 1.0f, 0 };
  492. colorMatrix.set (colorTransform);
  493. paint.setColorFilter (new ColorMatrixColorFilter (colorMatrix));
  494. java.lang.reflect.Method method = null;
  495. try
  496. {
  497. method = getClass().getMethod ("setLayerType", int.class, Paint.class);
  498. }
  499. catch (SecurityException e) {}
  500. catch (NoSuchMethodException e) {}
  501. if (method != null)
  502. {
  503. try
  504. {
  505. int layerTypeNone = 0;
  506. method.invoke (this, layerTypeNone, null);
  507. }
  508. catch (java.lang.IllegalArgumentException e) {}
  509. catch (java.lang.IllegalAccessException e) {}
  510. catch (java.lang.reflect.InvocationTargetException e) {}
  511. }
  512. }
  513. //==============================================================================
  514. private native void handlePaint (long host, Canvas canvas, Paint paint);
  515. @Override
  516. public void onDraw (Canvas canvas)
  517. {
  518. if (host == 0)
  519. return;
  520. handlePaint (host, canvas, paint);
  521. }
  522. @Override
  523. public boolean isOpaque()
  524. {
  525. return opaque;
  526. }
  527. private boolean opaque;
  528. private long host;
  529. private Paint paint = new Paint();
  530. //==============================================================================
  531. private native void handleMouseDown (long host, int index, float x, float y, long time);
  532. private native void handleMouseDrag (long host, int index, float x, float y, long time);
  533. private native void handleMouseUp (long host, int index, float x, float y, long time);
  534. @Override
  535. public boolean onTouchEvent (MotionEvent event)
  536. {
  537. if (host == 0)
  538. return false;
  539. int action = event.getAction();
  540. long time = event.getEventTime();
  541. switch (action & MotionEvent.ACTION_MASK)
  542. {
  543. case MotionEvent.ACTION_DOWN:
  544. handleMouseDown (host, event.getPointerId(0), event.getX(), event.getY(), time);
  545. return true;
  546. case MotionEvent.ACTION_CANCEL:
  547. case MotionEvent.ACTION_UP:
  548. handleMouseUp (host, event.getPointerId(0), event.getX(), event.getY(), time);
  549. return true;
  550. case MotionEvent.ACTION_MOVE:
  551. {
  552. int n = event.getPointerCount();
  553. for (int i = 0; i < n; ++i)
  554. handleMouseDrag (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  555. return true;
  556. }
  557. case MotionEvent.ACTION_POINTER_UP:
  558. {
  559. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  560. handleMouseUp (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  561. return true;
  562. }
  563. case MotionEvent.ACTION_POINTER_DOWN:
  564. {
  565. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  566. handleMouseDown (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  567. return true;
  568. }
  569. default:
  570. break;
  571. }
  572. return false;
  573. }
  574. //==============================================================================
  575. private native void handleKeyDown (long host, int keycode, int textchar);
  576. private native void handleKeyUp (long host, int keycode, int textchar);
  577. private native void handleBackButton (long host);
  578. public void showKeyboard (String type)
  579. {
  580. InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
  581. if (imm != null)
  582. {
  583. if (type.length() > 0)
  584. {
  585. imm.showSoftInput (this, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
  586. imm.setInputMethod (getWindowToken(), type);
  587. }
  588. else
  589. {
  590. imm.hideSoftInputFromWindow (getWindowToken(), 0);
  591. }
  592. }
  593. }
  594. @Override
  595. public boolean onKeyDown (int keyCode, KeyEvent event)
  596. {
  597. if (host == 0)
  598. return false;
  599. switch (keyCode)
  600. {
  601. case KeyEvent.KEYCODE_VOLUME_UP:
  602. case KeyEvent.KEYCODE_VOLUME_DOWN:
  603. return super.onKeyDown (keyCode, event);
  604. case KeyEvent.KEYCODE_BACK:
  605. {
  606. handleBackButton (host);
  607. return true;
  608. }
  609. default:
  610. break;
  611. }
  612. handleKeyDown (host, keyCode, event.getUnicodeChar());
  613. return true;
  614. }
  615. @Override
  616. public boolean onKeyUp (int keyCode, KeyEvent event)
  617. {
  618. if (host == 0)
  619. return false;
  620. handleKeyUp (host, keyCode, event.getUnicodeChar());
  621. return true;
  622. }
  623. @Override
  624. public boolean onKeyMultiple (int keyCode, int count, KeyEvent event)
  625. {
  626. if (host == 0)
  627. return false;
  628. if (keyCode != KeyEvent.KEYCODE_UNKNOWN || event.getAction() != KeyEvent.ACTION_MULTIPLE)
  629. return super.onKeyMultiple (keyCode, count, event);
  630. if (event.getCharacters() != null)
  631. {
  632. int utf8Char = event.getCharacters().codePointAt (0);
  633. handleKeyDown (host, utf8Char, utf8Char);
  634. return true;
  635. }
  636. return false;
  637. }
  638. // this is here to make keyboard entry work on a Galaxy Tab2 10.1
  639. @Override
  640. public InputConnection onCreateInputConnection (EditorInfo outAttrs)
  641. {
  642. outAttrs.actionLabel = "";
  643. outAttrs.hintText = "";
  644. outAttrs.initialCapsMode = 0;
  645. outAttrs.initialSelEnd = outAttrs.initialSelStart = -1;
  646. outAttrs.label = "";
  647. outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
  648. outAttrs.inputType = InputType.TYPE_NULL;
  649. return new BaseInputConnection (this, false);
  650. }
  651. //==============================================================================
  652. @Override
  653. protected void onSizeChanged (int w, int h, int oldw, int oldh)
  654. {
  655. if (host == 0)
  656. return;
  657. super.onSizeChanged (w, h, oldw, oldh);
  658. viewSizeChanged (host);
  659. }
  660. @Override
  661. protected void onLayout (boolean changed, int left, int top, int right, int bottom)
  662. {
  663. for (int i = getChildCount(); --i >= 0;)
  664. requestTransparentRegion (getChildAt (i));
  665. }
  666. private native void viewSizeChanged (long host);
  667. @Override
  668. public void onFocusChange (View v, boolean hasFocus)
  669. {
  670. if (host == 0)
  671. return;
  672. if (v == this)
  673. focusChanged (host, hasFocus);
  674. }
  675. private native void focusChanged (long host, boolean hasFocus);
  676. public void setViewName (String newName) {}
  677. public void setSystemUiVisibilityCompat (int visibility)
  678. {
  679. Method systemUIVisibilityMethod = null;
  680. try
  681. {
  682. systemUIVisibilityMethod = this.getClass().getMethod ("setSystemUiVisibility", int.class);
  683. }
  684. catch (SecurityException e) { return; }
  685. catch (NoSuchMethodException e) { return; }
  686. if (systemUIVisibilityMethod == null) return;
  687. try
  688. {
  689. systemUIVisibilityMethod.invoke (this, visibility);
  690. }
  691. catch (java.lang.IllegalArgumentException e) {}
  692. catch (java.lang.IllegalAccessException e) {}
  693. catch (java.lang.reflect.InvocationTargetException e) {}
  694. }
  695. public boolean isVisible() { return getVisibility() == VISIBLE; }
  696. public void setVisible (boolean b) { setVisibility (b ? VISIBLE : INVISIBLE); }
  697. public boolean containsPoint (int x, int y)
  698. {
  699. return true; //xxx needs to check overlapping views
  700. }
  701. //==============================================================================
  702. private native void handleAppResumed (long host);
  703. public void appResumed()
  704. {
  705. if (host == 0)
  706. return;
  707. handleAppResumed (host);
  708. }
  709. }
  710. //==============================================================================
  711. public static class NativeSurfaceView extends SurfaceView
  712. implements SurfaceHolder.Callback
  713. {
  714. private long nativeContext = 0;
  715. NativeSurfaceView (Context context, long nativeContextPtr)
  716. {
  717. super (context);
  718. nativeContext = nativeContextPtr;
  719. }
  720. public Surface getNativeSurface()
  721. {
  722. Surface retval = null;
  723. SurfaceHolder holder = getHolder();
  724. if (holder != null)
  725. retval = holder.getSurface();
  726. return retval;
  727. }
  728. //==============================================================================
  729. @Override
  730. public void surfaceChanged (SurfaceHolder holder, int format, int width, int height)
  731. {
  732. surfaceChangedNative (nativeContext, holder, format, width, height);
  733. }
  734. @Override
  735. public void surfaceCreated (SurfaceHolder holder)
  736. {
  737. surfaceCreatedNative (nativeContext, holder);
  738. }
  739. @Override
  740. public void surfaceDestroyed (SurfaceHolder holder)
  741. {
  742. surfaceDestroyedNative (nativeContext, holder);
  743. }
  744. @Override
  745. protected void dispatchDraw (Canvas canvas)
  746. {
  747. super.dispatchDraw (canvas);
  748. dispatchDrawNative (nativeContext, canvas);
  749. }
  750. //==============================================================================
  751. @Override
  752. protected void onAttachedToWindow ()
  753. {
  754. super.onAttachedToWindow();
  755. getHolder().addCallback (this);
  756. }
  757. @Override
  758. protected void onDetachedFromWindow ()
  759. {
  760. super.onDetachedFromWindow();
  761. getHolder().removeCallback (this);
  762. }
  763. //==============================================================================
  764. private native void dispatchDrawNative (long nativeContextPtr, Canvas canvas);
  765. private native void surfaceCreatedNative (long nativeContextptr, SurfaceHolder holder);
  766. private native void surfaceDestroyedNative (long nativeContextptr, SurfaceHolder holder);
  767. private native void surfaceChangedNative (long nativeContextptr, SurfaceHolder holder,
  768. int format, int width, int height);
  769. }
  770. public NativeSurfaceView createNativeSurfaceView (long nativeSurfacePtr)
  771. {
  772. return new NativeSurfaceView (this, nativeSurfacePtr);
  773. }
  774. //==============================================================================
  775. public final int[] renderGlyph (char glyph1, char glyph2, Paint paint, android.graphics.Matrix matrix, Rect bounds)
  776. {
  777. Path p = new Path();
  778. char[] str = { glyph1, glyph2 };
  779. paint.getTextPath (str, 0, (glyph2 != 0 ? 2 : 1), 0.0f, 0.0f, p);
  780. RectF boundsF = new RectF();
  781. p.computeBounds (boundsF, true);
  782. matrix.mapRect (boundsF);
  783. boundsF.roundOut (bounds);
  784. bounds.left--;
  785. bounds.right++;
  786. final int w = bounds.width();
  787. final int h = Math.max (1, bounds.height());
  788. Bitmap bm = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
  789. Canvas c = new Canvas (bm);
  790. matrix.postTranslate (-bounds.left, -bounds.top);
  791. c.setMatrix (matrix);
  792. c.drawPath (p, paint);
  793. final int sizeNeeded = w * h;
  794. if (cachedRenderArray.length < sizeNeeded)
  795. cachedRenderArray = new int [sizeNeeded];
  796. bm.getPixels (cachedRenderArray, 0, w, 0, 0, w, h);
  797. bm.recycle();
  798. return cachedRenderArray;
  799. }
  800. private int[] cachedRenderArray = new int [256];
  801. //==============================================================================
  802. public static class NativeInvocationHandler implements InvocationHandler
  803. {
  804. public NativeInvocationHandler (Activity activityToUse, long nativeContextRef)
  805. {
  806. activity = activityToUse;
  807. nativeContext = nativeContextRef;
  808. }
  809. public void nativeContextDeleted()
  810. {
  811. nativeContext = 0;
  812. }
  813. @Override
  814. public void finalize()
  815. {
  816. activity.runOnUiThread (new Runnable()
  817. {
  818. @Override
  819. public void run()
  820. {
  821. if (nativeContext != 0)
  822. dispatchFinalize (nativeContext);
  823. }
  824. });
  825. }
  826. @Override
  827. public Object invoke (Object proxy, Method method, Object[] args) throws Throwable
  828. {
  829. return dispatchInvoke (nativeContext, proxy, method, args);
  830. }
  831. //==============================================================================
  832. Activity activity;
  833. private long nativeContext = 0;
  834. private native void dispatchFinalize (long nativeContextRef);
  835. private native Object dispatchInvoke (long nativeContextRef, Object proxy, Method method, Object[] args);
  836. }
  837. public InvocationHandler createInvocationHandler (long nativeContextRef)
  838. {
  839. return new NativeInvocationHandler (this, nativeContextRef);
  840. }
  841. public void invocationHandlerContextDeleted (InvocationHandler handler)
  842. {
  843. ((NativeInvocationHandler) handler).nativeContextDeleted();
  844. }
  845. //==============================================================================
  846. public static class HTTPStream
  847. {
  848. public HTTPStream (String address, boolean isPostToUse, byte[] postDataToUse,
  849. String headersToUse, int timeOutMsToUse,
  850. int[] statusCodeToUse, StringBuffer responseHeadersToUse,
  851. int numRedirectsToFollowToUse, String httpRequestCmdToUse) throws IOException
  852. {
  853. isPost = isPostToUse;
  854. postData = postDataToUse;
  855. headers = headersToUse;
  856. timeOutMs = timeOutMsToUse;
  857. statusCode = statusCodeToUse;
  858. responseHeaders = responseHeadersToUse;
  859. totalLength = -1;
  860. numRedirectsToFollow = numRedirectsToFollowToUse;
  861. httpRequestCmd = httpRequestCmdToUse;
  862. connection = createConnection (address, isPost, postData, headers, timeOutMs, httpRequestCmd);
  863. }
  864. private final HttpURLConnection createConnection (String address, boolean isPost, byte[] postData,
  865. String headers, int timeOutMs, String httpRequestCmdToUse) throws IOException
  866. {
  867. HttpURLConnection newConnection = (HttpURLConnection) (new URL(address).openConnection());
  868. try
  869. {
  870. newConnection.setInstanceFollowRedirects (false);
  871. newConnection.setConnectTimeout (timeOutMs);
  872. newConnection.setReadTimeout (timeOutMs);
  873. // 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.
  874. // So convert headers string to an array, with an element for each line
  875. String headerLines[] = headers.split("\\n");
  876. // Set request headers
  877. for (int i = 0; i < headerLines.length; ++i)
  878. {
  879. int pos = headerLines[i].indexOf (":");
  880. if (pos > 0 && pos < headerLines[i].length())
  881. {
  882. String field = headerLines[i].substring (0, pos);
  883. String value = headerLines[i].substring (pos + 1);
  884. if (value.length() > 0)
  885. newConnection.setRequestProperty (field, value);
  886. }
  887. }
  888. newConnection.setRequestMethod (httpRequestCmd);
  889. if (isPost)
  890. {
  891. newConnection.setDoOutput (true);
  892. if (postData != null)
  893. {
  894. OutputStream out = newConnection.getOutputStream();
  895. out.write(postData);
  896. out.flush();
  897. }
  898. }
  899. return newConnection;
  900. }
  901. catch (Throwable e)
  902. {
  903. newConnection.disconnect();
  904. throw new IOException ("Connection error");
  905. }
  906. }
  907. private final InputStream getCancellableStream (final boolean isInput) throws ExecutionException
  908. {
  909. synchronized (createFutureLock)
  910. {
  911. if (hasBeenCancelled.get())
  912. return null;
  913. streamFuture = executor.submit (new Callable<BufferedInputStream>()
  914. {
  915. @Override
  916. public BufferedInputStream call() throws IOException
  917. {
  918. return new BufferedInputStream (isInput ? connection.getInputStream()
  919. : connection.getErrorStream());
  920. }
  921. });
  922. }
  923. try
  924. {
  925. return streamFuture.get();
  926. }
  927. catch (InterruptedException e)
  928. {
  929. return null;
  930. }
  931. catch (CancellationException e)
  932. {
  933. return null;
  934. }
  935. }
  936. public final boolean connect()
  937. {
  938. boolean result = false;
  939. int numFollowedRedirects = 0;
  940. while (true)
  941. {
  942. result = doConnect();
  943. if (! result)
  944. return false;
  945. if (++numFollowedRedirects > numRedirectsToFollow)
  946. break;
  947. int status = statusCode[0];
  948. if (status == 301 || status == 302 || status == 303 || status == 307)
  949. {
  950. // Assumes only one occurrence of "Location"
  951. int pos1 = responseHeaders.indexOf ("Location:") + 10;
  952. int pos2 = responseHeaders.indexOf ("\n", pos1);
  953. if (pos2 > pos1)
  954. {
  955. String currentLocation = connection.getURL().toString();
  956. String newLocation = responseHeaders.substring (pos1, pos2);
  957. try
  958. {
  959. // Handle newLocation whether it's absolute or relative
  960. URL baseUrl = new URL (currentLocation);
  961. URL newUrl = new URL (baseUrl, newLocation);
  962. String transformedNewLocation = newUrl.toString();
  963. if (transformedNewLocation != currentLocation)
  964. {
  965. // Clear responseHeaders before next iteration
  966. responseHeaders.delete (0, responseHeaders.length());
  967. synchronized (createStreamLock)
  968. {
  969. if (hasBeenCancelled.get())
  970. return false;
  971. connection.disconnect();
  972. try
  973. {
  974. connection = createConnection (transformedNewLocation, isPost,
  975. postData, headers, timeOutMs,
  976. httpRequestCmd);
  977. }
  978. catch (Throwable e)
  979. {
  980. return false;
  981. }
  982. }
  983. }
  984. else
  985. {
  986. break;
  987. }
  988. }
  989. catch (Throwable e)
  990. {
  991. return false;
  992. }
  993. }
  994. else
  995. {
  996. break;
  997. }
  998. }
  999. else
  1000. {
  1001. break;
  1002. }
  1003. }
  1004. return result;
  1005. }
  1006. private final boolean doConnect()
  1007. {
  1008. synchronized (createStreamLock)
  1009. {
  1010. if (hasBeenCancelled.get())
  1011. return false;
  1012. try
  1013. {
  1014. try
  1015. {
  1016. inputStream = getCancellableStream (true);
  1017. }
  1018. catch (ExecutionException e)
  1019. {
  1020. if (connection.getResponseCode() < 400)
  1021. {
  1022. statusCode[0] = connection.getResponseCode();
  1023. connection.disconnect();
  1024. return false;
  1025. }
  1026. }
  1027. finally
  1028. {
  1029. statusCode[0] = connection.getResponseCode();
  1030. }
  1031. try
  1032. {
  1033. if (statusCode[0] >= 400)
  1034. inputStream = getCancellableStream (false);
  1035. else
  1036. inputStream = getCancellableStream (true);
  1037. }
  1038. catch (ExecutionException e)
  1039. {}
  1040. for (java.util.Map.Entry<String, java.util.List<String>> entry : connection.getHeaderFields().entrySet())
  1041. {
  1042. if (entry.getKey() != null && entry.getValue() != null)
  1043. {
  1044. responseHeaders.append(entry.getKey() + ": "
  1045. + android.text.TextUtils.join(",", entry.getValue()) + "\n");
  1046. if (entry.getKey().compareTo ("Content-Length") == 0)
  1047. totalLength = Integer.decode (entry.getValue().get (0));
  1048. }
  1049. }
  1050. return true;
  1051. }
  1052. catch (IOException e)
  1053. {
  1054. return false;
  1055. }
  1056. }
  1057. }
  1058. static class DisconnectionRunnable implements Runnable
  1059. {
  1060. public DisconnectionRunnable (HttpURLConnection theConnection,
  1061. InputStream theInputStream,
  1062. ReentrantLock theCreateStreamLock,
  1063. Object theCreateFutureLock,
  1064. Future<BufferedInputStream> theStreamFuture)
  1065. {
  1066. connectionToDisconnect = theConnection;
  1067. inputStream = theInputStream;
  1068. createStreamLock = theCreateStreamLock;
  1069. createFutureLock = theCreateFutureLock;
  1070. streamFuture = theStreamFuture;
  1071. }
  1072. public void run()
  1073. {
  1074. try
  1075. {
  1076. if (! createStreamLock.tryLock())
  1077. {
  1078. synchronized (createFutureLock)
  1079. {
  1080. if (streamFuture != null)
  1081. streamFuture.cancel (true);
  1082. }
  1083. createStreamLock.lock();
  1084. }
  1085. if (connectionToDisconnect != null)
  1086. connectionToDisconnect.disconnect();
  1087. if (inputStream != null)
  1088. inputStream.close();
  1089. }
  1090. catch (IOException e)
  1091. {}
  1092. finally
  1093. {
  1094. createStreamLock.unlock();
  1095. }
  1096. }
  1097. private HttpURLConnection connectionToDisconnect;
  1098. private InputStream inputStream;
  1099. private ReentrantLock createStreamLock;
  1100. private Object createFutureLock;
  1101. Future<BufferedInputStream> streamFuture;
  1102. }
  1103. public final void release()
  1104. {
  1105. DisconnectionRunnable disconnectionRunnable = new DisconnectionRunnable (connection,
  1106. inputStream,
  1107. createStreamLock,
  1108. createFutureLock,
  1109. streamFuture);
  1110. synchronized (createStreamLock)
  1111. {
  1112. hasBeenCancelled.set (true);
  1113. connection = null;
  1114. }
  1115. Thread disconnectionThread = new Thread(disconnectionRunnable);
  1116. disconnectionThread.start();
  1117. }
  1118. public final int read (byte[] buffer, int numBytes)
  1119. {
  1120. int num = 0;
  1121. try
  1122. {
  1123. synchronized (createStreamLock)
  1124. {
  1125. if (inputStream != null)
  1126. num = inputStream.read (buffer, 0, numBytes);
  1127. }
  1128. }
  1129. catch (IOException e)
  1130. {}
  1131. if (num > 0)
  1132. position += num;
  1133. return num;
  1134. }
  1135. public final long getPosition() { return position; }
  1136. public final long getTotalLength() { return totalLength; }
  1137. public final boolean isExhausted() { return false; }
  1138. public final boolean setPosition (long newPos) { return false; }
  1139. private boolean isPost;
  1140. private byte[] postData;
  1141. private String headers;
  1142. private int timeOutMs;
  1143. String httpRequestCmd;
  1144. private HttpURLConnection connection;
  1145. private int[] statusCode;
  1146. private StringBuffer responseHeaders;
  1147. private int totalLength;
  1148. private int numRedirectsToFollow;
  1149. private InputStream inputStream;
  1150. private long position;
  1151. private final ReentrantLock createStreamLock = new ReentrantLock();
  1152. private final Object createFutureLock = new Object();
  1153. private AtomicBoolean hasBeenCancelled = new AtomicBoolean();
  1154. private final ExecutorService executor = Executors.newCachedThreadPool (Executors.defaultThreadFactory());
  1155. Future<BufferedInputStream> streamFuture;
  1156. }
  1157. public static final HTTPStream createHTTPStream (String address, boolean isPost, byte[] postData,
  1158. String headers, int timeOutMs, int[] statusCode,
  1159. StringBuffer responseHeaders, int numRedirectsToFollow,
  1160. String httpRequestCmd)
  1161. {
  1162. // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL)
  1163. if (timeOutMs < 0)
  1164. timeOutMs = 0;
  1165. else if (timeOutMs == 0)
  1166. timeOutMs = 30000;
  1167. for (;;)
  1168. {
  1169. try
  1170. {
  1171. HTTPStream httpStream = new HTTPStream (address, isPost, postData, headers,
  1172. timeOutMs, statusCode, responseHeaders,
  1173. numRedirectsToFollow, httpRequestCmd);
  1174. return httpStream;
  1175. }
  1176. catch (Throwable e) {}
  1177. return null;
  1178. }
  1179. }
  1180. public final void launchURL (String url)
  1181. {
  1182. startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse (url)));
  1183. }
  1184. private native boolean webViewPageLoadStarted (long host, WebView view, String url);
  1185. private native void webViewPageLoadFinished (long host, WebView view, String url);
  1186. $$JuceAndroidWebViewNativeCode$$ // If you get an error here, you need to re-save your project with the Projucer!
  1187. private native void webViewReceivedSslError (long host, WebView view, SslErrorHandler handler, SslError error);
  1188. private native void webViewCloseWindowRequest (long host, WebView view);
  1189. private native void webViewCreateWindowRequest (long host, WebView view);
  1190. //==============================================================================
  1191. public class JuceWebViewClient extends WebViewClient
  1192. {
  1193. public JuceWebViewClient (long hostToUse)
  1194. {
  1195. host = hostToUse;
  1196. }
  1197. public void hostDeleted()
  1198. {
  1199. synchronized (hostLock)
  1200. {
  1201. host = 0;
  1202. }
  1203. }
  1204. @Override
  1205. public void onPageFinished (WebView view, String url)
  1206. {
  1207. if (host == 0)
  1208. return;
  1209. webViewPageLoadFinished (host, view, url);
  1210. }
  1211. @Override
  1212. public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
  1213. {
  1214. if (host == 0)
  1215. return;
  1216. webViewReceivedSslError (host, view, handler, error);
  1217. }
  1218. $$JuceAndroidWebViewCode$$ // If you get an error here, you need to re-save your project with the Projucer!
  1219. private long host;
  1220. private final Object hostLock = new Object();
  1221. }
  1222. public class JuceWebChromeClient extends WebChromeClient
  1223. {
  1224. public JuceWebChromeClient (long hostToUse)
  1225. {
  1226. host = hostToUse;
  1227. }
  1228. @Override
  1229. public void onCloseWindow (WebView window)
  1230. {
  1231. webViewCloseWindowRequest (host, window);
  1232. }
  1233. @Override
  1234. public boolean onCreateWindow (WebView view, boolean isDialog,
  1235. boolean isUserGesture, Message resultMsg)
  1236. {
  1237. webViewCreateWindowRequest (host, view);
  1238. return false;
  1239. }
  1240. private long host;
  1241. private final Object hostLock = new Object();
  1242. }
  1243. //==============================================================================
  1244. public static final String getLocaleValue (boolean isRegion)
  1245. {
  1246. java.util.Locale locale = java.util.Locale.getDefault();
  1247. return isRegion ? locale.getCountry()
  1248. : locale.getLanguage();
  1249. }
  1250. private static final String getFileLocation (String type)
  1251. {
  1252. return Environment.getExternalStoragePublicDirectory (type).getAbsolutePath();
  1253. }
  1254. public static final String getDocumentsFolder()
  1255. {
  1256. if (getAndroidSDKVersion() >= 19)
  1257. return getFileLocation ("Documents");
  1258. return Environment.getDataDirectory().getAbsolutePath();
  1259. }
  1260. public static final String getPicturesFolder() { return getFileLocation (Environment.DIRECTORY_PICTURES); }
  1261. public static final String getMusicFolder() { return getFileLocation (Environment.DIRECTORY_MUSIC); }
  1262. public static final String getMoviesFolder() { return getFileLocation (Environment.DIRECTORY_MOVIES); }
  1263. public static final String getDownloadsFolder() { return getFileLocation (Environment.DIRECTORY_DOWNLOADS); }
  1264. //==============================================================================
  1265. @Override
  1266. protected void onActivityResult (int requestCode, int resultCode, Intent data)
  1267. {
  1268. appActivityResult (requestCode, resultCode, data);
  1269. }
  1270. @Override
  1271. protected void onNewIntent (Intent intent)
  1272. {
  1273. super.onNewIntent(intent);
  1274. setIntent(intent);
  1275. appNewIntent (intent);
  1276. }
  1277. //==============================================================================
  1278. public final Typeface getTypeFaceFromAsset (String assetName)
  1279. {
  1280. try
  1281. {
  1282. return Typeface.createFromAsset (this.getResources().getAssets(), assetName);
  1283. }
  1284. catch (Throwable e) {}
  1285. return null;
  1286. }
  1287. final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
  1288. public static String bytesToHex (byte[] bytes)
  1289. {
  1290. char[] hexChars = new char[bytes.length * 2];
  1291. for (int j = 0; j < bytes.length; ++j)
  1292. {
  1293. int v = bytes[j] & 0xff;
  1294. hexChars[j * 2] = hexArray[v >>> 4];
  1295. hexChars[j * 2 + 1] = hexArray[v & 0x0f];
  1296. }
  1297. return new String (hexChars);
  1298. }
  1299. final private java.util.Map dataCache = new java.util.HashMap();
  1300. synchronized private final File getDataCacheFile (byte[] data)
  1301. {
  1302. try
  1303. {
  1304. java.security.MessageDigest digest = java.security.MessageDigest.getInstance ("MD5");
  1305. digest.update (data);
  1306. String key = bytesToHex (digest.digest());
  1307. if (dataCache.containsKey (key))
  1308. return (File) dataCache.get (key);
  1309. File f = new File (this.getCacheDir(), "bindata_" + key);
  1310. f.delete();
  1311. FileOutputStream os = new FileOutputStream (f);
  1312. os.write (data, 0, data.length);
  1313. dataCache.put (key, f);
  1314. return f;
  1315. }
  1316. catch (Throwable e) {}
  1317. return null;
  1318. }
  1319. private final void clearDataCache()
  1320. {
  1321. java.util.Iterator it = dataCache.values().iterator();
  1322. while (it.hasNext())
  1323. {
  1324. File f = (File) it.next();
  1325. f.delete();
  1326. }
  1327. }
  1328. public final Typeface getTypeFaceFromByteArray (byte[] data)
  1329. {
  1330. try
  1331. {
  1332. File f = getDataCacheFile (data);
  1333. if (f != null)
  1334. return Typeface.createFromFile (f);
  1335. }
  1336. catch (Exception e)
  1337. {
  1338. Log.e ("JUCE", e.toString());
  1339. }
  1340. return null;
  1341. }
  1342. public static final int getAndroidSDKVersion()
  1343. {
  1344. return android.os.Build.VERSION.SDK_INT;
  1345. }
  1346. public final String audioManagerGetProperty (String property)
  1347. {
  1348. Object obj = getSystemService (AUDIO_SERVICE);
  1349. if (obj == null)
  1350. return null;
  1351. java.lang.reflect.Method method;
  1352. try
  1353. {
  1354. method = obj.getClass().getMethod ("getProperty", String.class);
  1355. }
  1356. catch (SecurityException e) { return null; }
  1357. catch (NoSuchMethodException e) { return null; }
  1358. if (method == null)
  1359. return null;
  1360. try
  1361. {
  1362. return (String) method.invoke (obj, property);
  1363. }
  1364. catch (java.lang.IllegalArgumentException e) {}
  1365. catch (java.lang.IllegalAccessException e) {}
  1366. catch (java.lang.reflect.InvocationTargetException e) {}
  1367. return null;
  1368. }
  1369. public final boolean hasSystemFeature (String property)
  1370. {
  1371. return getPackageManager().hasSystemFeature (property);
  1372. }
  1373. }