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.

708 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)
  118. {
  119. ComponentPeerView v = new ComponentPeerView (this, opaque);
  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_)
  266. {
  267. super (context);
  268. setWillNotDraw (false);
  269. opaque = opaque_;
  270. setFocusable (true);
  271. setFocusableInTouchMode (true);
  272. setOnFocusChangeListener (this);
  273. requestFocus();
  274. }
  275. //==============================================================================
  276. private native void handlePaint (Canvas canvas);
  277. @Override
  278. public void draw (Canvas canvas)
  279. {
  280. super.draw (canvas);
  281. handlePaint (canvas);
  282. }
  283. @Override
  284. public boolean isOpaque()
  285. {
  286. return opaque;
  287. }
  288. private boolean opaque;
  289. //==============================================================================
  290. private native void handleMouseDown (int index, float x, float y, long time);
  291. private native void handleMouseDrag (int index, float x, float y, long time);
  292. private native void handleMouseUp (int index, float x, float y, long time);
  293. @Override
  294. public boolean onTouchEvent (MotionEvent event)
  295. {
  296. int action = event.getAction();
  297. long time = event.getEventTime();
  298. switch (action & MotionEvent.ACTION_MASK)
  299. {
  300. case MotionEvent.ACTION_DOWN:
  301. handleMouseDown (event.getPointerId(0), event.getX(), event.getY(), time);
  302. return true;
  303. case MotionEvent.ACTION_CANCEL:
  304. case MotionEvent.ACTION_UP:
  305. handleMouseUp (event.getPointerId(0), event.getX(), event.getY(), time);
  306. return true;
  307. case MotionEvent.ACTION_MOVE:
  308. {
  309. int n = event.getPointerCount();
  310. for (int i = 0; i < n; ++i)
  311. handleMouseDrag (event.getPointerId(i), event.getX(i), event.getY(i), time);
  312. return true;
  313. }
  314. case MotionEvent.ACTION_POINTER_UP:
  315. {
  316. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  317. handleMouseUp (event.getPointerId(i), event.getX(i), event.getY(i), time);
  318. return true;
  319. }
  320. case MotionEvent.ACTION_POINTER_DOWN:
  321. {
  322. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  323. handleMouseDown (event.getPointerId(i), event.getX(i), event.getY(i), time);
  324. return true;
  325. }
  326. default:
  327. break;
  328. }
  329. return false;
  330. }
  331. //==============================================================================
  332. private native void handleKeyDown (int keycode, int textchar);
  333. private native void handleKeyUp (int keycode, int textchar);
  334. public void showKeyboard (boolean shouldShow)
  335. {
  336. InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
  337. if (imm != null)
  338. {
  339. if (shouldShow)
  340. imm.showSoftInput (this, InputMethodManager.SHOW_FORCED);
  341. else
  342. imm.hideSoftInputFromWindow (getWindowToken(), 0);
  343. }
  344. }
  345. @Override
  346. public boolean onKeyDown (int keyCode, KeyEvent event)
  347. {
  348. handleKeyDown (keyCode, event.getUnicodeChar());
  349. return true;
  350. }
  351. @Override
  352. public boolean onKeyUp (int keyCode, KeyEvent event)
  353. {
  354. handleKeyUp (keyCode, event.getUnicodeChar());
  355. return true;
  356. }
  357. // this is here to make keyboard entry work on a Galaxy Tab2 10.1
  358. @Override
  359. public InputConnection onCreateInputConnection (EditorInfo outAttrs)
  360. {
  361. outAttrs.actionLabel = "";
  362. outAttrs.hintText = "";
  363. outAttrs.initialCapsMode = 0;
  364. outAttrs.initialSelEnd = outAttrs.initialSelStart = -1;
  365. outAttrs.label = "";
  366. outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
  367. outAttrs.inputType = InputType.TYPE_NULL;
  368. return new BaseInputConnection (this, false);
  369. }
  370. //==============================================================================
  371. @Override
  372. protected void onSizeChanged (int w, int h, int oldw, int oldh)
  373. {
  374. super.onSizeChanged (w, h, oldw, oldh);
  375. viewSizeChanged();
  376. }
  377. @Override
  378. protected void onLayout (boolean changed, int left, int top, int right, int bottom)
  379. {
  380. for (int i = getChildCount(); --i >= 0;)
  381. requestTransparentRegion (getChildAt (i));
  382. }
  383. private native void viewSizeChanged();
  384. @Override
  385. public void onFocusChange (View v, boolean hasFocus)
  386. {
  387. if (v == this)
  388. focusChanged (hasFocus);
  389. }
  390. private native void focusChanged (boolean hasFocus);
  391. public void setViewName (String newName) {}
  392. public boolean isVisible() { return getVisibility() == VISIBLE; }
  393. public void setVisible (boolean b) { setVisibility (b ? VISIBLE : INVISIBLE); }
  394. public boolean containsPoint (int x, int y)
  395. {
  396. return true; //xxx needs to check overlapping views
  397. }
  398. public final void onPause()
  399. {
  400. for (int i = getChildCount(); --i >= 0;)
  401. {
  402. View v = getChildAt (i);
  403. if (v instanceof OpenGLView)
  404. ((OpenGLView) v).onPause();
  405. }
  406. }
  407. public final void onResume()
  408. {
  409. for (int i = getChildCount(); --i >= 0;)
  410. {
  411. View v = getChildAt (i);
  412. if (v instanceof OpenGLView)
  413. ((OpenGLView) v).onResume();
  414. }
  415. }
  416. public OpenGLView createGLView()
  417. {
  418. OpenGLView glView = new OpenGLView (getContext());
  419. addView (glView);
  420. return glView;
  421. }
  422. }
  423. //==============================================================================
  424. public final class OpenGLView extends GLSurfaceView
  425. implements GLSurfaceView.Renderer
  426. {
  427. OpenGLView (Context context)
  428. {
  429. super (context);
  430. setEGLContextClientVersion (2);
  431. setRenderer (this);
  432. setRenderMode (RENDERMODE_WHEN_DIRTY);
  433. }
  434. @Override
  435. public void onSurfaceCreated (GL10 unused, EGLConfig config)
  436. {
  437. contextCreated();
  438. }
  439. @Override
  440. public void onSurfaceChanged (GL10 unused, int width, int height)
  441. {
  442. contextChangedSize();
  443. }
  444. @Override
  445. public void onDrawFrame (GL10 unused)
  446. {
  447. render();
  448. }
  449. private native void contextCreated();
  450. private native void contextChangedSize();
  451. private native void render();
  452. }
  453. //==============================================================================
  454. public final int[] renderGlyph (char glyph, Paint paint, android.graphics.Matrix matrix, Rect bounds)
  455. {
  456. Path p = new Path();
  457. paint.getTextPath (String.valueOf (glyph), 0, 1, 0.0f, 0.0f, p);
  458. RectF boundsF = new RectF();
  459. p.computeBounds (boundsF, true);
  460. matrix.mapRect (boundsF);
  461. boundsF.roundOut (bounds);
  462. bounds.left--;
  463. bounds.right++;
  464. final int w = bounds.width();
  465. final int h = Math.max (1, bounds.height());
  466. Bitmap bm = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
  467. Canvas c = new Canvas (bm);
  468. matrix.postTranslate (-bounds.left, -bounds.top);
  469. c.setMatrix (matrix);
  470. c.drawPath (p, paint);
  471. final int sizeNeeded = w * h;
  472. if (cachedRenderArray.length < sizeNeeded)
  473. cachedRenderArray = new int [sizeNeeded];
  474. bm.getPixels (cachedRenderArray, 0, w, 0, 0, w, h);
  475. bm.recycle();
  476. return cachedRenderArray;
  477. }
  478. private int[] cachedRenderArray = new int [256];
  479. //==============================================================================
  480. public static class HTTPStream
  481. {
  482. public HTTPStream (HttpURLConnection connection_) throws IOException
  483. {
  484. connection = connection_;
  485. inputStream = new BufferedInputStream (connection.getInputStream());
  486. }
  487. public final void release()
  488. {
  489. try
  490. {
  491. inputStream.close();
  492. }
  493. catch (IOException e)
  494. {}
  495. connection.disconnect();
  496. }
  497. public final int read (byte[] buffer, int numBytes)
  498. {
  499. int num = 0;
  500. try
  501. {
  502. num = inputStream.read (buffer, 0, numBytes);
  503. }
  504. catch (IOException e)
  505. {}
  506. if (num > 0)
  507. position += num;
  508. return num;
  509. }
  510. public final long getPosition() { return position; }
  511. public final long getTotalLength() { return -1; }
  512. public final boolean isExhausted() { return false; }
  513. public final boolean setPosition (long newPos) { return false; }
  514. private HttpURLConnection connection;
  515. private InputStream inputStream;
  516. private long position;
  517. }
  518. public static final HTTPStream createHTTPStream (String address, boolean isPost, byte[] postData,
  519. String headers, int timeOutMs,
  520. java.lang.StringBuffer responseHeaders)
  521. {
  522. try
  523. {
  524. HttpURLConnection connection = (HttpURLConnection) (new URL (address).openConnection());
  525. if (connection != null)
  526. {
  527. try
  528. {
  529. if (isPost)
  530. {
  531. connection.setConnectTimeout (timeOutMs);
  532. connection.setDoOutput (true);
  533. connection.setChunkedStreamingMode (0);
  534. OutputStream out = connection.getOutputStream();
  535. out.write (postData);
  536. out.flush();
  537. }
  538. return new HTTPStream (connection);
  539. }
  540. catch (Throwable e)
  541. {
  542. connection.disconnect();
  543. }
  544. }
  545. }
  546. catch (Throwable e)
  547. {}
  548. return null;
  549. }
  550. public final void launchURL (String url)
  551. {
  552. startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse (url)));
  553. }
  554. public static final String getLocaleValue (boolean isRegion)
  555. {
  556. java.util.Locale locale = java.util.Locale.getDefault();
  557. return isRegion ? locale.getDisplayCountry (java.util.Locale.US)
  558. : locale.getDisplayLanguage (java.util.Locale.US);
  559. }
  560. //==============================================================================
  561. private final class SingleMediaScanner implements MediaScannerConnectionClient
  562. {
  563. public SingleMediaScanner (Context context, String filename)
  564. {
  565. file = filename;
  566. msc = new MediaScannerConnection (context, this);
  567. msc.connect();
  568. }
  569. @Override
  570. public void onMediaScannerConnected()
  571. {
  572. msc.scanFile (file, null);
  573. }
  574. @Override
  575. public void onScanCompleted (String path, Uri uri)
  576. {
  577. msc.disconnect();
  578. }
  579. private MediaScannerConnection msc;
  580. private String file;
  581. }
  582. public final void scanFile (String filename)
  583. {
  584. new SingleMediaScanner (this, filename);
  585. }
  586. }