private void setImage(final Bitmap bitmap) {
   if (!TiApplication.isUIThread()) {
     TiMessenger.sendBlockingMainMessage(handler.obtainMessage(SET_IMAGE), bitmap);
   } else {
     handleSetImage(bitmap);
   }
 }
 @Kroll.getProperty
 @Kroll.method
 public KrollDict getCenter() {
   return (KrollDict)
       TiMessenger.sendBlockingMainMessage(
           getMainHandler().obtainMessage(MSG_GETCENTER), getActivity());
 }
  @Kroll.method
  public void add(TiViewProxy child) {
    if (child == null) {
      Log.w(LCAT, "add called with null child");
      return;
    }

    if (children == null) {
      children = new ArrayList<TiViewProxy>();
    }

    if (peekView() != null) {
      if (TiApplication.isUIThread()) {
        handleAdd(child);
        return;
      }

      TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_ADD_CHILD), child);

    } else {
      children.add(child);
      child.parent = new WeakReference<TiViewProxy>(this);
    }
    // TODO zOrder
  }
  @Kroll.method
  public void remove(TiViewProxy child) {
    if (child == null) {
      Log.w(LCAT, "add called with null child");

      return;
    }

    if (peekView() != null) {
      if (TiApplication.isUIThread()) {
        handleRemove(child);
        return;
      }

      TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_REMOVE_CHILD), child);

    } else {
      if (children != null) {
        children.remove(child);
        if (child.parent != null && child.parent.get() == this) {
          child.parent = null;
        }
      }
    }
  }
    @Override
    protected void onPostExecute(Drawable d) {
      super.onPostExecute(d);

      if (d != null) {
        final Drawable fDrawable = d;

        // setImageDrawable has to run in the UI thread since it updates the UI
        TiMessenger.getMainMessenger()
            .post(
                new Runnable() {
                  @Override
                  public void run() {
                    setImageDrawable(fDrawable, token);
                  }
                });

      } else {
        if (Log.isDebugModeEnabled()) {
          String traceMsg = "Background image load returned null";
          if (proxy.hasProperty(TiC.PROPERTY_IMAGE)) {
            Object image = proxy.getProperty(TiC.PROPERTY_IMAGE);
            if (image instanceof String) {
              traceMsg += " (" + TiConvert.toString(image) + ")";
            }
          }
          Log.d(TAG, traceMsg);
        }
      }
    }
 public void callAsync(final KrollObject krollObject, final Object[] args) {
   TiMessenger.postOnRuntime(
       new Runnable() {
         public void run() {
           call(krollObject, args);
         }
       });
 }
 @Kroll.method
 public void appendItems(Object data) {
   if (TiApplication.isUIThread()) {
     handleAppendItems(data);
   } else {
     TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_APPEND_ITEMS), data);
   }
 }
 @Kroll.method
 @Kroll.setProperty
 public void setItems(Object data) {
   if (TiApplication.isUIThread()) {
     handleSetItems(data);
   } else {
     TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_SET_ITEMS), data);
   }
 }
  public void setWindow(Object windowProxyObject) {
    if (KrollRuntime.getInstance().isRuntimeThread()) {
      doSetWindow(windowProxyObject);

    } else {
      TiMessenger.sendBlockingRuntimeMessage(
          handler.obtainMessage(MSG_SET_WINDOW), windowProxyObject);
    }
  }
  public Object call(KrollObject krollObject, Object[] args) {
    if (KrollRuntime.getInstance().isRuntimeThread()) {
      return callSync(krollObject, args);

    } else {
      return TiMessenger.sendBlockingRuntimeMessage(
          handler.obtainMessage(MSG_CALL_SYNC), new FunctionArgs(krollObject, args));
    }
  }
 @Kroll.method
 public KrollDict getItemAt(int index) {
   if (TiApplication.isUIThread()) {
     return handleGetItemAt(index);
   } else {
     return (KrollDict)
         TiMessenger.sendBlockingMainMessage(
             getMainHandler().obtainMessage(MSG_GET_ITEM_AT), index);
   }
 }
 @Kroll.method
 @Kroll.getProperty
 public Object[] getItems() {
   if (TiApplication.isUIThread()) {
     return itemProperties.toArray();
   } else {
     return (Object[])
         TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GET_ITEMS));
   }
 }
  /**
   * Sends a message to an {@link java.util.concurrent.ArrayBlockingQueue#ArrayBlockingQueue(int)
   * ArrayBlockingQueue}, and dispatch messages on the current queue while blocking on the passed in
   * AsyncResult. If maxTimeout > 0 and the cannot get the permission from the semaphore within
   * maxTimeout, throw an error and return.
   *
   * @param message The message to send.
   * @param targetMessenger The TiMessenger to send it to.
   * @param asyncArg argument to be added to the AsyncResult put on the message.
   * @param maxTimeout the maximum time to wait for a permit from the semaphore.
   * @return The getResult() value of the AsyncResult put on the message.
   */
  private Object sendBlockingMessage(
      Message message, TiMessenger targetMessenger, Object asyncArg, final long maxTimeout) {
    @SuppressWarnings("serial")
    AsyncResult wrappedAsyncResult =
        new AsyncResult(asyncArg) {
          @Override
          public Object getResult() {
            int timeout = 0;
            long elapsedTime = 0;
            try {
              // TODO: create a multi-semaphore condition
              // here so we don't unnecessarily poll
              while (!tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
                if (messageQueue.size() == 0) {
                  timeout = 50;
                } else {
                  dispatchPendingMessages();
                }

                elapsedTime += timeout;
                if (maxTimeout > 0 && elapsedTime > maxTimeout) {
                  setException(new Throwable("getResult() has timed out."));
                  break;
                }
              }
            } catch (InterruptedException e) {
              if (Log.isDebugModeEnabled()) {
                Log.e(TAG, "Interrupted waiting for async result", e);
              }
              dispatchPendingMessages();
            }

            if (exception != null && Log.isDebugModeEnabled()) {
              Log.e(TAG, "Unable to get the result from the blocking message.", exception);
            }

            return result;
          }

          @Override
          public void setResult(Object result) {
            super.setResult(result);
          }
        };

    blockingMessageCount.incrementAndGet();
    message.obj = wrappedAsyncResult;
    targetMessenger.sendMessage(message);

    Object messageResult = wrappedAsyncResult.getResult();
    blockingMessageCount.decrementAndGet();
    dispatchPendingMessages();

    return messageResult;
  }
    @Override
    protected Bitmap doInBackground(final ImageArgs... params) {
      final ImageArgs imageArgs = params[0];

      recycle = imageArgs.mRecycle;
      mNetworkURL = imageArgs.mNetworkURL;
      Bitmap bitmap = null;

      mUrl = imageArgs.mImageref.getUrl();

      if (mNetworkURL) {
        boolean getAsync = true;
        try {
          String imageUrl = TiUrl.getCleanUri(imageArgs.mImageref.getUrl()).toString();

          URI uri = new URI(imageUrl);
          getAsync = !TiResponseCache.peek(uri); // expensive, don't want to do in UI thread
        } catch (URISyntaxException e) {
          Log.e(TAG, "URISyntaxException for url " + imageArgs.mImageref.getUrl(), e);
          getAsync = false;
        } catch (NullPointerException e) {
          Log.e(TAG, "NullPointerException for url " + imageArgs.mImageref.getUrl(), e);
          getAsync = false;
        } catch (Exception e) {
          Log.e(TAG, "Caught exception for url" + imageArgs.mImageref.getUrl(), e);
        }
        if (getAsync) {
          //
          // We've got to start the download back on the UI thread, if we do it on one
          // of the AsyncTask threads it will throw an exception.
          //
          mAsync = true;

          TiMessenger.getMainMessenger()
              .post(
                  new Runnable() {
                    @Override
                    public void run() {
                      imageArgs.mImageref.getBitmapAsync(imageDownloadListener);
                    }
                  });

        } else {
          bitmap =
              (imageArgs.mImageref)
                  .getBitmap(
                      imageArgs.mView, imageArgs.mRequestedWidth, imageArgs.mRequestedHeight);
        }
      } else {
        bitmap =
            (imageArgs.mImageref)
                .getBitmap(imageArgs.mView, imageArgs.mRequestedWidth, imageArgs.mRequestedHeight);
      }
      return bitmap;
    }
