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.

718 lines
23KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  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.net.Uri;
  25. import android.os.Bundle;
  26. import android.view.*;
  27. import android.view.inputmethod.BaseInputConnection;
  28. import android.view.inputmethod.EditorInfo;
  29. import android.view.inputmethod.InputConnection;
  30. import android.view.inputmethod.InputMethodManager;
  31. import android.graphics.*;
  32. import android.opengl.*;
  33. import android.text.ClipboardManager;
  34. import android.text.InputType;
  35. import android.util.DisplayMetrics;
  36. import java.io.BufferedInputStream;
  37. import java.io.IOException;
  38. import java.io.InputStream;
  39. import java.io.OutputStream;
  40. import java.net.URL;
  41. import java.net.HttpURLConnection;
  42. import javax.microedition.khronos.egl.EGLConfig;
  43. import javax.microedition.khronos.opengles.GL10;
  44. import android.media.AudioManager;
  45. import android.media.MediaScannerConnection;
  46. import android.media.MediaScannerConnection.MediaScannerConnectionClient;
  47. //==============================================================================
  48. public final class JuceAppActivity extends Activity
  49. {
  50. //==============================================================================
  51. static
  52. {
  53. System.loadLibrary ("juce_jni");
  54. }
  55. @Override
  56. public final void onCreate (Bundle savedInstanceState)
  57. {
  58. super.onCreate (savedInstanceState);
  59. viewHolder = new ViewHolder (this);
  60. setContentView (viewHolder);
  61. setVolumeControlStream (AudioManager.STREAM_MUSIC);
  62. }
  63. @Override
  64. protected final void onDestroy()
  65. {
  66. quitApp();
  67. super.onDestroy();
  68. }
  69. @Override
  70. protected final void onPause()
  71. {
  72. if (viewHolder != null)
  73. viewHolder.onPause();
  74. suspendApp();
  75. super.onPause();
  76. }
  77. @Override
  78. protected final void onResume()
  79. {
  80. super.onResume();
  81. if (viewHolder != null)
  82. viewHolder.onResume();
  83. resumeApp();
  84. }
  85. @Override
  86. public void onConfigurationChanged (Configuration cfg)
  87. {
  88. super.onConfigurationChanged (cfg);
  89. setContentView (viewHolder);
  90. }
  91. private void callAppLauncher()
  92. {
  93. launchApp (getApplicationInfo().publicSourceDir,
  94. getApplicationInfo().dataDir);
  95. }
  96. //==============================================================================
  97. private native void launchApp (String appFile, String appDataDir);
  98. private native void quitApp();
  99. private native void suspendApp();
  100. private native void resumeApp();
  101. private native void setScreenSize (int screenWidth, int screenHeight, int dpi);
  102. //==============================================================================
  103. public native void deliverMessage (long value);
  104. private android.os.Handler messageHandler = new android.os.Handler();
  105. public final void postMessage (long value)
  106. {
  107. messageHandler.post (new MessageCallback (value));
  108. }
  109. private final class MessageCallback implements Runnable
  110. {
  111. public MessageCallback (long value_) { value = value_; }
  112. public final void run() { deliverMessage (value); }
  113. private long value;
  114. }
  115. //==============================================================================
  116. private ViewHolder viewHolder;
  117. public final ComponentPeerView createNewView (boolean opaque, long host)
  118. {
  119. ComponentPeerView v = new ComponentPeerView (this, opaque, host);
  120. viewHolder.addView (v);
  121. return v;
  122. }
  123. public final void deleteView (ComponentPeerView view)
  124. {
  125. ViewGroup group = (ViewGroup) (view.getParent());
  126. if (group != null)
  127. group.removeView (view);
  128. }
  129. final class ViewHolder extends ViewGroup
  130. {
  131. public ViewHolder (Context context)
  132. {
  133. super (context);
  134. setDescendantFocusability (ViewGroup.FOCUS_AFTER_DESCENDANTS);
  135. setFocusable (false);
  136. }
  137. protected final void onLayout (boolean changed, int left, int top, int right, int bottom)
  138. {
  139. setScreenSize (getWidth(), getHeight(), getDPI());
  140. if (isFirstResize)
  141. {
  142. isFirstResize = false;
  143. callAppLauncher();
  144. }
  145. }
  146. public final void onPause()
  147. {
  148. for (int i = getChildCount(); --i >= 0;)
  149. {
  150. View v = getChildAt (i);
  151. if (v instanceof ComponentPeerView)
  152. ((ComponentPeerView) v).onPause();
  153. }
  154. }
  155. public final void onResume()
  156. {
  157. for (int i = getChildCount(); --i >= 0;)
  158. {
  159. View v = getChildAt (i);
  160. if (v instanceof ComponentPeerView)
  161. ((ComponentPeerView) v).onResume();
  162. }
  163. }
  164. private final int getDPI()
  165. {
  166. DisplayMetrics metrics = new DisplayMetrics();
  167. getWindowManager().getDefaultDisplay().getMetrics (metrics);
  168. return metrics.densityDpi;
  169. }
  170. private boolean isFirstResize = true;
  171. }
  172. public final void excludeClipRegion (android.graphics.Canvas canvas, float left, float top, float right, float bottom)
  173. {
  174. canvas.clipRect (left, top, right, bottom, android.graphics.Region.Op.DIFFERENCE);
  175. }
  176. //==============================================================================
  177. public final String getClipboardContent()
  178. {
  179. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  180. return clipboard.getText().toString();
  181. }
  182. public final void setClipboardContent (String newText)
  183. {
  184. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  185. clipboard.setText (newText);
  186. }
  187. //==============================================================================
  188. public final void showMessageBox (String title, String message, final long callback)
  189. {
  190. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  191. builder.setTitle (title)
  192. .setMessage (message)
  193. .setCancelable (true)
  194. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  195. {
  196. public void onClick (DialogInterface dialog, int id)
  197. {
  198. dialog.cancel();
  199. JuceAppActivity.this.alertDismissed (callback, 0);
  200. }
  201. });
  202. builder.create().show();
  203. }
  204. public final void showOkCancelBox (String title, String message, final long callback)
  205. {
  206. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  207. builder.setTitle (title)
  208. .setMessage (message)
  209. .setCancelable (true)
  210. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  211. {
  212. public void onClick (DialogInterface dialog, int id)
  213. {
  214. dialog.cancel();
  215. JuceAppActivity.this.alertDismissed (callback, 1);
  216. }
  217. })
  218. .setNegativeButton ("Cancel", new DialogInterface.OnClickListener()
  219. {
  220. public void onClick (DialogInterface dialog, int id)
  221. {
  222. dialog.cancel();
  223. JuceAppActivity.this.alertDismissed (callback, 0);
  224. }
  225. });
  226. builder.create().show();
  227. }
  228. public final void showYesNoCancelBox (String title, String message, final long callback)
  229. {
  230. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  231. builder.setTitle (title)
  232. .setMessage (message)
  233. .setCancelable (true)
  234. .setPositiveButton ("Yes", new DialogInterface.OnClickListener()
  235. {
  236. public void onClick (DialogInterface dialog, int id)
  237. {
  238. dialog.cancel();
  239. JuceAppActivity.this.alertDismissed (callback, 1);
  240. }
  241. })
  242. .setNegativeButton ("No", new DialogInterface.OnClickListener()
  243. {
  244. public void onClick (DialogInterface dialog, int id)
  245. {
  246. dialog.cancel();
  247. JuceAppActivity.this.alertDismissed (callback, 2);
  248. }
  249. })
  250. .setNeutralButton ("Cancel", new DialogInterface.OnClickListener()
  251. {
  252. public void onClick (DialogInterface dialog, int id)
  253. {
  254. dialog.cancel();
  255. JuceAppActivity.this.alertDismissed (callback, 0);
  256. }
  257. });
  258. builder.create().show();
  259. }
  260. public native void alertDismissed (long callback, int id);
  261. //==============================================================================
  262. public final class ComponentPeerView extends ViewGroup
  263. implements View.OnFocusChangeListener
  264. {
  265. public ComponentPeerView (Context context, boolean opaque_, long host)
  266. {
  267. super (context);
  268. this.host = host;
  269. setWillNotDraw (false);
  270. opaque = opaque_;
  271. setFocusable (true);
  272. setFocusableInTouchMode (true);
  273. setOnFocusChangeListener (this);
  274. requestFocus();
  275. }
  276. //==============================================================================
  277. private native void handlePaint (long host, Canvas canvas);
  278. @Override
  279. public void onDraw (Canvas canvas)
  280. {
  281. handlePaint (host, canvas);
  282. }
  283. @Override
  284. public boolean isOpaque()
  285. {
  286. return opaque;
  287. }
  288. private boolean opaque;
  289. private long host;
  290. //==============================================================================
  291. private native void handleMouseDown (long host, int index, float x, float y, long time);
  292. private native void handleMouseDrag (long host, int index, float x, float y, long time);
  293. private native void handleMouseUp (long host, int index, float x, float y, long time);
  294. @Override
  295. public boolean onTouchEvent (MotionEvent event)
  296. {
  297. int action = event.getAction();
  298. long time = event.getEventTime();
  299. switch (action & MotionEvent.ACTION_MASK)
  300. {
  301. case MotionEvent.ACTION_DOWN:
  302. handleMouseDown (host, event.getPointerId(0), event.getX(), event.getY(), time);
  303. return true;
  304. case MotionEvent.ACTION_CANCEL:
  305. case MotionEvent.ACTION_UP:
  306. handleMouseUp (host, event.getPointerId(0), event.getX(), event.getY(), time);
  307. return true;
  308. case MotionEvent.ACTION_MOVE:
  309. {
  310. int n = event.getPointerCount();
  311. for (int i = 0; i < n; ++i)
  312. handleMouseDrag (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  313. return true;
  314. }
  315. case MotionEvent.ACTION_POINTER_UP:
  316. {
  317. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  318. handleMouseUp (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  319. return true;
  320. }
  321. case MotionEvent.ACTION_POINTER_DOWN:
  322. {
  323. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  324. handleMouseDown (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  325. return true;
  326. }
  327. default:
  328. break;
  329. }
  330. return false;
  331. }
  332. //==============================================================================
  333. private native void handleKeyDown (long host, int keycode, int textchar);
  334. private native void handleKeyUp (long host, int keycode, int textchar);
  335. public void showKeyboard (boolean shouldShow)
  336. {
  337. InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
  338. if (imm != null)
  339. {
  340. if (shouldShow)
  341. imm.showSoftInput (this, InputMethodManager.SHOW_FORCED);
  342. else
  343. imm.hideSoftInputFromWindow (getWindowToken(), 0);
  344. }
  345. }
  346. @Override
  347. public boolean onKeyDown (int keyCode, KeyEvent event)
  348. {
  349. switch (keyCode)
  350. {
  351. case KeyEvent.KEYCODE_VOLUME_UP:
  352. case KeyEvent.KEYCODE_VOLUME_DOWN:
  353. return super.onKeyDown (keyCode, event);
  354. default: break;
  355. }
  356. handleKeyDown (host, keyCode, event.getUnicodeChar());
  357. return true;
  358. }
  359. @Override
  360. public boolean onKeyUp (int keyCode, KeyEvent event)
  361. {
  362. handleKeyUp (host, keyCode, event.getUnicodeChar());
  363. return true;
  364. }
  365. // this is here to make keyboard entry work on a Galaxy Tab2 10.1
  366. @Override
  367. public InputConnection onCreateInputConnection (EditorInfo outAttrs)
  368. {
  369. outAttrs.actionLabel = "";
  370. outAttrs.hintText = "";
  371. outAttrs.initialCapsMode = 0;
  372. outAttrs.initialSelEnd = outAttrs.initialSelStart = -1;
  373. outAttrs.label = "";
  374. outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
  375. outAttrs.inputType = InputType.TYPE_NULL;
  376. return new BaseInputConnection (this, false);
  377. }
  378. //==============================================================================
  379. @Override
  380. protected void onSizeChanged (int w, int h, int oldw, int oldh)
  381. {
  382. super.onSizeChanged (w, h, oldw, oldh);
  383. viewSizeChanged (host);
  384. }
  385. @Override
  386. protected void onLayout (boolean changed, int left, int top, int right, int bottom)
  387. {
  388. for (int i = getChildCount(); --i >= 0;)
  389. requestTransparentRegion (getChildAt (i));
  390. }
  391. private native void viewSizeChanged (long host);
  392. @Override
  393. public void onFocusChange (View v, boolean hasFocus)
  394. {
  395. if (v == this)
  396. focusChanged (host, hasFocus);
  397. }
  398. private native void focusChanged (long host, boolean hasFocus);
  399. public void setViewName (String newName) {}
  400. public boolean isVisible() { return getVisibility() == VISIBLE; }
  401. public void setVisible (boolean b) { setVisibility (b ? VISIBLE : INVISIBLE); }
  402. public boolean containsPoint (int x, int y)
  403. {
  404. return true; //xxx needs to check overlapping views
  405. }
  406. public final void onPause()
  407. {
  408. for (int i = getChildCount(); --i >= 0;)
  409. {
  410. View v = getChildAt (i);
  411. if (v instanceof OpenGLView)
  412. ((OpenGLView) v).onPause();
  413. }
  414. }
  415. public final void onResume()
  416. {
  417. for (int i = getChildCount(); --i >= 0;)
  418. {
  419. View v = getChildAt (i);
  420. if (v instanceof OpenGLView)
  421. ((OpenGLView) v).onResume();
  422. }
  423. }
  424. public OpenGLView createGLView()
  425. {
  426. OpenGLView glView = new OpenGLView (getContext());
  427. addView (glView);
  428. return glView;
  429. }
  430. }
  431. //==============================================================================
  432. public final class OpenGLView extends GLSurfaceView
  433. implements GLSurfaceView.Renderer
  434. {
  435. OpenGLView (Context context)
  436. {
  437. super (context);
  438. setEGLContextClientVersion (2);
  439. setRenderer (this);
  440. setRenderMode (RENDERMODE_WHEN_DIRTY);
  441. }
  442. @Override
  443. public void onSurfaceCreated (GL10 unused, EGLConfig config)
  444. {
  445. contextCreated();
  446. }
  447. @Override
  448. public void onSurfaceChanged (GL10 unused, int width, int height)
  449. {
  450. contextChangedSize();
  451. }
  452. @Override
  453. public void onDrawFrame (GL10 unused)
  454. {
  455. render();
  456. }
  457. private native void contextCreated();
  458. private native void contextChangedSize();
  459. private native void render();
  460. }
  461. //==============================================================================
  462. public final int[] renderGlyph (char glyph, Paint paint, android.graphics.Matrix matrix, Rect bounds)
  463. {
  464. Path p = new Path();
  465. paint.getTextPath (String.valueOf (glyph), 0, 1, 0.0f, 0.0f, p);
  466. RectF boundsF = new RectF();
  467. p.computeBounds (boundsF, true);
  468. matrix.mapRect (boundsF);
  469. boundsF.roundOut (bounds);
  470. bounds.left--;
  471. bounds.right++;
  472. final int w = bounds.width();
  473. final int h = Math.max (1, bounds.height());
  474. Bitmap bm = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
  475. Canvas c = new Canvas (bm);
  476. matrix.postTranslate (-bounds.left, -bounds.top);
  477. c.setMatrix (matrix);
  478. c.drawPath (p, paint);
  479. final int sizeNeeded = w * h;
  480. if (cachedRenderArray.length < sizeNeeded)
  481. cachedRenderArray = new int [sizeNeeded];
  482. bm.getPixels (cachedRenderArray, 0, w, 0, 0, w, h);
  483. bm.recycle();
  484. return cachedRenderArray;
  485. }
  486. private int[] cachedRenderArray = new int [256];
  487. //==============================================================================
  488. public static class HTTPStream
  489. {
  490. public HTTPStream (HttpURLConnection connection_) throws IOException
  491. {
  492. connection = connection_;
  493. inputStream = new BufferedInputStream (connection.getInputStream());
  494. }
  495. public final void release()
  496. {
  497. try
  498. {
  499. inputStream.close();
  500. }
  501. catch (IOException e)
  502. {}
  503. connection.disconnect();
  504. }
  505. public final int read (byte[] buffer, int numBytes)
  506. {
  507. int num = 0;
  508. try
  509. {
  510. num = inputStream.read (buffer, 0, numBytes);
  511. }
  512. catch (IOException e)
  513. {}
  514. if (num > 0)
  515. position += num;
  516. return num;
  517. }
  518. public final long getPosition() { return position; }
  519. public final long getTotalLength() { return -1; }
  520. public final boolean isExhausted() { return false; }
  521. public final boolean setPosition (long newPos) { return false; }
  522. private HttpURLConnection connection;
  523. private InputStream inputStream;
  524. private long position;
  525. }
  526. public static final HTTPStream createHTTPStream (String address, boolean isPost, byte[] postData,
  527. String headers, int timeOutMs,
  528. java.lang.StringBuffer responseHeaders)
  529. {
  530. try
  531. {
  532. HttpURLConnection connection = (HttpURLConnection) (new URL (address).openConnection());
  533. if (connection != null)
  534. {
  535. try
  536. {
  537. if (isPost)
  538. {
  539. connection.setConnectTimeout (timeOutMs);
  540. connection.setDoOutput (true);
  541. connection.setChunkedStreamingMode (0);
  542. OutputStream out = connection.getOutputStream();
  543. out.write (postData);
  544. out.flush();
  545. }
  546. return new HTTPStream (connection);
  547. }
  548. catch (Throwable e)
  549. {
  550. connection.disconnect();
  551. }
  552. }
  553. }
  554. catch (Throwable e)
  555. {}
  556. return null;
  557. }
  558. public final void launchURL (String url)
  559. {
  560. startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse (url)));
  561. }
  562. public static final String getLocaleValue (boolean isRegion)
  563. {
  564. java.util.Locale locale = java.util.Locale.getDefault();
  565. return isRegion ? locale.getDisplayCountry (java.util.Locale.US)
  566. : locale.getDisplayLanguage (java.util.Locale.US);
  567. }
  568. //==============================================================================
  569. private final class SingleMediaScanner implements MediaScannerConnectionClient
  570. {
  571. public SingleMediaScanner (Context context, String filename)
  572. {
  573. file = filename;
  574. msc = new MediaScannerConnection (context, this);
  575. msc.connect();
  576. }
  577. @Override
  578. public void onMediaScannerConnected()
  579. {
  580. msc.scanFile (file, null);
  581. }
  582. @Override
  583. public void onScanCompleted (String path, Uri uri)
  584. {
  585. msc.disconnect();
  586. }
  587. private MediaScannerConnection msc;
  588. private String file;
  589. }
  590. public final void scanFile (String filename)
  591. {
  592. new SingleMediaScanner (this, filename);
  593. }
  594. }