public void sendError(String error) {
   Log.i(LCAT, "Sending error " + error);
   TiDict event = new TiDict();
   event.put("error", error);
   event.put("source", proxy);
   fireCallback(ON_ERROR, new Object[] {event});
 }
  public void onTextChanged(CharSequence s, int start, int before, int count) {
    String value = tv.getText().toString();
    TiDict data = new TiDict();
    data.put("value", value);

    proxy.internalSetDynamicValue("value", value, false);
    proxy.fireEvent("change", data);
  }
 public void setBackgroundFromProperties(TiDict props) {
   if (props.containsKey("backgroundImage")) {
     setBackgroundImageProperty(props, "backgroundImage");
   } else if (props.containsKey("backgroundColor")) {
     Integer bgColor = TiConvert.toColor(props, "backgroundColor", "opacity");
     setBackgroundColor(bgColor);
   }
 }
 public void fireScroll(int to) {
   if (hasListeners(EVENT_SCROLL)) {
     TiDict options = new TiDict();
     options.put("index", to);
     options.put("view", this);
     options.put("currentPage", getView().getCurrentPage());
     TiEventHelper.fireViewEvent(this, EVENT_SCROLL, options);
   }
 }
  public void send(Object userData) throws MethodNotSupportedException {
    // TODO consider using task manager
    final TiHTTPClient me = this;
    double totalLength = 0;
    needMultipart = false;

    if (userData != null) {
      if (userData instanceof TiDict) {
        TiDict data = (TiDict) userData;

        // first time through check if we need multipart for POST
        for (String key : data.keySet()) {
          Object value = data.get(key);
          if (value instanceof TiBaseFile || value instanceof TiBlob) {
            needMultipart = true;
          }
        }

        for (String key : data.keySet()) {
          Object value = data.get(key);

          if (method.equals("POST") || method.equals("PUT")) {
            if (value instanceof TiBaseFile || value instanceof TiBlob) {
              totalLength += addTitaniumFileAsPostData(key, value);
            } else {
              String str = TiConvert.toString(value);
              addPostData(key, str);
              totalLength += str.length();
            }
          } else if (method.equals("GET")) {
            uri = uri.buildUpon().appendQueryParameter(key, TiConvert.toString(value)).build();
          }
        }
      } else {
        addStringData(TiConvert.toString(userData));
      }
    }

    request = new DefaultHttpRequestFactory().newHttpRequest(method, uri.toString());
    for (String header : headers.keySet()) {
      request.setHeader(header, headers.get(header));
    }

    clientThread =
        new Thread(
            new ClientRunnable(totalLength),
            "TiHttpClient-" + httpClientThreadCounter.incrementAndGet());
    clientThread.setPriority(Thread.MIN_PRIORITY);
    clientThread.start();
    if (DBG) {
      Log.d(LCAT, "Leaving send()");
    }
  }
  public boolean onEditorAction(TextView v, int actionId, KeyEvent keyEvent) {
    String value = tv.getText().toString();
    TiDict data = new TiDict();
    data.put("value", value);

    proxy.internalSetDynamicValue("value", value, false);
    proxy.fireEvent("return", data);

    Boolean enableReturnKey = (Boolean) proxy.getDynamicValue("enableReturnKey");
    if (enableReturnKey != null && enableReturnKey && v.getText().length() == 0) {
      return true;
    }
    return false;
  }
Beispiel #7
0
  @Override
  public void processProperties(TiDict d) {
    super.processProperties(d);

    TextView tv = (TextView) getNativeView();
    // Only accept one, prefer text to title.
    if (d.containsKey("text")) {
      tv.setText(TiConvert.toString(d, "text"));
    } else if (d.containsKey("title")) { // TODO this may not need to be supported.
      tv.setText(TiConvert.toString(d, "title"));
    }

    if (d.containsKey("color")) {
      tv.setTextColor(TiConvert.toColor(d, "color"));
    }
    if (d.containsKey("highlightedColor")) {
      tv.setHighlightColor(TiConvert.toColor(d, "highlightedColor"));
    }
    if (d.containsKey("font")) {
      TiUIHelper.styleText(tv, d.getTiDict("font"));
    }
    if (d.containsKey("textAlign")) {
      String textAlign = d.getString("textAlign");
      setAlignment(tv, textAlign);
    }
    tv.invalidate();
  }