Beispiel #15
0
  @Kroll.method
  public KrollDict toImage() {
    if (TiApplication.isUIThread()) {
      return handleToImage();

    } else {
      return (KrollDict)
          TiMessenger.sendBlockingMainMessage(
              getMainHandler().obtainMessage(MSG_TOIMAGE), getActivity());
    }
  }
Beispiel #16
0
  public TiUIView getOrCreateView() {
    if (activity == null || view != null) {
      return view;
    }

    if (TiApplication.isUIThread()) {
      return handleGetView();
    }

    return (TiUIView)
        TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GETVIEW), 0);
  }
 @Kroll.method
 public boolean canGoForward() {
   if (peekView() != null) {
     if (TiApplication.isUIThread()) {
       return getWebView().canGoForward();
     } else {
       return (Boolean)
           TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_CAN_GO_FORWARD));
     }
   }
   return false;
 }
  protected void handleSendMessage(int messageId) {
    try {
      Message message = TiMessenger.getMainMessenger().getHandler().obtainMessage(messageId, this);
      messenger.send(message);

    } catch (RemoteException e) {
      Log.e(TAG, "Unable to message creator. finishing.", e);
      finish();

    } catch (RuntimeException e) {
      Log.e(TAG, "Unable to message creator. finishing.", e);
      finish();
    }
  }
 @Kroll.method
 @Kroll.getProperty
 public String getUserAgent() {
   TiUIWebView currWebView = getWebView();
   if (currWebView != null) {
     if (TiApplication.isUIThread()) {
       return currWebView.getUserAgentString();
     } else {
       return (String)
           TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GET_USER_AGENT));
     }
   }
   return "";
 }
  protected void sendMessage(final int msgId) {
    if (messenger == null || msgId == -1) {
      return;
    }

    // fire an async message on this thread's queue
    // so we don't block onCreate() from returning
    TiMessenger.postOnMain(
        new Runnable() {
          public void run() {
            handleSendMessage(msgId);
          }
        });
  }
  @Kroll.method
  public void insertItemsAt(int index, Object data) {
    if (!isIndexValid(index)) {
      return;
    }

    if (TiApplication.isUIThread()) {
      handleInsertItemsAt(index, data);
    } else {
      KrollDict d = new KrollDict();
      d.put(TiC.PROPERTY_DATA, data);
      d.put(TiC.EVENT_PROPERTY_INDEX, index);
      TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_INSERT_ITEMS_AT), d);
    }
  }
  @Kroll.method
  public void deleteItemsAt(int index, int count) {
    if (!isIndexValid(index)) {
      return;
    }

    if (TiApplication.isUIThread()) {
      handleDeleteItemsAt(index, count);
    } else {
      KrollDict d = new KrollDict();
      d.put(TiC.EVENT_PROPERTY_INDEX, index);
      d.put(TiC.PROPERTY_COUNT, count);
      TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_DELETE_ITEMS_AT), d);
    }
  }
  @Kroll.method
  public void updateItemAt(int index, Object data) {
    if (!isIndexValid(index) || !(data instanceof HashMap)) {
      return;
    }

    if (TiApplication.isUIThread()) {
      handleUpdateItemAt(index, new Object[] {data});
    } else {
      KrollDict d = new KrollDict();
      d.put(TiC.EVENT_PROPERTY_INDEX, index);
      d.put(TiC.PROPERTY_DATA, new Object[] {data});
      TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_UPDATE_ITEM_AT), d);
    }
  }
