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.

564 lines
19KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-10 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. package com.juce;
  19. import android.app.Activity;
  20. import android.app.AlertDialog;
  21. import android.content.DialogInterface;
  22. import android.content.Context;
  23. import android.content.Intent;
  24. import android.content.res.Configuration;
  25. import android.net.Uri;
  26. import android.os.Bundle;
  27. import android.view.*;
  28. import android.graphics.*;
  29. import android.opengl.*;
  30. import android.text.ClipboardManager;
  31. import java.io.BufferedInputStream;
  32. import java.io.IOException;
  33. import java.io.InputStream;
  34. import java.io.OutputStream;
  35. import java.net.URL;
  36. import java.net.HttpURLConnection;
  37. import javax.microedition.khronos.egl.EGLConfig;
  38. import javax.microedition.khronos.opengles.GL10;
  39. import android.media.MediaScannerConnection;
  40. import android.media.MediaScannerConnection.MediaScannerConnectionClient;
  41. //==============================================================================
  42. public final class JuceAppActivity extends Activity
  43. {
  44. //==============================================================================
  45. static
  46. {
  47. System.loadLibrary ("juce_jni");
  48. }
  49. @Override
  50. public final void onCreate (Bundle savedInstanceState)
  51. {
  52. super.onCreate (savedInstanceState);
  53. viewHolder = new ViewHolder (this);
  54. setContentView (viewHolder);
  55. }
  56. @Override
  57. protected final void onDestroy()
  58. {
  59. quitApp();
  60. super.onDestroy();
  61. }
  62. @Override
  63. protected final void onPause()
  64. {
  65. suspendApp();
  66. super.onPause();
  67. }
  68. @Override
  69. protected final void onResume()
  70. {
  71. super.onResume();
  72. resumeApp();
  73. }
  74. @Override
  75. public void onConfigurationChanged (Configuration cfg)
  76. {
  77. super.onConfigurationChanged (cfg);
  78. setContentView (viewHolder);
  79. }
  80. private void callAppLauncher()
  81. {
  82. launchApp (getApplicationInfo().publicSourceDir,
  83. getApplicationInfo().dataDir);
  84. }
  85. //==============================================================================
  86. private native void launchApp (String appFile, String appDataDir);
  87. private native void quitApp();
  88. private native void suspendApp();
  89. private native void resumeApp();
  90. private native void setScreenSize (int screenWidth, int screenHeight);
  91. //==============================================================================
  92. public native void deliverMessage (long value);
  93. private android.os.Handler messageHandler = new android.os.Handler();
  94. public final void postMessage (long value)
  95. {
  96. messageHandler.post (new MessageCallback (value));
  97. }
  98. private final class MessageCallback implements Runnable
  99. {
  100. public MessageCallback (long value_) { value = value_; }
  101. public final void run() { deliverMessage (value); }
  102. private long value;
  103. }
  104. //==============================================================================
  105. private ViewHolder viewHolder;
  106. public final ComponentPeerView createNewView (boolean opaque)
  107. {
  108. ComponentPeerView v = new ComponentPeerView (this, opaque);
  109. viewHolder.addView (v);
  110. return v;
  111. }
  112. public final void deleteView (ComponentPeerView view)
  113. {
  114. ViewGroup group = (ViewGroup) (view.getParent());
  115. if (group != null)
  116. group.removeView (view);
  117. }
  118. final class ViewHolder extends ViewGroup
  119. {
  120. public ViewHolder (Context context)
  121. {
  122. super (context);
  123. setDescendantFocusability (ViewGroup.FOCUS_AFTER_DESCENDANTS);
  124. setFocusable (false);
  125. }
  126. protected final void onLayout (boolean changed, int left, int top, int right, int bottom)
  127. {
  128. setScreenSize (getWidth(), getHeight());
  129. if (isFirstResize)
  130. {
  131. isFirstResize = false;
  132. callAppLauncher();
  133. }
  134. }
  135. private boolean isFirstResize = true;
  136. }
  137. public final void excludeClipRegion (android.graphics.Canvas canvas, float left, float top, float right, float bottom)
  138. {
  139. canvas.clipRect (left, top, right, bottom, android.graphics.Region.Op.DIFFERENCE);
  140. }
  141. //==============================================================================
  142. public final String getClipboardContent()
  143. {
  144. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  145. return clipboard.getText().toString();
  146. }
  147. public final void setClipboardContent (String newText)
  148. {
  149. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  150. clipboard.setText (newText);
  151. }
  152. //==============================================================================
  153. public final void showMessageBox (String title, String message, final long callback)
  154. {
  155. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  156. builder.setTitle (title)
  157. .setMessage (message)
  158. .setCancelable (true)
  159. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  160. {
  161. public void onClick (DialogInterface dialog, int id)
  162. {
  163. dialog.cancel();
  164. JuceAppActivity.this.alertDismissed (callback, 0);
  165. }
  166. });
  167. builder.create().show();
  168. }
  169. public final void showOkCancelBox (String title, String message, final long callback)
  170. {
  171. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  172. builder.setTitle (title)
  173. .setMessage (message)
  174. .setCancelable (true)
  175. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  176. {
  177. public void onClick (DialogInterface dialog, int id)
  178. {
  179. dialog.cancel();
  180. JuceAppActivity.this.alertDismissed (callback, 1);
  181. }
  182. })
  183. .setNegativeButton ("Cancel", new DialogInterface.OnClickListener()
  184. {
  185. public void onClick (DialogInterface dialog, int id)
  186. {
  187. dialog.cancel();
  188. JuceAppActivity.this.alertDismissed (callback, 0);
  189. }
  190. });
  191. builder.create().show();
  192. }
  193. public final void showYesNoCancelBox (String title, String message, final long callback)
  194. {
  195. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  196. builder.setTitle (title)
  197. .setMessage (message)
  198. .setCancelable (true)
  199. .setPositiveButton ("Yes", new DialogInterface.OnClickListener()
  200. {
  201. public void onClick (DialogInterface dialog, int id)
  202. {
  203. dialog.cancel();
  204. JuceAppActivity.this.alertDismissed (callback, 1);
  205. }
  206. })
  207. .setNegativeButton ("No", new DialogInterface.OnClickListener()
  208. {
  209. public void onClick (DialogInterface dialog, int id)
  210. {
  211. dialog.cancel();
  212. JuceAppActivity.this.alertDismissed (callback, 2);
  213. }
  214. })
  215. .setNeutralButton ("Cancel", new DialogInterface.OnClickListener()
  216. {
  217. public void onClick (DialogInterface dialog, int id)
  218. {
  219. dialog.cancel();
  220. JuceAppActivity.this.alertDismissed (callback, 0);
  221. }
  222. });
  223. builder.create().show();
  224. }
  225. public native void alertDismissed (long callback, int id);
  226. //==============================================================================
  227. public final class ComponentPeerView extends ViewGroup
  228. implements View.OnFocusChangeListener
  229. {
  230. public ComponentPeerView (Context context, boolean opaque_)
  231. {
  232. super (context);
  233. setWillNotDraw (false);
  234. opaque = opaque_;
  235. setFocusable (true);
  236. setFocusableInTouchMode (true);
  237. setOnFocusChangeListener (this);
  238. requestFocus();
  239. }
  240. //==============================================================================
  241. private native void handlePaint (Canvas canvas);
  242. @Override
  243. public void draw (Canvas canvas)
  244. {
  245. super.draw (canvas);
  246. handlePaint (canvas);
  247. }
  248. @Override
  249. public boolean isOpaque()
  250. {
  251. return opaque;
  252. }
  253. private boolean opaque;
  254. //==============================================================================
  255. private native void handleMouseDown (float x, float y, long time);
  256. private native void handleMouseDrag (float x, float y, long time);
  257. private native void handleMouseUp (float x, float y, long time);
  258. @Override
  259. public boolean onTouchEvent (MotionEvent event)
  260. {
  261. switch (event.getAction())
  262. {
  263. case MotionEvent.ACTION_DOWN: handleMouseDown (event.getX(), event.getY(), event.getEventTime()); return true;
  264. case MotionEvent.ACTION_MOVE: handleMouseDrag (event.getX(), event.getY(), event.getEventTime()); return true;
  265. case MotionEvent.ACTION_CANCEL:
  266. case MotionEvent.ACTION_UP: handleMouseUp (event.getX(), event.getY(), event.getEventTime()); return true;
  267. default: break;
  268. }
  269. return false;
  270. }
  271. //==============================================================================
  272. @Override
  273. protected void onSizeChanged (int w, int h, int oldw, int oldh)
  274. {
  275. super.onSizeChanged (w, h, oldw, oldh);
  276. viewSizeChanged();
  277. }
  278. @Override
  279. protected void onLayout (boolean changed, int left, int top, int right, int bottom)
  280. {
  281. for (int i = getChildCount(); --i >= 0;)
  282. requestTransparentRegion (getChildAt (i));
  283. }
  284. private native void viewSizeChanged();
  285. @Override
  286. public void onFocusChange (View v, boolean hasFocus)
  287. {
  288. if (v == this)
  289. focusChanged (hasFocus);
  290. }
  291. private native void focusChanged (boolean hasFocus);
  292. public void setViewName (String newName) {}
  293. public boolean isVisible() { return getVisibility() == VISIBLE; }
  294. public void setVisible (boolean b) { setVisibility (b ? VISIBLE : INVISIBLE); }
  295. public boolean containsPoint (int x, int y)
  296. {
  297. return true; //xxx needs to check overlapping views
  298. }
  299. public OpenGLView createGLView()
  300. {
  301. OpenGLView glView = new OpenGLView (getContext());
  302. addView (glView);
  303. return glView;
  304. }
  305. }
  306. //==============================================================================
  307. public final class OpenGLView extends GLSurfaceView
  308. implements GLSurfaceView.Renderer
  309. {
  310. OpenGLView (Context context)
  311. {
  312. super (context);
  313. setEGLContextClientVersion (2);
  314. setRenderer (this);
  315. setRenderMode (RENDERMODE_WHEN_DIRTY);
  316. }
  317. @Override
  318. public void onSurfaceCreated (GL10 unused, EGLConfig config)
  319. {
  320. contextCreated();
  321. }
  322. @Override
  323. public void onSurfaceChanged (GL10 unused, int width, int height)
  324. {
  325. contextChangedSize();
  326. }
  327. @Override
  328. public void onDrawFrame (GL10 unused)
  329. {
  330. render();
  331. }
  332. private native void contextCreated();
  333. private native void contextChangedSize();
  334. private native void render();
  335. }
  336. //==============================================================================
  337. public final int[] renderGlyph (char glyph, Paint paint, android.graphics.Matrix matrix, Rect bounds)
  338. {
  339. Path p = new Path();
  340. paint.getTextPath (String.valueOf (glyph), 0, 1, 0.0f, 0.0f, p);
  341. RectF boundsF = new RectF();
  342. p.computeBounds (boundsF, true);
  343. matrix.mapRect (boundsF);
  344. boundsF.roundOut (bounds);
  345. bounds.left--;
  346. bounds.right++;
  347. final int w = bounds.width();
  348. final int h = Math.max (1, bounds.height());
  349. Bitmap bm = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
  350. Canvas c = new Canvas (bm);
  351. matrix.postTranslate (-bounds.left, -bounds.top);
  352. c.setMatrix (matrix);
  353. c.drawPath (p, paint);
  354. final int sizeNeeded = w * h;
  355. if (cachedRenderArray.length < sizeNeeded)
  356. cachedRenderArray = new int [sizeNeeded];
  357. bm.getPixels (cachedRenderArray, 0, w, 0, 0, w, h);
  358. bm.recycle();
  359. return cachedRenderArray;
  360. }
  361. private int[] cachedRenderArray = new int [256];
  362. //==============================================================================
  363. public static class HTTPStream
  364. {
  365. public HTTPStream (HttpURLConnection connection_) throws IOException
  366. {
  367. connection = connection_;
  368. inputStream = new BufferedInputStream (connection.getInputStream());
  369. }
  370. public final void release()
  371. {
  372. try
  373. {
  374. inputStream.close();
  375. }
  376. catch (IOException e)
  377. {}
  378. connection.disconnect();
  379. }
  380. public final int read (byte[] buffer, int numBytes)
  381. {
  382. int num = 0;
  383. try
  384. {
  385. num = inputStream.read (buffer, 0, numBytes);
  386. }
  387. catch (IOException e)
  388. {}
  389. if (num > 0)
  390. position += num;
  391. return num;
  392. }
  393. public final long getPosition() { return position; }
  394. public final long getTotalLength() { return -1; }
  395. public final boolean isExhausted() { return false; }
  396. public final boolean setPosition (long newPos) { return false; }
  397. private HttpURLConnection connection;
  398. private InputStream inputStream;
  399. private long position;
  400. }
  401. public static final HTTPStream createHTTPStream (String address, boolean isPost, byte[] postData,
  402. String headers, int timeOutMs,
  403. java.lang.StringBuffer responseHeaders)
  404. {
  405. try
  406. {
  407. HttpURLConnection connection = (HttpURLConnection) (new URL (address).openConnection());
  408. if (connection != null)
  409. {
  410. try
  411. {
  412. if (isPost)
  413. {
  414. connection.setConnectTimeout (timeOutMs);
  415. connection.setDoOutput (true);
  416. connection.setChunkedStreamingMode (0);
  417. OutputStream out = connection.getOutputStream();
  418. out.write (postData);
  419. out.flush();
  420. }
  421. return new HTTPStream (connection);
  422. }
  423. catch (Throwable e)
  424. {
  425. connection.disconnect();
  426. }
  427. }
  428. }
  429. catch (Throwable e)
  430. {}
  431. return null;
  432. }
  433. public final void launchURL (String url)
  434. {
  435. startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse (url)));
  436. }
  437. public static final String getLocaleValue (boolean isRegion)
  438. {
  439. java.util.Locale locale = java.util.Locale.getDefault();
  440. return isRegion ? locale.getDisplayCountry (java.util.Locale.US)
  441. : locale.getDisplayLanguage (java.util.Locale.US);
  442. }
  443. //==============================================================================
  444. private final class SingleMediaScanner implements MediaScannerConnectionClient
  445. {
  446. public SingleMediaScanner (Context context, String filename)
  447. {
  448. file = filename;
  449. msc = new MediaScannerConnection (context, this);
  450. msc.connect();
  451. }
  452. @Override
  453. public void onMediaScannerConnected()
  454. {
  455. msc.scanFile (file, null);
  456. }
  457. @Override
  458. public void onScanCompleted (String path, Uri uri)
  459. {
  460. msc.disconnect();
  461. }
  462. private MediaScannerConnection msc;
  463. private String file;
  464. }
  465. public final void scanFile (String filename)
  466. {
  467. new SingleMediaScanner (this, filename);
  468. }
  469. }