Beispiel #8
0
  protected TiDict eventToTiDict(SensorEvent event, long ts) {
    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];

    TiDict heading = new TiDict();
    heading.put("type", EVENT_HEADING);
    heading.put("timestamp", ts);
    heading.put("x", x);
    heading.put("y", y);
    heading.put("z", z);
    heading.put("magneticHeading", x);
    heading.put("accuracy", event.accuracy);
    if (DBG) {
      switch (event.accuracy) {
        case SensorManager.SENSOR_STATUS_UNRELIABLE:
          Log.i(LCAT, "Compass accuracy unreliable");
          break;
        case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
          Log.i(LCAT, "Compass accuracy low");
          break;
        case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
          Log.i(LCAT, "Compass accuracy medium");
          break;
        case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
          Log.i(LCAT, "Compass accuracy high");
          break;
        default:
          Log.w(LCAT, "Unknown compass accuracy value: " + event.accuracy);
      }
    }
    if (geomagneticField != null) {
      float trueHeading = x - geomagneticField.getDeclination();
      if (trueHeading < 0) {
        trueHeading = 360 - trueHeading;
      }

      heading.put("trueHeading", trueHeading);
    }
    TiDict data = new TiDict();
    data.put("heading", heading);

    return data;
  }
  @Override
  public void processProperties(TiDict d) {
    TiImageView view = getView();

    if (d.containsKey("images")) {
      Object o = d.get("images");
      if (o instanceof Object[]) {
        setImages((Object[]) o);
      }
    } else if (d.containsKey("url")) {
      Log.w(LCAT, "The url property of ImageView is deprecated, use image instead.");
      if (!d.containsKey("image")) {
        d.put("image", d.get("url"));
      }
    }
    if (d.containsKey("canScale")) {
      view.setCanScaleImage(TiConvert.toBoolean(d, "canScale"));
    }
    if (d.containsKey("enableZoomControls")) {
      view.setEnableZoomControls(TiConvert.toBoolean(d, "enableZoomControls"));
    }
    if (d.containsKey("image")) {
      Object image = d.get("image");
      if (image instanceof String) {
        String imageURL = TiConvert.toString(d, "image");
        if (URLUtil.isNetworkUrl(imageURL)) {
          synchronized (imageTokenGenerator) {
            token = imageTokenGenerator.incrementAndGet();
            getView().setImageDrawable(null);
            new BgImageLoader(getProxy().getTiContext(), null, null, token).load(imageURL);
          }
        } else {
          setImage(createBitmap(imageURL));
        }
      } else {
        setImage(createBitmap(image));
      }

    } else {
      getProxy().internalSetDynamicValue("image", null, false);
    }

    super.processProperties(d);
  }
Beispiel #10
0
  @Override
  public Object get(String name, Scriptable start) {
    if (this.has(name, start)) {
      return super.get(name, start);
    }
    if (target instanceof TiProxy) {
      TiDict constants = ((TiProxy) target).getConstants();
      if (constants != null) {
        if (constants.containsKey(name)) {
          Object value = constants.get(name);
          super.putConst(name, start, value);
          return value;
        }
      }
    }

    if (DBG) {
      Log.d(LCAT, "get name: " + name);
    }
    Object o = NOT_FOUND;

    // If starts with Capital letter see if there is a module for it.
    if (name.matches("^[A-Z].*") || name.matches("iPhone")) {
      Object p = loadModule(name);
      if (p != null) {
        o = new KrollObject(this, p);
        put(name, this, o);
        ((TiModule) p).postCreate();
      }
    } else {
      if (DBG) {
        Log.d(LCAT, "Start: " + start.getClassName() + " looking for method:" + name);
      }
      o = handleMethodOrProperty(name, start, true, null);
    }

    return o;
  }