Beispiel #24
0
  @Kroll.method
  public TiBlob getFilteredScreenshot(HashMap options) {
    if (options != null) {
      if (options.containsKey("callback")) {
        KrollFunction callback = (KrollFunction) options.get("callback");
        if (callback != null) {
          (new FilterScreenShotTask()).execute(options);
          return null;
        }
      }
    }

    //        View view = TiApplication.getAppCurrentActivity().getWindow()
    //                .getDecorView();
    View view =
        TiApplication.getAppCurrentActivity()
            .getWindow()
            .getDecorView()
            .findViewById(android.R.id.content);
    if (view == null) {
      return null;
    }

    Bitmap bitmap = null;
    try {
      if (TiApplication.isUIThread()) {
        bitmap = TiUIHelper.viewToBitmap(null, view);
      } else {
        bitmap =
            (Bitmap)
                TiMessenger.sendBlockingMainMessage(
                    getMainHandler().obtainMessage(MSG_GETVIEWIMAGE), view);
      }
      //            Rect statusBar = new Rect();
      //            view.getWindowVisibleDisplayFrame(statusBar);
      //            bitmap = Bitmap.createBitmap(bitmap, 0, statusBar.top,
      //                    bitmap.getWidth(), bitmap.getHeight() - statusBar.top,
      //                    null, true);
    } catch (Exception e) {
      bitmap = null;
    }
    return getFilteredImage(bitmap, options);
  }
 public KrollObject() {
   handler = new Handler(TiMessenger.getRuntimeMessenger().getLooper(), this);
 }
 private Handler getRuntimeHandler() {
   if (runtimeHandler == null) {
     runtimeHandler = new Handler(TiMessenger.getRuntimeMessenger().getLooper(), this);
   }
   return runtimeHandler;
 }
  public InputStream openInputStream(String path, boolean report) throws IOException {
    InputStream is = null;

    Context context = softContext.get();
    if (context != null) {
      if (isTitaniumResource(path)) {
        String[] parts = path.split(":");
        if (parts.length != 3) {
          Log.w(TAG, "Malformed titanium resource url, resource not loaded: " + path);
          return null;
        }
        @SuppressWarnings("unused")
        String titanium = parts[0];
        String section = parts[1];
        String resid = parts[2];

        if (TI_RESOURCE_PREFIX.equals(section)) {
          is =
              TiFileHelper.class.getResourceAsStream(
                  "/org/appcelerator/titanium/res/drawable/" + resid + ".png");
        } else if ("Sys".equals(section)) {
          Integer id = systemIcons.get(resid);
          if (id != null) {
            is = Resources.getSystem().openRawResource(id);
          } else {
            Log.w(TAG, "Drawable not found for system id: " + path);
          }
        } else {
          Log.e(TAG, "Unknown section identifier: " + section);
        }
      } else if (URLUtil.isNetworkUrl(path)) {
        if (TiApplication.isUIThread()) {
          is =
              (InputStream)
                  TiMessenger.sendBlockingRuntimeMessage(
                      getRuntimeHandler().obtainMessage(MSG_NETWORK_URL), path);
        } else {
          is = handleNetworkURL(path);
        }
      } else if (path.startsWith(RESOURCE_ROOT_ASSETS)) {
        path = path.substring(22); // length of "file:///android_asset/"
        boolean found = false;

        if (foundResourcePathCache.contains(path)) {
          found = true;
        } else if (!notFoundResourcePathCache.contains(path)) {
          String base = path.substring(0, path.lastIndexOf("/"));

          synchronized (resourcePathCache) {
            if (!resourcePathCache.contains(base)) {
              String[] paths = context.getAssets().list(base);
              for (int i = 0; i < paths.length; i++) {
                foundResourcePathCache.add(base + '/' + paths[i]);
              }
              resourcePathCache.add(base);
              if (foundResourcePathCache.contains(path)) {
                found = true;
              }
            }
            if (!found) {
              notFoundResourcePathCache.add(path);
            }
          }
        }
        if (found) {
          is = context.getAssets().open(path);
        } else throw new FileNotFoundException();
      } else if (path.startsWith(SD_CARD_PREFIX)) {
        File file = new File(path);
        if (file.exists()) {
          is = context.getAssets().open(path);
        } else throw new FileNotFoundException();
      } else if (URLUtil.isFileUrl(path)) {
        URL u = new URL(path);
        is = u.openStream();
      } else {
        path = joinPaths("Resources", path);
        is = context.getAssets().open(path);
      }
    }

    return is;
  }