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.

917 lines
31KB

  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 android.util.Log;
  37. import java.io.*;
  38. import java.net.URL;
  39. import java.net.HttpURLConnection;
  40. import javax.microedition.khronos.egl.EGLConfig;
  41. import javax.microedition.khronos.opengles.GL10;
  42. import android.media.AudioManager;
  43. import android.media.MediaScannerConnection;
  44. import android.media.MediaScannerConnection.MediaScannerConnectionClient;
  45. //==============================================================================
  46. public class JuceAppActivity extends Activity
  47. {
  48. //==============================================================================
  49. static
  50. {
  51. System.loadLibrary ("juce_jni");
  52. }
  53. @Override
  54. public void onCreate (Bundle savedInstanceState)
  55. {
  56. super.onCreate (savedInstanceState);
  57. viewHolder = new ViewHolder (this);
  58. setContentView (viewHolder);
  59. setVolumeControlStream (AudioManager.STREAM_MUSIC);
  60. }
  61. @Override
  62. protected void onDestroy()
  63. {
  64. quitApp();
  65. super.onDestroy();
  66. clearDataCache();
  67. }
  68. @Override
  69. protected void onPause()
  70. {
  71. if (viewHolder != null)
  72. viewHolder.onPause();
  73. suspendApp();
  74. super.onPause();
  75. }
  76. @Override
  77. protected void onResume()
  78. {
  79. super.onResume();
  80. if (viewHolder != null)
  81. viewHolder.onResume();
  82. resumeApp();
  83. }
  84. @Override
  85. public void onConfigurationChanged (Configuration cfg)
  86. {
  87. super.onConfigurationChanged (cfg);
  88. setContentView (viewHolder);
  89. }
  90. private void callAppLauncher()
  91. {
  92. launchApp (getApplicationInfo().publicSourceDir,
  93. getApplicationInfo().dataDir);
  94. }
  95. //==============================================================================
  96. private native void launchApp (String appFile, String appDataDir);
  97. private native void quitApp();
  98. private native void suspendApp();
  99. private native void resumeApp();
  100. private native void setScreenSize (int screenWidth, int screenHeight, int dpi);
  101. //==============================================================================
  102. public native void deliverMessage (long value);
  103. private android.os.Handler messageHandler = new android.os.Handler();
  104. public final void postMessage (long value)
  105. {
  106. messageHandler.post (new MessageCallback (value));
  107. }
  108. private final class MessageCallback implements Runnable
  109. {
  110. public MessageCallback (long value_) { value = value_; }
  111. public final void run() { deliverMessage (value); }
  112. private long value;
  113. }
  114. //==============================================================================
  115. private ViewHolder viewHolder;
  116. public final ComponentPeerView createNewView (boolean opaque, long host)
  117. {
  118. ComponentPeerView v = new ComponentPeerView (this, opaque, host);
  119. viewHolder.addView (v);
  120. return v;
  121. }
  122. public final void deleteView (ComponentPeerView view)
  123. {
  124. ViewGroup group = (ViewGroup) (view.getParent());
  125. if (group != null)
  126. group.removeView (view);
  127. }
  128. public final void deleteOpenGLView (OpenGLView view)
  129. {
  130. ViewGroup group = (ViewGroup) (view.getParent());
  131. if (group != null)
  132. group.removeView (view);
  133. }
  134. final class ViewHolder extends ViewGroup
  135. {
  136. public ViewHolder (Context context)
  137. {
  138. super (context);
  139. setDescendantFocusability (ViewGroup.FOCUS_AFTER_DESCENDANTS);
  140. setFocusable (false);
  141. }
  142. protected final void onLayout (boolean changed, int left, int top, int right, int bottom)
  143. {
  144. setScreenSize (getWidth(), getHeight(), getDPI());
  145. if (isFirstResize)
  146. {
  147. isFirstResize = false;
  148. callAppLauncher();
  149. }
  150. }
  151. public final void onPause()
  152. {
  153. for (int i = getChildCount(); --i >= 0;)
  154. {
  155. View v = getChildAt (i);
  156. if (v instanceof ComponentPeerView)
  157. ((ComponentPeerView) v).onPause();
  158. }
  159. }
  160. public final void onResume()
  161. {
  162. for (int i = getChildCount(); --i >= 0;)
  163. {
  164. View v = getChildAt (i);
  165. if (v instanceof ComponentPeerView)
  166. ((ComponentPeerView) v).onResume();
  167. }
  168. }
  169. private final int getDPI()
  170. {
  171. DisplayMetrics metrics = new DisplayMetrics();
  172. getWindowManager().getDefaultDisplay().getMetrics (metrics);
  173. return metrics.densityDpi;
  174. }
  175. private boolean isFirstResize = true;
  176. }
  177. public final void excludeClipRegion (android.graphics.Canvas canvas, float left, float top, float right, float bottom)
  178. {
  179. canvas.clipRect (left, top, right, bottom, android.graphics.Region.Op.DIFFERENCE);
  180. }
  181. //==============================================================================
  182. public final String getClipboardContent()
  183. {
  184. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  185. return clipboard.getText().toString();
  186. }
  187. public final void setClipboardContent (String newText)
  188. {
  189. ClipboardManager clipboard = (ClipboardManager) getSystemService (CLIPBOARD_SERVICE);
  190. clipboard.setText (newText);
  191. }
  192. //==============================================================================
  193. public final void showMessageBox (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 ("OK", new DialogInterface.OnClickListener()
  200. {
  201. public void onClick (DialogInterface dialog, int id)
  202. {
  203. dialog.cancel();
  204. JuceAppActivity.this.alertDismissed (callback, 0);
  205. }
  206. });
  207. builder.create().show();
  208. }
  209. public final void showOkCancelBox (String title, String message, final long callback)
  210. {
  211. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  212. builder.setTitle (title)
  213. .setMessage (message)
  214. .setCancelable (true)
  215. .setPositiveButton ("OK", new DialogInterface.OnClickListener()
  216. {
  217. public void onClick (DialogInterface dialog, int id)
  218. {
  219. dialog.cancel();
  220. JuceAppActivity.this.alertDismissed (callback, 1);
  221. }
  222. })
  223. .setNegativeButton ("Cancel", new DialogInterface.OnClickListener()
  224. {
  225. public void onClick (DialogInterface dialog, int id)
  226. {
  227. dialog.cancel();
  228. JuceAppActivity.this.alertDismissed (callback, 0);
  229. }
  230. });
  231. builder.create().show();
  232. }
  233. public final void showYesNoCancelBox (String title, String message, final long callback)
  234. {
  235. AlertDialog.Builder builder = new AlertDialog.Builder (this);
  236. builder.setTitle (title)
  237. .setMessage (message)
  238. .setCancelable (true)
  239. .setPositiveButton ("Yes", new DialogInterface.OnClickListener()
  240. {
  241. public void onClick (DialogInterface dialog, int id)
  242. {
  243. dialog.cancel();
  244. JuceAppActivity.this.alertDismissed (callback, 1);
  245. }
  246. })
  247. .setNegativeButton ("No", new DialogInterface.OnClickListener()
  248. {
  249. public void onClick (DialogInterface dialog, int id)
  250. {
  251. dialog.cancel();
  252. JuceAppActivity.this.alertDismissed (callback, 2);
  253. }
  254. })
  255. .setNeutralButton ("Cancel", new DialogInterface.OnClickListener()
  256. {
  257. public void onClick (DialogInterface dialog, int id)
  258. {
  259. dialog.cancel();
  260. JuceAppActivity.this.alertDismissed (callback, 0);
  261. }
  262. });
  263. builder.create().show();
  264. }
  265. public native void alertDismissed (long callback, int id);
  266. //==============================================================================
  267. public final class ComponentPeerView extends ViewGroup
  268. implements View.OnFocusChangeListener
  269. {
  270. public ComponentPeerView (Context context, boolean opaque_, long host)
  271. {
  272. super (context);
  273. this.host = host;
  274. setWillNotDraw (false);
  275. opaque = opaque_;
  276. setFocusable (true);
  277. setFocusableInTouchMode (true);
  278. setOnFocusChangeListener (this);
  279. requestFocus();
  280. }
  281. //==============================================================================
  282. private native void handlePaint (long host, Canvas canvas);
  283. @Override
  284. public void onDraw (Canvas canvas)
  285. {
  286. handlePaint (host, canvas);
  287. }
  288. @Override
  289. public boolean isOpaque()
  290. {
  291. return opaque;
  292. }
  293. private boolean opaque;
  294. private long host;
  295. //==============================================================================
  296. private native void handleMouseDown (long host, int index, float x, float y, long time);
  297. private native void handleMouseDrag (long host, int index, float x, float y, long time);
  298. private native void handleMouseUp (long host, int index, float x, float y, long time);
  299. @Override
  300. public boolean onTouchEvent (MotionEvent event)
  301. {
  302. int action = event.getAction();
  303. long time = event.getEventTime();
  304. switch (action & MotionEvent.ACTION_MASK)
  305. {
  306. case MotionEvent.ACTION_DOWN:
  307. handleMouseDown (host, event.getPointerId(0), event.getX(), event.getY(), time);
  308. return true;
  309. case MotionEvent.ACTION_CANCEL:
  310. case MotionEvent.ACTION_UP:
  311. handleMouseUp (host, event.getPointerId(0), event.getX(), event.getY(), time);
  312. return true;
  313. case MotionEvent.ACTION_MOVE:
  314. {
  315. int n = event.getPointerCount();
  316. for (int i = 0; i < n; ++i)
  317. handleMouseDrag (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  318. return true;
  319. }
  320. case MotionEvent.ACTION_POINTER_UP:
  321. {
  322. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  323. handleMouseUp (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  324. return true;
  325. }
  326. case MotionEvent.ACTION_POINTER_DOWN:
  327. {
  328. int i = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
  329. handleMouseDown (host, event.getPointerId(i), event.getX(i), event.getY(i), time);
  330. return true;
  331. }
  332. default:
  333. break;
  334. }
  335. return false;
  336. }
  337. //==============================================================================
  338. private native void handleKeyDown (long host, int keycode, int textchar);
  339. private native void handleKeyUp (long host, int keycode, int textchar);
  340. public void showKeyboard (String type)
  341. {
  342. InputMethodManager imm = (InputMethodManager) getSystemService (Context.INPUT_METHOD_SERVICE);
  343. if (imm != null)
  344. {
  345. if (type.length() > 0)
  346. {
  347. imm.showSoftInput (this, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
  348. imm.setInputMethod (getWindowToken(), type);
  349. }
  350. else
  351. {
  352. imm.hideSoftInputFromWindow (getWindowToken(), 0);
  353. }
  354. }
  355. }
  356. @Override
  357. public boolean onKeyDown (int keyCode, KeyEvent event)
  358. {
  359. switch (keyCode)
  360. {
  361. case KeyEvent.KEYCODE_VOLUME_UP:
  362. case KeyEvent.KEYCODE_VOLUME_DOWN:
  363. return super.onKeyDown (keyCode, event);
  364. default: break;
  365. }
  366. handleKeyDown (host, keyCode, event.getUnicodeChar());
  367. return true;
  368. }
  369. @Override
  370. public boolean onKeyUp (int keyCode, KeyEvent event)
  371. {
  372. handleKeyUp (host, keyCode, event.getUnicodeChar());
  373. return true;
  374. }
  375. @Override
  376. public boolean onKeyMultiple (int keyCode, int count, KeyEvent event)
  377. {
  378. if (keyCode != KeyEvent.KEYCODE_UNKNOWN || event.getAction() != KeyEvent.ACTION_MULTIPLE)
  379. return super.onKeyMultiple (keyCode, count, event);
  380. if (event.getCharacters() != null)
  381. {
  382. int utf8Char = event.getCharacters().codePointAt (0);
  383. handleKeyDown (host, utf8Char, utf8Char);
  384. return true;
  385. }
  386. return false;
  387. }
  388. // this is here to make keyboard entry work on a Galaxy Tab2 10.1
  389. @Override
  390. public InputConnection onCreateInputConnection (EditorInfo outAttrs)
  391. {
  392. outAttrs.actionLabel = "";
  393. outAttrs.hintText = "";
  394. outAttrs.initialCapsMode = 0;
  395. outAttrs.initialSelEnd = outAttrs.initialSelStart = -1;
  396. outAttrs.label = "";
  397. outAttrs.imeOptions = EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI;
  398. outAttrs.inputType = InputType.TYPE_NULL;
  399. return new BaseInputConnection (this, false);
  400. }
  401. //==============================================================================
  402. @Override
  403. protected void onSizeChanged (int w, int h, int oldw, int oldh)
  404. {
  405. super.onSizeChanged (w, h, oldw, oldh);
  406. viewSizeChanged (host);
  407. }
  408. @Override
  409. protected void onLayout (boolean changed, int left, int top, int right, int bottom)
  410. {
  411. for (int i = getChildCount(); --i >= 0;)
  412. requestTransparentRegion (getChildAt (i));
  413. }
  414. private native void viewSizeChanged (long host);
  415. @Override
  416. public void onFocusChange (View v, boolean hasFocus)
  417. {
  418. if (v == this)
  419. focusChanged (host, hasFocus);
  420. }
  421. private native void focusChanged (long host, boolean hasFocus);
  422. public void setViewName (String newName) {}
  423. public boolean isVisible() { return getVisibility() == VISIBLE; }
  424. public void setVisible (boolean b) { setVisibility (b ? VISIBLE : INVISIBLE); }
  425. public boolean containsPoint (int x, int y)
  426. {
  427. return true; //xxx needs to check overlapping views
  428. }
  429. public final void onPause()
  430. {
  431. for (int i = getChildCount(); --i >= 0;)
  432. {
  433. View v = getChildAt (i);
  434. if (v instanceof OpenGLView)
  435. ((OpenGLView) v).onPause();
  436. }
  437. }
  438. public final void onResume()
  439. {
  440. for (int i = getChildCount(); --i >= 0;)
  441. {
  442. View v = getChildAt (i);
  443. if (v instanceof OpenGLView)
  444. ((OpenGLView) v).onResume();
  445. }
  446. }
  447. public OpenGLView createGLView()
  448. {
  449. OpenGLView glView = new OpenGLView (getContext());
  450. addView (glView);
  451. return glView;
  452. }
  453. }
  454. //==============================================================================
  455. public final class OpenGLView extends GLSurfaceView
  456. implements GLSurfaceView.Renderer
  457. {
  458. OpenGLView (Context context)
  459. {
  460. super (context);
  461. setEGLContextClientVersion (2);
  462. setRenderer (this);
  463. setRenderMode (RENDERMODE_WHEN_DIRTY);
  464. }
  465. @Override
  466. public void onSurfaceCreated (GL10 unused, EGLConfig config)
  467. {
  468. contextCreated();
  469. }
  470. @Override
  471. public void onSurfaceChanged (GL10 unused, int width, int height)
  472. {
  473. contextChangedSize();
  474. }
  475. @Override
  476. public void onDrawFrame (GL10 unused)
  477. {
  478. render();
  479. }
  480. private native void contextCreated();
  481. private native void contextChangedSize();
  482. private native void render();
  483. }
  484. //==============================================================================
  485. public final int[] renderGlyph (char glyph, Paint paint, android.graphics.Matrix matrix, Rect bounds)
  486. {
  487. Path p = new Path();
  488. paint.getTextPath (String.valueOf (glyph), 0, 1, 0.0f, 0.0f, p);
  489. RectF boundsF = new RectF();
  490. p.computeBounds (boundsF, true);
  491. matrix.mapRect (boundsF);
  492. boundsF.roundOut (bounds);
  493. bounds.left--;
  494. bounds.right++;
  495. final int w = bounds.width();
  496. final int h = Math.max (1, bounds.height());
  497. Bitmap bm = Bitmap.createBitmap (w, h, Bitmap.Config.ARGB_8888);
  498. Canvas c = new Canvas (bm);
  499. matrix.postTranslate (-bounds.left, -bounds.top);
  500. c.setMatrix (matrix);
  501. c.drawPath (p, paint);
  502. final int sizeNeeded = w * h;
  503. if (cachedRenderArray.length < sizeNeeded)
  504. cachedRenderArray = new int [sizeNeeded];
  505. bm.getPixels (cachedRenderArray, 0, w, 0, 0, w, h);
  506. bm.recycle();
  507. return cachedRenderArray;
  508. }
  509. private int[] cachedRenderArray = new int [256];
  510. //==============================================================================
  511. public static class HTTPStream
  512. {
  513. public HTTPStream (HttpURLConnection connection_,
  514. int[] statusCode, StringBuffer responseHeaders) throws IOException
  515. {
  516. connection = connection_;
  517. try
  518. {
  519. inputStream = new BufferedInputStream (connection.getInputStream());
  520. }
  521. catch (IOException e)
  522. {
  523. if (connection.getResponseCode() < org.apache.http.HttpStatus.SC_BAD_REQUEST)
  524. throw e;
  525. }
  526. finally
  527. {
  528. statusCode[0] = connection.getResponseCode();
  529. }
  530. if (statusCode[0] >= org.apache.http.HttpStatus.SC_BAD_REQUEST)
  531. inputStream = connection.getErrorStream();
  532. else
  533. inputStream = connection.getInputStream();
  534. for (java.util.Map.Entry<String, java.util.List<String>> entry : connection.getHeaderFields().entrySet())
  535. if (entry.getKey() != null && entry.getValue() != null)
  536. responseHeaders.append (entry.getKey() + ": "
  537. + android.text.TextUtils.join (",", entry.getValue()) + "\n");
  538. }
  539. public final void release()
  540. {
  541. try
  542. {
  543. inputStream.close();
  544. }
  545. catch (IOException e)
  546. {}
  547. connection.disconnect();
  548. }
  549. public final int read (byte[] buffer, int numBytes)
  550. {
  551. int num = 0;
  552. try
  553. {
  554. num = inputStream.read (buffer, 0, numBytes);
  555. }
  556. catch (IOException e)
  557. {}
  558. if (num > 0)
  559. position += num;
  560. return num;
  561. }
  562. public final long getPosition() { return position; }
  563. public final long getTotalLength() { return -1; }
  564. public final boolean isExhausted() { return false; }
  565. public final boolean setPosition (long newPos) { return false; }
  566. private HttpURLConnection connection;
  567. private InputStream inputStream;
  568. private long position;
  569. }
  570. public static final HTTPStream createHTTPStream (String address,
  571. boolean isPost, byte[] postData, String headers,
  572. int timeOutMs, int[] statusCode,
  573. StringBuffer responseHeaders,
  574. int numRedirectsToFollow)
  575. {
  576. // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL)
  577. if (timeOutMs < 0)
  578. timeOutMs = 0;
  579. else if (timeOutMs == 0)
  580. timeOutMs = 30000;
  581. // 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.
  582. // So convert headers string to an array, with an element for each line
  583. String headerLines[] = headers.split("\\n");
  584. for (;;)
  585. {
  586. try
  587. {
  588. HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());
  589. if (connection != null)
  590. {
  591. try
  592. {
  593. connection.setInstanceFollowRedirects (false);
  594. connection.setConnectTimeout (timeOutMs);
  595. connection.setReadTimeout (timeOutMs);
  596. // Set request headers
  597. for (int i = 0; i < headerLines.length; ++i)
  598. {
  599. int pos = headerLines[i].indexOf (":");
  600. if (pos > 0 && pos < headerLines[i].length())
  601. {
  602. String field = headerLines[i].substring (0, pos);
  603. String value = headerLines[i].substring (pos + 1);
  604. if (value.length() > 0)
  605. connection.setRequestProperty (field, value);
  606. }
  607. }
  608. if (isPost)
  609. {
  610. connection.setRequestMethod ("POST");
  611. connection.setDoOutput (true);
  612. if (postData != null)
  613. {
  614. OutputStream out = connection.getOutputStream();
  615. out.write(postData);
  616. out.flush();
  617. }
  618. }
  619. HTTPStream httpStream = new HTTPStream (connection, statusCode, responseHeaders);
  620. // Process redirect & continue as necessary
  621. int status = statusCode[0];
  622. if (--numRedirectsToFollow >= 0
  623. && (status == 301 || status == 302 || status == 303 || status == 307))
  624. {
  625. // Assumes only one occurrence of "Location"
  626. int pos1 = responseHeaders.indexOf ("Location:") + 10;
  627. int pos2 = responseHeaders.indexOf ("\n", pos1);
  628. if (pos2 > pos1)
  629. {
  630. String newLocation = responseHeaders.substring(pos1, pos2);
  631. // Handle newLocation whether it's absolute or relative
  632. URL baseUrl = new URL (address);
  633. URL newUrl = new URL (baseUrl, newLocation);
  634. String transformedNewLocation = newUrl.toString();
  635. if (transformedNewLocation != address)
  636. {
  637. address = transformedNewLocation;
  638. // Clear responseHeaders before next iteration
  639. responseHeaders.delete (0, responseHeaders.length());
  640. continue;
  641. }
  642. }
  643. }
  644. return httpStream;
  645. }
  646. catch (Throwable e)
  647. {
  648. connection.disconnect();
  649. }
  650. }
  651. }
  652. catch (Throwable e) {}
  653. return null;
  654. }
  655. }
  656. public final void launchURL (String url)
  657. {
  658. startActivity (new Intent (Intent.ACTION_VIEW, Uri.parse (url)));
  659. }
  660. public static final String getLocaleValue (boolean isRegion)
  661. {
  662. java.util.Locale locale = java.util.Locale.getDefault();
  663. return isRegion ? locale.getDisplayCountry (java.util.Locale.US)
  664. : locale.getDisplayLanguage (java.util.Locale.US);
  665. }
  666. //==============================================================================
  667. private final class SingleMediaScanner implements MediaScannerConnectionClient
  668. {
  669. public SingleMediaScanner (Context context, String filename)
  670. {
  671. file = filename;
  672. msc = new MediaScannerConnection (context, this);
  673. msc.connect();
  674. }
  675. @Override
  676. public void onMediaScannerConnected()
  677. {
  678. msc.scanFile (file, null);
  679. }
  680. @Override
  681. public void onScanCompleted (String path, Uri uri)
  682. {
  683. msc.disconnect();
  684. }
  685. private MediaScannerConnection msc;
  686. private String file;
  687. }
  688. public final void scanFile (String filename)
  689. {
  690. new SingleMediaScanner (this, filename);
  691. }
  692. public final Typeface getTypeFaceFromAsset (String assetName)
  693. {
  694. try
  695. {
  696. return Typeface.createFromAsset (this.getResources().getAssets(), assetName);
  697. }
  698. catch (Throwable e) {}
  699. return null;
  700. }
  701. final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
  702. public static String bytesToHex (byte[] bytes)
  703. {
  704. char[] hexChars = new char[bytes.length * 2];
  705. for (int j = 0; j < bytes.length; ++j)
  706. {
  707. int v = bytes[j] & 0xff;
  708. hexChars[j * 2] = hexArray[v >>> 4];
  709. hexChars[j * 2 + 1] = hexArray[v & 0x0f];
  710. }
  711. return new String (hexChars);
  712. }
  713. final private java.util.Map dataCache = new java.util.HashMap();
  714. synchronized private final File getDataCacheFile (byte[] data)
  715. {
  716. try
  717. {
  718. java.security.MessageDigest digest = java.security.MessageDigest.getInstance ("MD5");
  719. digest.update (data);
  720. String key = bytesToHex (digest.digest());
  721. if (dataCache.containsKey (key))
  722. return (File) dataCache.get (key);
  723. File f = new File (this.getCacheDir(), "bindata_" + key);
  724. f.delete();
  725. FileOutputStream os = new FileOutputStream (f);
  726. os.write (data, 0, data.length);
  727. dataCache.put (key, f);
  728. return f;
  729. }
  730. catch (Throwable e) {}
  731. return null;
  732. }
  733. private final void clearDataCache()
  734. {
  735. java.util.Iterator it = dataCache.values().iterator();
  736. while (it.hasNext())
  737. {
  738. File f = (File) it.next();
  739. f.delete();
  740. }
  741. }
  742. public final Typeface getTypeFaceFromByteArray (byte[] data)
  743. {
  744. try
  745. {
  746. File f = getDataCacheFile (data);
  747. if (f != null)
  748. return Typeface.createFromFile (f);
  749. }
  750. catch (Exception e)
  751. {
  752. Log.e ("JUCE", e.toString());
  753. }
  754. return null;
  755. }
  756. }