Beispiel #11
0
  protected Object toNative(Object value, Class<?> target) {
    Object o = null;

    if (value instanceof String) {
      o = Context.jsToJava(value, target);
    } else if (value instanceof Double || value instanceof Integer) {
      o = Context.jsToJava(value, target);
    } else if (value instanceof Boolean) {
      o = Context.jsToJava(value, target);
    } else if (value instanceof Function) {
      if (DBG) {
        Log.i(LCAT, "Is a Function");
      }
      o = new KrollCallback(weakKrollContext.get(), this, (Function) value);
    } else if (value == null) {
      o = null;
    } else if (value instanceof Scriptable) {
      Scriptable svalue = (Scriptable) value;
      if (isArrayLike(svalue)) {
        o = toArray(svalue);
      } else if (value instanceof KrollObject) {
        o = ((KrollObject) value).target;
      } else if (svalue.getClassName().equals("Date")) {
        double time = (Double) ScriptableObject.callMethod(svalue, "getTime", new Object[0]);
        o = new Date((long) time);
      } else {
        TiDict args = new TiDict();
        o = args;

        Scriptable so = (Scriptable) value;
        for (Object key : so.getIds()) {
          Object v = so.get((String) key, so);
          v = toNative(v, Object.class);
          //					if (v instanceof Scriptable && isArrayLike((Scriptable) v)) {
          //						v = toArray((Scriptable) v);
          //					}
          if (DBG) {
            Log.i(LCAT, "Key: " + key + " value: " + v + " type: " + v.getClass().getName());
          }
          args.put((String) key, v);
        }
        // Log.w(LCAT, "Unhandled type conversion of Scriptable: value: " + value.toString() + "
        // type: " + value.getClass().getName());
      }
    } else {
      if (value.getClass().isArray()) {
        Object[] values = (Object[]) value;
        Object[] newValues = new Object[values.length];
        for (int i = 0; i < values.length; i++) {
          newValues[i] = toNative(values[i], Object.class);
        }
        o = newValues;
      } else {
        Log.w(
            LCAT,
            "Unhandled type conversion: value: "
                + value.toString()
                + " type: "
                + value.getClass().getName());
      }
    }

    return o;
  }
 private void fireChange(int index) {
   TiDict data = new TiDict();
   data.put("index", index);
   proxy.fireEvent("change", data);
 }
 private void fireLoad(String state) {
   TiDict data = new TiDict();
   data.put("state", state);
   proxy.fireEvent("load", data);
 }
  @Override
  public void processProperties(TiDict d) {
    super.processProperties(d);

    if (d.containsKey("enabled")) {
      tv.setEnabled(d.getBoolean("enabled"));
    }
    if (d.containsKey("value")) {
      tv.setText(d.getString("value"));
    }
    if (d.containsKey("color")) {
      tv.setTextColor(TiConvert.toColor(d, "color"));
    }
    if (d.containsKey("hintText")) {
      tv.setHint(d.getString("hintText"));
    }
    if (d.containsKey("font")) {
      TiUIHelper.styleText(tv, d.getTiDict("font"));
    }
    if (d.containsKey("textAlign") || d.containsKey("verticalAlign")) {
      String textAlign = null;
      String verticalAlign = null;
      if (d.containsKey("textAlign")) {
        textAlign = d.getString("textAlign");
      }
      if (d.containsKey("verticalAlign")) {
        verticalAlign = d.getString("verticalAlign");
      }
      handleTextAlign(textAlign, verticalAlign);
    }
    if (d.containsKey("returnKeyType")) {
      handleReturnKeyType(d.getInt("returnKeyType"));
    }
    if (d.containsKey("keyboardType")) {
      boolean autocorrect = true;
      if (d.containsKey("autocorrect")) {
        autocorrect = d.getBoolean("autocorrect");
      }
      handleKeyboardType(d.getInt("keyboardType"), autocorrect);
    }

    if (d.containsKey("autocapitalization")) {

      Capitalize autoCapValue = null;

      switch (d.getInt("autocapitalization")) {
        case TEXT_AUTOCAPITALIZATION_NONE:
          autoCapValue = Capitalize.NONE;
          break;

        case TEXT_AUTOCAPITALIZATION_ALL:
          autoCapValue = Capitalize.CHARACTERS;
          break;

        case TEXT_AUTOCAPITALIZATION_SENTENCES:
          autoCapValue = Capitalize.SENTENCES;
          break;

        case TEXT_AUTOCAPITALIZATION_WORDS:
          autoCapValue = Capitalize.WORDS;
          break;

        default:
          Log.w(
              LCAT, "Unknown AutoCapitalization Value [" + d.getString("autocapitalization") + "]");
          break;
      }

      if (null != autoCapValue) {
        tv.setKeyListener(TextKeyListener.getInstance(false, autoCapValue));
      }
    }

    if (d.containsKey("passwordMask")) {
      if (TiConvert.toBoolean(d.get("passwordMask"))) {
        // This shouldn't be needed but it's belts & braces
        tv.setKeyListener(TextKeyListener.getInstance(false, Capitalize.NONE));
        // Both setTransform & keyboard type are required
        tv.setTransformationMethod(PasswordTransformationMethod.getInstance());
        // We also need to set the keyboard type - otherwise the password mask won't be applied
        handleKeyboardType(KEYBOARD_PASSWORD, false);
      }
    }
  }
 @Override
 protected TiDict getFocusEventObject(boolean hasFocus) {
   TiDict event = new TiDict();
   event.put("value", tv.getText().toString());
   return event;
 }
