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.

1779 lines
63KB

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