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.

1805 lines
64KB

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