Beispiel #16
0
  @SuppressWarnings("serial")
  public static Object fromNative(Object value, KrollContext kroll) {
    Object o = value;

    if (DBG) {
      if (value != null) {
        Log.d(LCAT, "Incoming type is " + value.getClass().getCanonicalName());
      }
    }
    if (value == null
        || value instanceof String
        || value instanceof Number
        || value instanceof Boolean
        || value instanceof Scriptable
        || value instanceof Function) {
      o = Context.javaToJS(value, kroll.getScope());
    } else if (value instanceof TiDict) {
      TiDict d = (TiDict) value;
      ScriptableObject so =
          new ScriptableObject(
              kroll.getScope(), ScriptableObject.getObjectPrototype(kroll.getScope())) {
            @Override
            public String getClassName() {
              return "Object";
            }

            public String toString() {
              StringBuilder sb = new StringBuilder();
              sb.append("{ ");

              Object[] ids = (Object[]) getIds();
              String sep = "";

              if (ids != null) {
                for (Object id : ids) {
                  sb.append(" '").append(id).append("' : ");
                  Object o = get(id.toString(), this);
                  if (o == null) {
                    sb.append("null");
                  } else if (o instanceof String) {
                    sb.append(" '").append((String) o).append("' ");
                  } else if (o instanceof Number) {
                    sb.append(o);
                  } else if (o instanceof ScriptableObject) {
                    sb.append(" {").append(o).append("} ");
                  } else {
                    sb.append(o);
                  }

                  sb.append("sep");
                  sep = ",";
                }
              }

              sb.append(" }");

              return sb.toString();
            }
          };
      for (String key : d.keySet()) {
        so.put(key, so, fromNative(d.get(key), kroll));
      }
      o = so;
    } else if (value instanceof Date) {
      Date date = (Date) value;
      o =
          Context.getCurrentContext()
              .newObject(kroll.getScope(), "Date", new Object[] {date.getTime()});
    } else if (value.getClass().isArray()) {
      int length = Array.getLength(value);
      Object[] jsArray = new Object[length];
      for (int i = 0; i < length; i++) {
        jsArray[i] = fromNative(Array.get(value, i), kroll);
      }

      o = Context.getCurrentContext().newObject(kroll.getScope(), "Array", jsArray);
    } else {
      o = new KrollObject(kroll, value);
    }

    return o;
  }
Beispiel #17
0
    public String handleResponse(HttpResponse response) throws HttpResponseException, IOException {
      connected = true;
      String clientResponse = null;

      if (client != null) {
        TiHTTPClient c = client.get();
        if (c != null) {
          c.response = response;
          c.setReadyState(READY_STATE_HEADERS_RECEIVED);
          c.setStatus(response.getStatusLine().getStatusCode());
          c.setStatusText(response.getStatusLine().getReasonPhrase());
          c.setReadyState(READY_STATE_LOADING);
        }

        if (DBG) {
          try {
            Log.w(LCAT, "Entity Type: " + response.getEntity().getClass());
            Log.w(LCAT, "Entity Content Type: " + response.getEntity().getContentType().getValue());
            Log.w(LCAT, "Entity isChunked: " + response.getEntity().isChunked());
            Log.w(LCAT, "Entity isStreaming: " + response.getEntity().isStreaming());
          } catch (Throwable t) {
            // Ignore
          }
        }

        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
          setResponseText(response.getEntity());
          throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
        }

        entity = response.getEntity();
        if (entity.getContentType() != null) {
          contentType = entity.getContentType().getValue();
        }
        KrollCallback onDataStreamCallback = c.getCallback(ON_DATA_STREAM);
        if (onDataStreamCallback != null) {
          is = entity.getContent();
          charset = EntityUtils.getContentCharSet(entity);

          responseData = null;

          if (is != null) {
            final KrollCallback cb = onDataStreamCallback;
            long contentLength = entity.getContentLength();
            if (DBG) {
              Log.d(LCAT, "Content length: " + contentLength);
            }
            int count = 0;
            int totalSize = 0;
            byte[] buf = new byte[4096];
            if (DBG) {
              Log.d(LCAT, "Available: " + is.available());
            }
            if (aborted) {
              if (entity != null) {
                entity.consumeContent();
              }
            } else {
              while ((count = is.read(buf)) != -1) {
                totalSize += count;
                TiDict o = new TiDict();
                o.put("totalCount", contentLength);
                o.put("totalSize", totalSize);
                o.put("size", count);

                byte[] newbuf = new byte[count];
                System.arraycopy(buf, 0, newbuf, 0, count);
                if (responseData == null) {
                  responseData = TiBlob.blobFromData(proxy.getTiContext(), newbuf, contentType);
                } else {
                  responseData.append(TiBlob.blobFromData(proxy.getTiContext(), newbuf));
                }

                TiBlob blob = TiBlob.blobFromData(proxy.getTiContext(), newbuf);
                o.put("blob", blob);
                o.put("progress", ((double) totalSize) / ((double) contentLength));

                cb.callWithProperties(o);
              }
              if (entity != null) {
                try {
                  entity.consumeContent();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              }
            }
          }
        } else {
          setResponseData(entity);
        }
      }
      return clientResponse;
    }
  @Override
  public void propertyChanged(String key, Object oldValue, Object newValue, TiProxy proxy) {
    if (DBG) {
      Log.d(LCAT, "Property: " + key + " old: " + oldValue + " new: " + newValue);
    }
    if (key.equals("enabled")) {
      tv.setEnabled(TiConvert.toBoolean(newValue));
    } else if (key.equals("value")) {
      tv.setText((String) newValue);
    } else if (key.equals("color")) {
      tv.setTextColor(TiConvert.toColor((String) newValue));
    } else if (key.equals("passwordMask")) {
      if (TiConvert.toBoolean(newValue) == true) {
        // This shouldn't be needed but it's belts & braces
        tv.setKeyListener(TextKeyListener.getInstance(false, Capitalize.NONE));
        // Both setTransform & keyboard type are required
        tv.setTransformationMethod(PasswordTransformationMethod.getInstance());
        // We also need to set the keyboard type - otherwise the password mask won't be applied
        handleKeyboardType(KEYBOARD_PASSWORD, false);
      } else {
        handleKeyboardType(KEYBOARD_DEFAULT, false);
      }
    } else if (key.equals("hintText")) {
      tv.setHint((String) newValue);
    } else if (key.equals("textAlign") || key.equals("verticalAlign")) {
      String textAlign = null;
      String verticalAlign = null;
      if (key.equals("textAlign")) {
        textAlign = TiConvert.toString(newValue);
      }
      if (key.equals("verticalAlign")) {
        verticalAlign = TiConvert.toString(newValue);
      }
      handleTextAlign(textAlign, verticalAlign);
    } else if (key.equals("autocapitalization")) {

      // TODO Missing
      Capitalize autoCapValue = null;

      switch (TiConvert.toInt(newValue)) {
        case TEXT_AUTOCAPITALIZATION_NONE:
          autoCapValue = Capitalize.NONE;
          break;

        case TEXT_AUTOCAPITALIZATION_ALL:
          autoCapValue = Capitalize.CHARACTERS;
          break;

        case TEXT_AUTOCAPITALIZATION_SENTENCES:
          autoCapValue = Capitalize.SENTENCES;
          break;

        case TEXT_AUTOCAPITALIZATION_WORDS:
          autoCapValue = Capitalize.WORDS;
          break;

        default:
          Log.w(LCAT, "Unknown AutoCapitalization Value [" + TiConvert.toString(newValue) + "]");
          break;
      }

      if (null != autoCapValue) {
        tv.setKeyListener(TextKeyListener.getInstance(false, autoCapValue));
      }

    } else if (key.equals("keyboardType") || (key.equals("autocorrect"))) {
      TiDict d = proxy.getDynamicProperties();
      boolean autocorrect = false;
      if (d.containsKey("autocorrect")) {
        autocorrect = d.getBoolean("autocorrect");
      }

      handleKeyboardType(TiConvert.toInt(d, "keyboardType"), autocorrect);
    } else if (key.equals("returnKeyType")) {
      handleReturnKeyType(TiConvert.toInt(newValue));
    } else if (key.equals("font")) {
      TiUIHelper.styleText(tv, (TiDict) newValue);
    } else {
      super.propertyChanged(key, oldValue, newValue, proxy);
    }
  }