<commit_before>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "jni_internal.h"
#include "class_linker.h"
#include "object.h"
#include "object_utils.h"
#include "reflection.h"

#include "JniConstants.h" // Last to avoid problems with LOG redefinition.

namespace art {

static bool GetFieldValue(Object* o, Field* f, JValue& value, bool allow_references) {
  ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
  if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) {
    return false;
  }
  switch (FieldHelper(f).GetTypeAsPrimitiveType()) {
  case Primitive::kPrimBoolean:
    value.z = f->GetBoolean(o);
    return true;
  case Primitive::kPrimByte:
    value.b = f->GetByte(o);
    return true;
  case Primitive::kPrimChar:
    value.c = f->GetChar(o);
    return true;
  case Primitive::kPrimDouble:
    value.d = f->GetDouble(o);
    return true;
  case Primitive::kPrimFloat:
    value.f = f->GetFloat(o);
    return true;
  case Primitive::kPrimInt:
    value.i = f->GetInt(o);
    return true;
  case Primitive::kPrimLong:
    value.j = f->GetLong(o);
    return true;
  case Primitive::kPrimShort:
    value.s = f->GetShort(o);
    return true;
  case Primitive::kPrimNot:
    if (allow_references) {
      value.l = f->GetObject(o);
      return true;
    }
    // Else break to report an error.
    break;
  case Primitive::kPrimVoid:
    // Never okay.
    break;
  }
  Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
      "Not a primitive field: %s", PrettyField(f).c_str());
  return false;
}

static bool CheckReceiver(JNIEnv* env, jobject javaObj, Field* f, Object*& o) {
  if (f->IsStatic()) {
    o = NULL;
    return true;
  }

  o = Decode<Object*>(env, javaObj);
  Class* declaringClass = f->GetDeclaringClass();
  if (!VerifyObjectInClass(env, o, declaringClass)) {
    return false;
  }
  return true;
}

static jobject Field_get(JNIEnv* env, jobject javaField, jobject javaObj) {
  Field* f = DecodeField(env->FromReflectedField(javaField));
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return NULL;
  }

  // Get the field's value, boxing if necessary.
  JValue value = { 0 };
  if (!GetFieldValue(o, f, value, true)) {
    return NULL;
  }
  BoxPrimitive(FieldHelper(f).GetTypeAsPrimitiveType(), value);

  return AddLocalReference<jobject>(env, value.l);
}

static JValue GetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char dst_descriptor) {
  Field* f = DecodeField(env->FromReflectedField(javaField));
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return JValue();
  }

  // Read the value.
  JValue field_value = { 0 };
  if (!GetFieldValue(o, f, field_value, false)) {
    return JValue();
  }

  // Widen it if necessary (and possible).
  JValue wide_value;
  Class* dst_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(dst_descriptor);
  if (!ConvertPrimitiveValue(FieldHelper(f).GetTypeAsPrimitiveType(), dst_type->GetPrimitiveType(),
                             field_value, wide_value)) {
    return JValue();
  }
  return wide_value;
}

static jboolean Field_getBoolean(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'Z').z;
}

static jbyte Field_getByte(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'B').b;
}

static jchar Field_getChar(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'C').c;
}

static jdouble Field_getDouble(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'D').d;
}

static jfloat Field_getFloat(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'F').f;
}

static jint Field_getInt(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'I').i;
}

static jlong Field_getLong(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'J').j;
}

static jshort Field_getShort(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'S').s;
}

static void SetFieldValue(Object* o, Field* f, const JValue& new_value, bool allow_references) {
  if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) {
    return;
  }
  switch (FieldHelper(f).GetTypeAsPrimitiveType()) {
  case Primitive::kPrimBoolean:
    f->SetBoolean(o, new_value.z);
    break;
  case Primitive::kPrimByte:
    f->SetByte(o, new_value.b);
    break;
  case Primitive::kPrimChar:
    f->SetChar(o, new_value.c);
    break;
  case Primitive::kPrimDouble:
    f->SetDouble(o, new_value.d);
    break;
  case Primitive::kPrimFloat:
    f->SetFloat(o, new_value.f);
    break;
  case Primitive::kPrimInt:
    f->SetInt(o, new_value.i);
    break;
  case Primitive::kPrimLong:
    f->SetLong(o, new_value.j);
    break;
  case Primitive::kPrimShort:
    f->SetShort(o, new_value.s);
    break;
  case Primitive::kPrimNot:
    if (allow_references) {
      f->SetObject(o, new_value.l);
      break;
    }
    // Else fall through to report an error.
  case Primitive::kPrimVoid:
    // Never okay.
    Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
        "Not a primitive field: %s", PrettyField(f).c_str());
    return;
  }

  // Special handling for final fields on SMP systems.
  // We need a store/store barrier here (JMM requirement).
  if (f->IsFinal()) {
    ANDROID_MEMBAR_STORE();
  }
}

static void Field_set(JNIEnv* env, jobject javaField, jobject javaObj, jobject javaValue) {
  ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
  Field* f = DecodeField(env->FromReflectedField(javaField));

  // Unbox the value, if necessary.
  Object* boxed_value = Decode<Object*>(env, javaValue);
  JValue unboxed_value;
  if (!UnboxPrimitive(boxed_value, FieldHelper(f).GetType(), unboxed_value, "field")) {
    return;
  }

  // Check that the receiver is non-null and an instance of the field's declaring class.
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return;
  }

  SetFieldValue(o, f, unboxed_value, true);
}

static void SetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char src_descriptor,
                              const JValue& new_value) {
  ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
  Field* f = DecodeField(env->FromReflectedField(javaField));
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return;
  }
  FieldHelper fh(f);
  if (!fh.IsPrimitiveType()) {
    Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
        "Not a primitive field: %s", PrettyField(f).c_str());
    return;
  }

  // Widen the value if necessary (and possible).
  JValue wide_value;
  Class* src_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(src_descriptor);
  if (!ConvertPrimitiveValue(src_type->GetPrimitiveType(), fh.GetTypeAsPrimitiveType(),
                             new_value, wide_value)) {
    return;
  }

  // Write the value.
  SetFieldValue(o, f, wide_value, false);
}

static void Field_setBoolean(JNIEnv* env, jobject javaField, jobject javaObj, jboolean value) {
  JValue v = { 0 };
  v.z = value;
  SetPrimitiveField(env, javaField, javaObj, 'Z', v);
}

static void Field_setByte(JNIEnv* env, jobject javaField, jobject javaObj, jbyte value) {
  JValue v = { 0 };
  v.b = value;
  SetPrimitiveField(env, javaField, javaObj, 'B', v);
}

static void Field_setChar(JNIEnv* env, jobject javaField, jobject javaObj, jchar value) {
  JValue v = { 0 };
  v.c = value;
  SetPrimitiveField(env, javaField, javaObj, 'C', v);
}

static void Field_setDouble(JNIEnv* env, jobject javaField, jobject javaObj, jdouble value) {
  JValue v = { 0 };
  v.d = value;
  SetPrimitiveField(env, javaField, javaObj, 'D', v);
}

static void Field_setFloat(JNIEnv* env, jobject javaField, jobject javaObj, jfloat value) {
  JValue v = { 0 };
  v.f = value;
  SetPrimitiveField(env, javaField, javaObj, 'F', v);
}

static void Field_setInt(JNIEnv* env, jobject javaField, jobject javaObj, jint value) {
  JValue v = { 0 };
  v.i = value;
  SetPrimitiveField(env, javaField, javaObj, 'I', v);
}

static void Field_setLong(JNIEnv* env, jobject javaField, jobject javaObj, jlong value) {
  JValue v = { 0 };
  v.j = value;
  SetPrimitiveField(env, javaField, javaObj, 'J', v);
}

static void Field_setShort(JNIEnv* env, jobject javaField, jobject javaObj, jshort value) {
  JValue v = { 0 };
  v.s = value;
  SetPrimitiveField(env, javaField, javaObj, 'S', v);
}

static JNINativeMethod gMethods[] = {
  NATIVE_METHOD(Field, get,        "(Ljava/lang/Object;)Ljava/lang/Object;"),
  NATIVE_METHOD(Field, getBoolean, "(Ljava/lang/Object;)Z"),
  NATIVE_METHOD(Field, getByte,    "(Ljava/lang/Object;)B"),
  NATIVE_METHOD(Field, getChar,    "(Ljava/lang/Object;)C"),
  NATIVE_METHOD(Field, getDouble,  "(Ljava/lang/Object;)D"),
  NATIVE_METHOD(Field, getFloat,   "(Ljava/lang/Object;)F"),
  NATIVE_METHOD(Field, getInt,     "(Ljava/lang/Object;)I"),
  NATIVE_METHOD(Field, getLong,    "(Ljava/lang/Object;)J"),
  NATIVE_METHOD(Field, getShort,   "(Ljava/lang/Object;)S"),
  NATIVE_METHOD(Field, set,        "(Ljava/lang/Object;Ljava/lang/Object;)V"),
  NATIVE_METHOD(Field, setBoolean, "(Ljava/lang/Object;Z)V"),
  NATIVE_METHOD(Field, setByte,    "(Ljava/lang/Object;B)V"),
  NATIVE_METHOD(Field, setChar,    "(Ljava/lang/Object;C)V"),
  NATIVE_METHOD(Field, setDouble,  "(Ljava/lang/Object;D)V"),
  NATIVE_METHOD(Field, setFloat,   "(Ljava/lang/Object;F)V"),
  NATIVE_METHOD(Field, setInt,     "(Ljava/lang/Object;I)V"),
  NATIVE_METHOD(Field, setLong,    "(Ljava/lang/Object;J)V"),
  NATIVE_METHOD(Field, setShort,   "(Ljava/lang/Object;S)V"),
};

void register_java_lang_reflect_Field(JNIEnv* env) {
  jniRegisterNativeMethods(env, "java/lang/reflect/Field", gMethods, NELEM(gMethods));
}

}  // namespace art
<commit_msg>Ensure byte and short values are sign extended before boxing.<commit_after>/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "jni_internal.h"
#include "class_linker.h"
#include "object.h"
#include "object_utils.h"
#include "reflection.h"

#include "JniConstants.h" // Last to avoid problems with LOG redefinition.

namespace art {

static bool GetFieldValue(Object* o, Field* f, JValue& value, bool allow_references) {
  DCHECK_EQ(value.j, 0LL);
  ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
  if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) {
    return false;
  }
  switch (FieldHelper(f).GetTypeAsPrimitiveType()) {
  case Primitive::kPrimBoolean:
    value.z = f->GetBoolean(o);
    return true;
  case Primitive::kPrimByte:
    // Read byte and ensure it is fully sign-extended to an int.
    value.i = ((int32_t)f->GetByte(o) << 24) >> 24;
    return true;
  case Primitive::kPrimChar:
    value.c = f->GetChar(o);
    return true;
  case Primitive::kPrimDouble:
    value.d = f->GetDouble(o);
    return true;
  case Primitive::kPrimFloat:
    value.f = f->GetFloat(o);
    return true;
  case Primitive::kPrimInt:
    value.i = f->GetInt(o);
    return true;
  case Primitive::kPrimLong:
    value.j = f->GetLong(o);
    return true;
  case Primitive::kPrimShort:
    // Read short and ensure it is fully sign-extended to an int.
    value.i = ((int32_t)f->GetShort(o) << 16) >> 16;
    return true;
  case Primitive::kPrimNot:
    if (allow_references) {
      value.l = f->GetObject(o);
      return true;
    }
    // Else break to report an error.
    break;
  case Primitive::kPrimVoid:
    // Never okay.
    break;
  }
  Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
      "Not a primitive field: %s", PrettyField(f).c_str());
  return false;
}

static bool CheckReceiver(JNIEnv* env, jobject javaObj, Field* f, Object*& o) {
  if (f->IsStatic()) {
    o = NULL;
    return true;
  }

  o = Decode<Object*>(env, javaObj);
  Class* declaringClass = f->GetDeclaringClass();
  if (!VerifyObjectInClass(env, o, declaringClass)) {
    return false;
  }
  return true;
}

static jobject Field_get(JNIEnv* env, jobject javaField, jobject javaObj) {
  Field* f = DecodeField(env->FromReflectedField(javaField));
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return NULL;
  }

  // Get the field's value, boxing if necessary.
  JValue value = { 0 };
  if (!GetFieldValue(o, f, value, true)) {
    return NULL;
  }
  BoxPrimitive(FieldHelper(f).GetTypeAsPrimitiveType(), value);

  return AddLocalReference<jobject>(env, value.l);
}

static JValue GetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char dst_descriptor) {
  Field* f = DecodeField(env->FromReflectedField(javaField));
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return JValue();
  }

  // Read the value.
  JValue field_value = { 0 };
  if (!GetFieldValue(o, f, field_value, false)) {
    return JValue();
  }

  // Widen it if necessary (and possible).
  JValue wide_value;
  Class* dst_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(dst_descriptor);
  if (!ConvertPrimitiveValue(FieldHelper(f).GetTypeAsPrimitiveType(), dst_type->GetPrimitiveType(),
                             field_value, wide_value)) {
    return JValue();
  }
  return wide_value;
}

static jboolean Field_getBoolean(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'Z').z;
}

static jbyte Field_getByte(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'B').b;
}

static jchar Field_getChar(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'C').c;
}

static jdouble Field_getDouble(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'D').d;
}

static jfloat Field_getFloat(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'F').f;
}

static jint Field_getInt(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'I').i;
}

static jlong Field_getLong(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'J').j;
}

static jshort Field_getShort(JNIEnv* env, jobject javaField, jobject javaObj) {
  return GetPrimitiveField(env, javaField, javaObj, 'S').s;
}

static void SetFieldValue(Object* o, Field* f, const JValue& new_value, bool allow_references) {
  if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(f->GetDeclaringClass(), true, true)) {
    return;
  }
  switch (FieldHelper(f).GetTypeAsPrimitiveType()) {
  case Primitive::kPrimBoolean:
    f->SetBoolean(o, new_value.z);
    break;
  case Primitive::kPrimByte:
    f->SetByte(o, new_value.b);
    break;
  case Primitive::kPrimChar:
    f->SetChar(o, new_value.c);
    break;
  case Primitive::kPrimDouble:
    f->SetDouble(o, new_value.d);
    break;
  case Primitive::kPrimFloat:
    f->SetFloat(o, new_value.f);
    break;
  case Primitive::kPrimInt:
    f->SetInt(o, new_value.i);
    break;
  case Primitive::kPrimLong:
    f->SetLong(o, new_value.j);
    break;
  case Primitive::kPrimShort:
    f->SetShort(o, new_value.s);
    break;
  case Primitive::kPrimNot:
    if (allow_references) {
      f->SetObject(o, new_value.l);
      break;
    }
    // Else fall through to report an error.
  case Primitive::kPrimVoid:
    // Never okay.
    Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
        "Not a primitive field: %s", PrettyField(f).c_str());
    return;
  }

  // Special handling for final fields on SMP systems.
  // We need a store/store barrier here (JMM requirement).
  if (f->IsFinal()) {
    ANDROID_MEMBAR_STORE();
  }
}

static void Field_set(JNIEnv* env, jobject javaField, jobject javaObj, jobject javaValue) {
  ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
  Field* f = DecodeField(env->FromReflectedField(javaField));

  // Unbox the value, if necessary.
  Object* boxed_value = Decode<Object*>(env, javaValue);
  JValue unboxed_value;
  if (!UnboxPrimitive(boxed_value, FieldHelper(f).GetType(), unboxed_value, "field")) {
    return;
  }

  // Check that the receiver is non-null and an instance of the field's declaring class.
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return;
  }

  SetFieldValue(o, f, unboxed_value, true);
}

static void SetPrimitiveField(JNIEnv* env, jobject javaField, jobject javaObj, char src_descriptor,
                              const JValue& new_value) {
  ScopedThreadStateChange tsc(Thread::Current(), kRunnable);
  Field* f = DecodeField(env->FromReflectedField(javaField));
  Object* o = NULL;
  if (!CheckReceiver(env, javaObj, f, o)) {
    return;
  }
  FieldHelper fh(f);
  if (!fh.IsPrimitiveType()) {
    Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
        "Not a primitive field: %s", PrettyField(f).c_str());
    return;
  }

  // Widen the value if necessary (and possible).
  JValue wide_value;
  Class* src_type = Runtime::Current()->GetClassLinker()->FindPrimitiveClass(src_descriptor);
  if (!ConvertPrimitiveValue(src_type->GetPrimitiveType(), fh.GetTypeAsPrimitiveType(),
                             new_value, wide_value)) {
    return;
  }

  // Write the value.
  SetFieldValue(o, f, wide_value, false);
}

static void Field_setBoolean(JNIEnv* env, jobject javaField, jobject javaObj, jboolean value) {
  JValue v = { 0 };
  v.z = value;
  SetPrimitiveField(env, javaField, javaObj, 'Z', v);
}

static void Field_setByte(JNIEnv* env, jobject javaField, jobject javaObj, jbyte value) {
  JValue v = { 0 };
  v.b = value;
  SetPrimitiveField(env, javaField, javaObj, 'B', v);
}

static void Field_setChar(JNIEnv* env, jobject javaField, jobject javaObj, jchar value) {
  JValue v = { 0 };
  v.c = value;
  SetPrimitiveField(env, javaField, javaObj, 'C', v);
}

static void Field_setDouble(JNIEnv* env, jobject javaField, jobject javaObj, jdouble value) {
  JValue v = { 0 };
  v.d = value;
  SetPrimitiveField(env, javaField, javaObj, 'D', v);
}

static void Field_setFloat(JNIEnv* env, jobject javaField, jobject javaObj, jfloat value) {
  JValue v = { 0 };
  v.f = value;
  SetPrimitiveField(env, javaField, javaObj, 'F', v);
}

static void Field_setInt(JNIEnv* env, jobject javaField, jobject javaObj, jint value) {
  JValue v = { 0 };
  v.i = value;
  SetPrimitiveField(env, javaField, javaObj, 'I', v);
}

static void Field_setLong(JNIEnv* env, jobject javaField, jobject javaObj, jlong value) {
  JValue v = { 0 };
  v.j = value;
  SetPrimitiveField(env, javaField, javaObj, 'J', v);
}

static void Field_setShort(JNIEnv* env, jobject javaField, jobject javaObj, jshort value) {
  JValue v = { 0 };
  v.s = value;
  SetPrimitiveField(env, javaField, javaObj, 'S', v);
}

static JNINativeMethod gMethods[] = {
  NATIVE_METHOD(Field, get,        "(Ljava/lang/Object;)Ljava/lang/Object;"),
  NATIVE_METHOD(Field, getBoolean, "(Ljava/lang/Object;)Z"),
  NATIVE_METHOD(Field, getByte,    "(Ljava/lang/Object;)B"),
  NATIVE_METHOD(Field, getChar,    "(Ljava/lang/Object;)C"),
  NATIVE_METHOD(Field, getDouble,  "(Ljava/lang/Object;)D"),
  NATIVE_METHOD(Field, getFloat,   "(Ljava/lang/Object;)F"),
  NATIVE_METHOD(Field, getInt,     "(Ljava/lang/Object;)I"),
  NATIVE_METHOD(Field, getLong,    "(Ljava/lang/Object;)J"),
  NATIVE_METHOD(Field, getShort,   "(Ljava/lang/Object;)S"),
  NATIVE_METHOD(Field, set,        "(Ljava/lang/Object;Ljava/lang/Object;)V"),
  NATIVE_METHOD(Field, setBoolean, "(Ljava/lang/Object;Z)V"),
  NATIVE_METHOD(Field, setByte,    "(Ljava/lang/Object;B)V"),
  NATIVE_METHOD(Field, setChar,    "(Ljava/lang/Object;C)V"),
  NATIVE_METHOD(Field, setDouble,  "(Ljava/lang/Object;D)V"),
  NATIVE_METHOD(Field, setFloat,   "(Ljava/lang/Object;F)V"),
  NATIVE_METHOD(Field, setInt,     "(Ljava/lang/Object;I)V"),
  NATIVE_METHOD(Field, setLong,    "(Ljava/lang/Object;J)V"),
  NATIVE_METHOD(Field, setShort,   "(Ljava/lang/Object;S)V"),
};

void register_java_lang_reflect_Field(JNIEnv* env) {
  jniRegisterNativeMethods(env, "java/lang/reflect/Field", gMethods, NELEM(gMethods));
}

}  // namespace art
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>
#include <string>

#include "chrome/browser/download/download_util.h"

#include "base/logging.h"

namespace download_util {

// For file extensions taken from mozilla:

/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code, released
 * March 31, 1998.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998-1999
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Doug Turner <dougt@netscape.com>
 *   Dean Tessman <dean_tessman@hotmail.com>
 *   Brodie Thiesfield <brofield@jellycan.com>
 *   Jungshik Shin <jshin@i18nl10n.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

static const char* const g_executables[] = {
#if defined(OS_WIN)
  "ad",
  "ade",
  "adp",
  "app",
  "application",
  "asp",
  "asx",
  "bas",
  "bat",
  "chm",
  "cmd",
  "com",
  "cpl",
  "crt",
  "dll",
  "exe",
  "fxp",
  "hlp",
  "hta",
  "htm",
  "html",
  "htt",
  "inf",
  "ins",
  "isp",
  "jar",
  "js",
  "jse",
  "lnk",
  "mad",
  "maf",
  "mag",
  "mam",
  "maq",
  "mar",
  "mas",
  "mat",
  "mau",
  "mav",
  "maw",
  "mda",
  "mdb",
  "mde",
  "mdt",
  "mdw",
  "mdz",
  "mht",
  "mhtml",
  "msc",
  "msh",
  "mshxml",
  "msi",
  "msp",
  "mst",
  "ops",
  "pcd",
  "pif",
  "plg",
  "prf",
  "prg",
  "pst",
  "reg",
  "scf",
  "scr",
  "sct",
  "shb",
  "shs",
  "shtm",
  "shtml",
  "url",
  "vb",
  "vbe",
  "vbs",
  "vsd",
  "vsmacros",
  "vss",
  "vst",
  "vsw",
  "ws",
  "wsc",
  "wsf",
  "wsh",
  "xht",
  "xhtm",
  "xhtml",
  "xml",
  "xsl",
  "xslt",
#elif defined(OS_LINUX)
  // TODO(estade): lengthen this list.
  "exe",
  "pl",
  "py",
  "rb",
  "sh",
#elif defined(OS_MACOSX)
  // TODO(thakis): Figure out what makes sense here -- crbug.com/19096
  "dmg",
#endif
};

void InitializeExeTypes(std::set<std::string>* exe_extensions) {
  DCHECK(exe_extensions);
  for (size_t i = 0; i < arraysize(g_executables); ++i)
    exe_extensions->insert(g_executables[i]);
}

}  // namespace download_util
<commit_msg>One more bad extension.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <set>
#include <string>

#include "chrome/browser/download/download_util.h"

#include "base/logging.h"

namespace download_util {

// For file extensions taken from mozilla:

/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code, released
 * March 31, 1998.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998-1999
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Doug Turner <dougt@netscape.com>
 *   Dean Tessman <dean_tessman@hotmail.com>
 *   Brodie Thiesfield <brofield@jellycan.com>
 *   Jungshik Shin <jshin@i18nl10n.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

static const char* const g_executables[] = {
#if defined(OS_WIN)
  "ad",
  "ade",
  "adp",
  "app",
  "application",
  "asp",
  "asx",
  "bas",
  "bat",
  "chm",
  "cmd",
  "com",
  "cpl",
  "crt",
  "dll",
  "exe",
  "fxp",
  "hlp",
  "hta",
  "htm",
  "html",
  "htt",
  "inf",
  "ins",
  "isp",
  "jar",
  "js",
  "jse",
  "lnk",
  "mad",
  "maf",
  "mag",
  "mam",
  "maq",
  "mar",
  "mas",
  "mat",
  "mau",
  "mav",
  "maw",
  "mda",
  "mdb",
  "mde",
  "mdt",
  "mdw",
  "mdz",
  "mht",
  "mhtml",
  "msc",
  "msh",
  "mshxml",
  "msi",
  "msp",
  "mst",
  "ops",
  "pcd",
  "pif",
  "plg",
  "prf",
  "prg",
  "pst",
  "reg",
  "scf",
  "scr",
  "sct",
  "shb",
  "shs",
  "shtm",
  "shtml",
  "svg",
  "url",
  "vb",
  "vbe",
  "vbs",
  "vsd",
  "vsmacros",
  "vss",
  "vst",
  "vsw",
  "ws",
  "wsc",
  "wsf",
  "wsh",
  "xht",
  "xhtm",
  "xhtml",
  "xml",
  "xsl",
  "xslt",
#elif defined(OS_LINUX)
  // TODO(estade): lengthen this list.
  "exe",
  "pl",
  "py",
  "rb",
  "sh",
#elif defined(OS_MACOSX)
  // TODO(thakis): Figure out what makes sense here -- crbug.com/19096
  "dmg",
#endif
};

void InitializeExeTypes(std::set<std::string>* exe_extensions) {
  DCHECK(exe_extensions);
  for (size_t i = 0; i < arraysize(g_executables); ++i)
    exe_extensions->insert(g_executables[i]);
}

}  // namespace download_util
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "zero_even_op.h"

namespace caffe2 {

template <>
bool ZeroEvenOp<float, CPUContext>::RunOnDevice() {
  // Retrieve the input tensor.
  const auto& X = Input(0);
  CAFFE_ENFORCE(X.ndim() == 1);

  // Initialize the output tensor to a copy of the input tensor.
  auto* Y = Output(0);
  Y->CopyFrom(X);

  // Set output elements at even indices to zero.
  auto* Y_data = Y->mutable_data<float>();
  for (auto i = 0; i < Y->size(); i += 2) {
    Y_data[i] = 0.0f;
  }

  return true;
}

REGISTER_CPU_OPERATOR(ZeroEven, ZeroEvenOp<float, CPUContext>);

OPERATOR_SCHEMA(ZeroEven)
    .NumInputs(1)
    .NumOutputs(1)
    .Input(
        0,
        "X",
        "1D input tensor")
    .Output(
        0,
        "Y",
        "1D output tensor");

} // namespace caffe2
<commit_msg>Renaming size() to numel()<commit_after>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "zero_even_op.h"

namespace caffe2 {

template <>
bool ZeroEvenOp<float, CPUContext>::RunOnDevice() {
  // Retrieve the input tensor.
  const auto& X = Input(0);
  CAFFE_ENFORCE(X.ndim() == 1);

  // Initialize the output tensor to a copy of the input tensor.
  auto* Y = Output(0);
  Y->CopyFrom(X);

  // Set output elements at even indices to zero.
  auto* Y_data = Y->mutable_data<float>();
  for (auto i = 0; i < Y->numel(); i += 2) {
    Y_data[i] = 0.0f;
  }

  return true;
}

REGISTER_CPU_OPERATOR(ZeroEven, ZeroEvenOp<float, CPUContext>);

OPERATOR_SCHEMA(ZeroEven)
    .NumInputs(1)
    .NumOutputs(1)
    .Input(
        0,
        "X",
        "1D input tensor")
    .Output(
        0,
        "Y",
        "1D output tensor");

} // namespace caffe2
<|endoftext|>


<commit_before><commit_msg>No need to wait for debugger here on Android, this code does seem to work<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/reload_button_gtk.h"

#include "app/l10n_util.h"
#include "base/logging.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/location_bar_view_gtk.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// The width of this button in GTK+ theme mode. The Stop and Refresh stock icons
// can be different sizes; this variable is used to make sure that the button
// doesn't change sizes when switching between the two.
static int GtkButtonWidth = 0;

ReloadButtonGtk::ReloadButtonGtk(LocationBarViewGtk* location_bar,
                                 Browser* browser)
    : location_bar_(location_bar),
      browser_(browser),
      button_delay_(0),
      pretend_timer_is_running_for_unittest_(false),
      intended_mode_(MODE_RELOAD),
      visible_mode_(MODE_RELOAD),
      theme_provider_(browser ?
                      GtkThemeProvider::GetFrom(browser->profile()) : NULL),
      reload_(theme_provider_, IDR_RELOAD, IDR_RELOAD_P, IDR_RELOAD_H, 0),
      stop_(theme_provider_, IDR_STOP, IDR_STOP_P, IDR_STOP_H, 0),
      widget_(gtk_chrome_button_new()) {
  gtk_widget_set_size_request(widget_.get(), reload_.Width(), reload_.Height());

  gtk_widget_set_app_paintable(widget_.get(), TRUE);

  g_signal_connect(widget_.get(), "clicked",
                   G_CALLBACK(OnClickedThunk), this);
  g_signal_connect(widget_.get(), "expose-event",
                   G_CALLBACK(OnExposeThunk), this);
  g_signal_connect(widget_.get(), "leave-notify-event",
                   G_CALLBACK(OnLeaveNotifyThunk), this);
  GTK_WIDGET_UNSET_FLAGS(widget_.get(), GTK_CAN_FOCUS);

  gtk_widget_set_has_tooltip(widget_.get(), TRUE);
  g_signal_connect(widget_.get(), "query-tooltip",
                   G_CALLBACK(OnQueryTooltipThunk), this);

  hover_controller_.Init(widget());
  gtk_util::SetButtonTriggersNavigation(widget());

  if (theme_provider_) {
    theme_provider_->InitThemesFor(this);
    registrar_.Add(this,
                   NotificationType::BROWSER_THEME_CHANGED,
                   Source<GtkThemeProvider>(theme_provider_));
  }
}

ReloadButtonGtk::~ReloadButtonGtk() {
  widget_.Destroy();
}

void ReloadButtonGtk::ChangeMode(Mode mode, bool force) {
  intended_mode_ = mode;

  // If the change is forced, or the user isn't hovering the icon, or it's safe
  // to change it to the other image type, make the change immediately;
  // otherwise we'll let it happen later.
  if (force || GTK_WIDGET_STATE(widget()) == GTK_STATE_NORMAL ||
      ((mode == MODE_STOP) ?
        !timer_running() : (visible_mode_ != MODE_STOP))) {
    timer_.Stop();
    visible_mode_ = mode;

    UpdateThemeButtons();
    gtk_widget_queue_draw(widget_.get());
  }
}

void ReloadButtonGtk::Observe(NotificationType type,
                              const NotificationSource& source,
                              const NotificationDetails& details) {
  DCHECK(NotificationType::BROWSER_THEME_CHANGED == type);

  GtkThemeProvider* provider = static_cast<GtkThemeProvider*>(
      Source<GtkThemeProvider>(source).ptr());
  DCHECK_EQ(provider, theme_provider_);
  GtkButtonWidth = 0;
  UpdateThemeButtons();
}

void ReloadButtonGtk::OnButtonTimer() {
  ChangeMode(intended_mode_, true);
}

void ReloadButtonGtk::OnClicked(GtkWidget* sender) {
  if (visible_mode_ == MODE_STOP) {
    if (browser_)
      browser_->Stop();

    // The user has clicked, so we can feel free to update the button,
    // even if the mouse is still hovering.
    ChangeMode(MODE_RELOAD, true);
  } else if (!timer_running()) {
    // Shift-clicking or Ctrl-clicking the reload button means we should ignore
    // any cached content.
    int command;
    GdkModifierType modifier_state;
    gtk_get_current_event_state(&modifier_state);
    guint modifier_state_uint = modifier_state;
    if (modifier_state_uint & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
      command = IDC_RELOAD_IGNORING_CACHE;
      // Mask off Shift and Control so they don't affect the disposition below.
      modifier_state_uint &= ~(GDK_SHIFT_MASK | GDK_CONTROL_MASK);
    } else {
      command = IDC_RELOAD;
    }

    WindowOpenDisposition disposition =
        event_utils::DispositionFromEventFlags(modifier_state_uint);
    if (disposition == CURRENT_TAB) {
      // Forcibly reset the location bar, since otherwise it won't discard any
      // ongoing user edits, since it doesn't realize this is a user-initiated
      // action.
      location_bar_->Revert();
    }

    if (browser_)
      browser_->ExecuteCommandWithDisposition(command, disposition);

    // Figure out the system double-click time.
    if (button_delay_ == 0) {
      GtkSettings* settings = gtk_settings_get_default();
      g_object_get(G_OBJECT(settings), "gtk-double-click-time", &button_delay_,
                   NULL);
    }

    // Start a timer - while this timer is running, the reload button cannot be
    // changed to a stop button.  We do not set |intended_mode_| to MODE_STOP
    // here as we want to wait for the browser to tell us that it has started
    // loading (and this may occur only after some delay).
    timer_.Stop();
    timer_.Start(base::TimeDelta::FromMilliseconds(button_delay_), this,
                 &ReloadButtonGtk::OnButtonTimer);
  }
}

gboolean ReloadButtonGtk::OnExpose(GtkWidget* widget,
                                   GdkEventExpose* e) {
  if (theme_provider_ && theme_provider_->UseGtkTheme())
    return FALSE;
  return ((visible_mode_ == MODE_RELOAD) ? reload_ : stop_).OnExpose(
      widget, e, hover_controller_.GetCurrentValue());
}

gboolean ReloadButtonGtk::OnLeaveNotify(GtkWidget* widget,
                                        GdkEventCrossing* event) {
  ChangeMode(intended_mode_, false);
  return FALSE;
}

gboolean ReloadButtonGtk::OnQueryTooltip(GtkWidget* sender,
                                         gint x,
                                         gint y,
                                         gboolean keyboard_mode,
                                         GtkTooltip* tooltip) {
  // |location_bar_| can be NULL in tests.
  if (!location_bar_)
    return FALSE;

  gtk_tooltip_set_text(tooltip, l10n_util::GetStringUTF8(
      (visible_mode_ == MODE_RELOAD) ?
      IDS_TOOLTIP_RELOAD : IDS_TOOLTIP_STOP).c_str());
  return TRUE;
}

void ReloadButtonGtk::UpdateThemeButtons() {
  bool use_gtk = theme_provider_ && theme_provider_->UseGtkTheme();

  if (use_gtk) {
    GdkPixbuf* pixbuf = gtk_widget_render_icon(widget(),
        (intended_mode_ == MODE_RELOAD) ? GTK_STOCK_REFRESH : GTK_STOCK_STOP,
        GTK_ICON_SIZE_SMALL_TOOLBAR, NULL);

    gtk_button_set_image(GTK_BUTTON(widget_.get()),
                         gtk_image_new_from_pixbuf(pixbuf));
    g_object_unref(pixbuf);

    gtk_widget_set_size_request(widget_.get(), -1, -1);
    GtkRequisition req;
    gtk_widget_size_request(widget(), &req);
    GtkButtonWidth = std::max(GtkButtonWidth, req.width);
    gtk_widget_set_size_request(widget_.get(), GtkButtonWidth, -1);

    gtk_widget_set_app_paintable(widget_.get(), FALSE);
    gtk_widget_set_double_buffered(widget_.get(), TRUE);
  } else {
    gtk_button_set_image(GTK_BUTTON(widget()), NULL);

    gtk_widget_set_size_request(widget_.get(), reload_.Width(),
                                reload_.Height());

    gtk_widget_set_app_paintable(widget_.get(), TRUE);
    // We effectively double-buffer by virtue of having only one image...
    gtk_widget_set_double_buffered(widget_.get(), FALSE);
  }

  gtk_chrome_button_set_use_gtk_rendering(
      GTK_CHROME_BUTTON(widget_.get()), use_gtk);
}
<commit_msg>Fix GTK unittest failure<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/reload_button_gtk.h"

#include "app/l10n_util.h"
#include "base/logging.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/gtk/gtk_util.h"
#include "chrome/browser/gtk/location_bar_view_gtk.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"

// The width of this button in GTK+ theme mode. The Stop and Refresh stock icons
// can be different sizes; this variable is used to make sure that the button
// doesn't change sizes when switching between the two.
static int GtkButtonWidth = 0;

ReloadButtonGtk::ReloadButtonGtk(LocationBarViewGtk* location_bar,
                                 Browser* browser)
    : location_bar_(location_bar),
      browser_(browser),
      button_delay_(0),
      pretend_timer_is_running_for_unittest_(false),
      intended_mode_(MODE_RELOAD),
      visible_mode_(MODE_RELOAD),
      theme_provider_(browser ?
                      GtkThemeProvider::GetFrom(browser->profile()) : NULL),
      reload_(theme_provider_, IDR_RELOAD, IDR_RELOAD_P, IDR_RELOAD_H, 0),
      stop_(theme_provider_, IDR_STOP, IDR_STOP_P, IDR_STOP_H, 0),
      widget_(gtk_chrome_button_new()) {
  gtk_widget_set_size_request(widget_.get(), reload_.Width(), reload_.Height());

  gtk_widget_set_app_paintable(widget_.get(), TRUE);

  g_signal_connect(widget_.get(), "clicked",
                   G_CALLBACK(OnClickedThunk), this);
  g_signal_connect(widget_.get(), "expose-event",
                   G_CALLBACK(OnExposeThunk), this);
  g_signal_connect(widget_.get(), "leave-notify-event",
                   G_CALLBACK(OnLeaveNotifyThunk), this);
  GTK_WIDGET_UNSET_FLAGS(widget_.get(), GTK_CAN_FOCUS);

  gtk_widget_set_has_tooltip(widget_.get(), TRUE);
  g_signal_connect(widget_.get(), "query-tooltip",
                   G_CALLBACK(OnQueryTooltipThunk), this);

  hover_controller_.Init(widget());
  gtk_util::SetButtonTriggersNavigation(widget());

  if (theme_provider_) {
    theme_provider_->InitThemesFor(this);
    registrar_.Add(this,
                   NotificationType::BROWSER_THEME_CHANGED,
                   Source<GtkThemeProvider>(theme_provider_));
  }
}

ReloadButtonGtk::~ReloadButtonGtk() {
  widget_.Destroy();
}

void ReloadButtonGtk::ChangeMode(Mode mode, bool force) {
  intended_mode_ = mode;

  // If the change is forced, or the user isn't hovering the icon, or it's safe
  // to change it to the other image type, make the change immediately;
  // otherwise we'll let it happen later.
  if (force || GTK_WIDGET_STATE(widget()) == GTK_STATE_NORMAL ||
      ((mode == MODE_STOP) ?
        !timer_running() : (visible_mode_ != MODE_STOP))) {
    timer_.Stop();
    visible_mode_ = mode;

    UpdateThemeButtons();
    gtk_widget_queue_draw(widget_.get());
  }
}

void ReloadButtonGtk::Observe(NotificationType type,
                              const NotificationSource& source,
                              const NotificationDetails& details) {
  DCHECK(NotificationType::BROWSER_THEME_CHANGED == type);

  GtkThemeProvider* provider = static_cast<GtkThemeProvider*>(
      Source<GtkThemeProvider>(source).ptr());
  DCHECK_EQ(provider, theme_provider_);
  GtkButtonWidth = 0;
  UpdateThemeButtons();
}

void ReloadButtonGtk::OnButtonTimer() {
  ChangeMode(intended_mode_, true);
}

void ReloadButtonGtk::OnClicked(GtkWidget* sender) {
  if (visible_mode_ == MODE_STOP) {
    if (browser_)
      browser_->Stop();

    // The user has clicked, so we can feel free to update the button,
    // even if the mouse is still hovering.
    ChangeMode(MODE_RELOAD, true);
  } else if (!timer_running()) {
    // Shift-clicking or Ctrl-clicking the reload button means we should ignore
    // any cached content.
    int command;
    GdkModifierType modifier_state;
    gtk_get_current_event_state(&modifier_state);
    guint modifier_state_uint = modifier_state;
    if (modifier_state_uint & (GDK_SHIFT_MASK | GDK_CONTROL_MASK)) {
      command = IDC_RELOAD_IGNORING_CACHE;
      // Mask off Shift and Control so they don't affect the disposition below.
      modifier_state_uint &= ~(GDK_SHIFT_MASK | GDK_CONTROL_MASK);
    } else {
      command = IDC_RELOAD;
    }

    WindowOpenDisposition disposition =
        event_utils::DispositionFromEventFlags(modifier_state_uint);
    if (disposition == CURRENT_TAB) {
      // Forcibly reset the location bar, since otherwise it won't discard any
      // ongoing user edits, since it doesn't realize this is a user-initiated
      // action.
      location_bar_->Revert();
    }

    if (browser_)
      browser_->ExecuteCommandWithDisposition(command, disposition);

    // Figure out the system double-click time.
    if (button_delay_ == 0) {
      GtkSettings* settings = gtk_settings_get_default();
      g_object_get(G_OBJECT(settings), "gtk-double-click-time", &button_delay_,
                   NULL);
    }

    // Start a timer - while this timer is running, the reload button cannot be
    // changed to a stop button.  We do not set |intended_mode_| to MODE_STOP
    // here as we want to wait for the browser to tell us that it has started
    // loading (and this may occur only after some delay).
    timer_.Stop();
    timer_.Start(base::TimeDelta::FromMilliseconds(button_delay_), this,
                 &ReloadButtonGtk::OnButtonTimer);
  }
}

gboolean ReloadButtonGtk::OnExpose(GtkWidget* widget,
                                   GdkEventExpose* e) {
  if (theme_provider_ && theme_provider_->UseGtkTheme())
    return FALSE;
  return ((visible_mode_ == MODE_RELOAD) ? reload_ : stop_).OnExpose(
      widget, e, hover_controller_.GetCurrentValue());
}

gboolean ReloadButtonGtk::OnLeaveNotify(GtkWidget* widget,
                                        GdkEventCrossing* event) {
  ChangeMode(intended_mode_, true);
  return FALSE;
}

gboolean ReloadButtonGtk::OnQueryTooltip(GtkWidget* sender,
                                         gint x,
                                         gint y,
                                         gboolean keyboard_mode,
                                         GtkTooltip* tooltip) {
  // |location_bar_| can be NULL in tests.
  if (!location_bar_)
    return FALSE;

  gtk_tooltip_set_text(tooltip, l10n_util::GetStringUTF8(
      (visible_mode_ == MODE_RELOAD) ?
      IDS_TOOLTIP_RELOAD : IDS_TOOLTIP_STOP).c_str());
  return TRUE;
}

void ReloadButtonGtk::UpdateThemeButtons() {
  bool use_gtk = theme_provider_ && theme_provider_->UseGtkTheme();

  if (use_gtk) {
    GdkPixbuf* pixbuf = gtk_widget_render_icon(widget(),
        (intended_mode_ == MODE_RELOAD) ? GTK_STOCK_REFRESH : GTK_STOCK_STOP,
        GTK_ICON_SIZE_SMALL_TOOLBAR, NULL);

    gtk_button_set_image(GTK_BUTTON(widget_.get()),
                         gtk_image_new_from_pixbuf(pixbuf));
    g_object_unref(pixbuf);

    gtk_widget_set_size_request(widget_.get(), -1, -1);
    GtkRequisition req;
    gtk_widget_size_request(widget(), &req);
    GtkButtonWidth = std::max(GtkButtonWidth, req.width);
    gtk_widget_set_size_request(widget_.get(), GtkButtonWidth, -1);

    gtk_widget_set_app_paintable(widget_.get(), FALSE);
    gtk_widget_set_double_buffered(widget_.get(), TRUE);
  } else {
    gtk_button_set_image(GTK_BUTTON(widget()), NULL);

    gtk_widget_set_size_request(widget_.get(), reload_.Width(),
                                reload_.Height());

    gtk_widget_set_app_paintable(widget_.get(), TRUE);
    // We effectively double-buffer by virtue of having only one image...
    gtk_widget_set_double_buffered(widget_.get(), FALSE);
  }

  gtk_chrome_button_set_use_gtk_rendering(
      GTK_CHROME_BUTTON(widget_.get()), use_gtk);
}
<|endoftext|>


<commit_before>#include <Quiver.h>

Quiver::Quiver(QString sourcePath, QObject *parent) : QObject(parent)
{
        _engine = new QQmlApplicationEngine;
        new QQmlFileSelector(_engine);
        addProperty("quiver", this);

        _watcher = new QFileSystemWatcher;
        connect(_watcher,     SIGNAL(fileChanged(const QString&)),
                this,    SLOT(fileChanged(const QString&)));
        connect(_watcher,     SIGNAL(directoryChanged(const QString&)),
                this,    SLOT(fileChanged(const QString&)));

        if (!sourcePath.isEmpty()) {
                setSource(sourcePath);
        }
}

Quiver::~Quiver()
{
        delete _engine;
        delete _watcher;
}

void Quiver::detectPlatform() {
        QString platform_name("unknown");

#ifdef Q_OS_IOS
        platform_name = "ios";
#endif

#ifdef Q_OS_MACX
        platform_name = "osx";
#endif

#ifdef Q_OS_WIN
        platform_name = "win";
#endif

        QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
        if (env.contains("Quiver_platformName") && !env.value("Quiver_platformName").isEmpty()) {
                platform_name = env.value("Quiver_platformName");
        }

        setPlatform(platform_name);
}

void Quiver::setPlatform(const QString & platformName) {
        _platformName = platformName;
}

void Quiver::setSource(const QString & path)
{
        _sourcePath = path;

        if (_platformName.isEmpty()) {
                detectPlatform();
        }

        QDir platformDir(_sourcePath + "/" + _platformName);
        _engine->addImportPath(_sourcePath);
        _engine->load(QUrl::fromLocalFile(platformDir.absolutePath() + "/main.qml"));
        addWatchPath(platformDir.absolutePath());
        printf("Quiver: main.qml loaded\n"); //this must be printf() and not qDebug() << for some reason ... (20141125)
        fflush(stdout);
}

void Quiver::fileChanged(const QString & path)
{
        _engine->clearComponentCache();
        emit pendingConnectionRequestChanged();

        _watcher->addPath(path);
}

void Quiver::addWatchPath(const QString & path)
{
        _watcher->addPath(path);
}

void Quiver::addWatchPaths(const QStringList & paths)
{
        _watcher->addPaths(paths);
}

void Quiver::addProperty(const QString & name, QObject * obj)
{
        _engine->rootContext()->setContextProperty(name, obj);
}

void Quiver::addImageProvider(const QString & name, QQmlImageProviderBase *image_provider) {
        _engine->addImageProvider(name, image_provider);
}
<commit_msg>enable loading from a qrc-based source (hopefully)<commit_after>#include <Quiver.h>

Quiver::Quiver(QString sourcePath, QObject *parent) : QObject(parent)
{
        _engine = new QQmlApplicationEngine;
        new QQmlFileSelector(_engine);
        addProperty("quiver", this);

        _watcher = new QFileSystemWatcher;
        connect(_watcher,     SIGNAL(fileChanged(const QString&)),
                this,    SLOT(fileChanged(const QString&)));
        connect(_watcher,     SIGNAL(directoryChanged(const QString&)),
                this,    SLOT(fileChanged(const QString&)));

        if (!sourcePath.isEmpty()) {
                setSource(sourcePath);
        }
}

Quiver::~Quiver()
{
        delete _engine;
        delete _watcher;
}

void Quiver::detectPlatform() {
        QString platform_name("unknown");

#ifdef Q_OS_IOS
        platform_name = "ios";
#endif

#ifdef Q_OS_MACX
        platform_name = "osx";
#endif

#ifdef Q_OS_WIN
        platform_name = "win";
#endif

        QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
        if (env.contains("Quiver_platformName") && !env.value("Quiver_platformName").isEmpty()) {
                platform_name = env.value("Quiver_platformName");
        }

        setPlatform(platform_name);
}

void Quiver::setPlatform(const QString & platformName) {
        _platformName = platformName;
}

void Quiver::setSource(const QString & path)
{
        _sourcePath = path;

        if (_platformName.isEmpty()) {
                detectPlatform();
        }

        _engine->addImportPath(_sourcePath);
        if (path.startsWith("qrc:/")) {
                _engine->load(QUrl(_sourcePath + "/" + _platformName + "/main.qml"));
        } else {
                QDir platformDir(_sourcePath + "/" + _platformName);
                _engine->load(QUrl::fromLocalFile(platformDir.absolutePath() + "/main.qml"));
                addWatchPath(platformDir.absolutePath());
        }

        printf("Quiver: main.qml loaded\n"); //this must be printf() and not qDebug() << for some reason ... (20141125)
        fflush(stdout);
}

void Quiver::fileChanged(const QString & path)
{
        _engine->clearComponentCache();
        emit pendingConnectionRequestChanged();

        _watcher->addPath(path);
}

void Quiver::addWatchPath(const QString & path)
{
        _watcher->addPath(path);
}

void Quiver::addWatchPaths(const QStringList & paths)
{
        _watcher->addPaths(paths);
}

void Quiver::addProperty(const QString & name, QObject * obj)
{
        _engine->rootContext()->setContextProperty(name, obj);
}

void Quiver::addImageProvider(const QString & name, QQmlImageProviderBase *image_provider) {
        _engine->addImageProvider(name, image_provider);
}
<|endoftext|>


<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "io.h"

NEXTPNR_NAMESPACE_BEGIN

std::string iovoltage_to_str(IOVoltage v)
{
    switch (v) {
    case IOVoltage::VCC_3V3:
        return "3V3";
    case IOVoltage::VCC_2V5:
        return "2V5";
    case IOVoltage::VCC_1V8:
        return "1V8";
    case IOVoltage::VCC_1V5:
        return "1V5";
    case IOVoltage::VCC_1V35:
        return "1V35";
    case IOVoltage::VCC_1V2:
        return "1V2";
    }
    NPNR_ASSERT_FALSE("unknown IO voltage");
}

IOVoltage iovoltage_from_str(const std::string &name)
{
    if (name == "3V3")
        return IOVoltage::VCC_3V3;
    if (name == "2V5")
        return IOVoltage::VCC_2V5;
    if (name == "1V8")
        return IOVoltage::VCC_1V8;
    if (name == "1V5")
        return IOVoltage::VCC_1V5;
    if (name == "1V35")
        return IOVoltage::VCC_1V35;
    if (name == "1V2")
        return IOVoltage::VCC_1V2;
    NPNR_ASSERT_FALSE("unknown IO voltage");
}

std::string iotype_to_str(IOType type)
{
    if (type == IOType::TYPE_NONE)
        return "NONE";
#define X(t)                                                                                \
    if (type == IOType::t)                                                                                \
        return #t;
#include "iotypes.inc"
#undef X
    if (type == IOType::TYPE_UNKNOWN)
        return "<unknown>";
    NPNR_ASSERT_FALSE("unknown IO type");
}

IOType ioType_from_str(const std::string &name)
{
    if (name == "NONE")
        return IOType::TYPE_NONE;
#define X(t)                                                                                \
    if (name == #t)                                                                                \
        return IOType::t;
#include "iotypes.inc"
    return IOType::TYPE_UNKNOWN;
}

IOVoltage get_vccio(IOType type)
{
    switch (type) {
    case IOType::LVTTL33:
    case IOType::LVCMOS33:
    case IOType::LVCMOS33D:
    case IOType::LVPECL33:
    case IOType::LVPECL33E:
        return IOVoltage::VCC_3V3;
    case IOType::LVCMOS25:
    case IOType::LVCMOS25D:
    case IOType::LVDS:
    case IOType::SLVS:
    case IOType::SUBLVDS:
    case IOType::LVDS25E:
    case IOType::MLVDS25:
    case IOType::MLVDS25E:
    case IOType::BLVDS25:
        return IOVoltage::VCC_2V5;
    case IOType::LVCMOS18:
    case IOType::LVCMOS18D:
    case IOType::SSTL18_I:
    case IOType::SSTL18_II:
    case IOType::SSTL18D_I:
    case IOType::SSTL18D_II:
        return IOVoltage::VCC_1V8;
    case IOType::LVCMOS15:
    case IOType::SSTL15_I:
    case IOType::SSTL15_II:
    case IOType::SSTL15D_I:
    case IOType::SSTL15D_II:
        return IOVoltage::VCC_1V5;
    case IOType::SSTL135_I:
    case IOType::SSTL135_II:
    case IOType::SSTL135D_I:
    case IOType::SSTL135D_II:
        return IOVoltage::VCC_1V35;
    case IOType::LVCMOS12:
    case IOType::HSUL12:
    case IOType::HSUL12D:
        return IOVoltage::VCC_1V2;
    default:
        NPNR_ASSERT_FALSE("unknown IO type, unable to determine VccIO");
    }
}

bool is_strong_vccio_constraint(IOType type, PortType dir, IOSide side)
{
    if (dir == PORT_OUT || dir == PORT_INOUT)
        return true;
    switch (type) {
    case IOType::TYPE_NONE:
    case IOType::LVCMOS33D:
    case IOType::LVPECL33:
    case IOType::LVDS:
    case IOType::MLVDS25:
    case IOType::BLVDS25:
    case IOType::SLVS:
    case IOType::SUBLVDS:
    case IOType::LVCMOS12:
    case IOType::HSUL12:
    case IOType::HSUL12D:
        return false;
    case IOType::LVCMOS33:
    case IOType::LVTTL33:
    case IOType::LVCMOS25:
        return (side == IOSide::LEFT || side == IOSide::RIGHT);
    default:
        return true;
    }
}

bool is_differential(IOType type)
{
    switch (type) {
    case IOType::LVCMOS33D:
    case IOType::LVCMOS25D:
    case IOType::LVPECL33:
    case IOType::LVDS:
    case IOType::MLVDS25:
    case IOType::BLVDS25:
    case IOType::SLVS:
    case IOType::SUBLVDS:
    case IOType::LVCMOS18D:
    case IOType::SSTL18D_I:
    case IOType::SSTL18D_II:
    case IOType::SSTL15D_I:
    case IOType::SSTL15D_II:
    case IOType::SSTL135D_I:
    case IOType::SSTL135D_II:
    case IOType::HSUL12D:
        return true;
    default:
        return false;
    }
}

bool is_referenced(IOType type)
{
    switch (type) {
    case IOType::SSTL18_I:
    case IOType::SSTL18_II:
    case IOType::SSTL18D_I:
    case IOType::SSTL18D_II:
    case IOType::SSTL15_I:
    case IOType::SSTL15_II:
    case IOType::SSTL15D_I:
    case IOType::SSTL15D_II:
    case IOType::SSTL135_I:
    case IOType::SSTL135_II:
    case IOType::SSTL135D_I:
    case IOType::SSTL135D_II:
    case IOType::HSUL12:
    case IOType::HSUL12D:
        return true;
    default:
        return false;
    }
}

bool valid_loc_for_io(IOType type, PortType dir, IOSide side, int z)
{
    bool is_lr = side == IOSide::LEFT || side == IOSide::RIGHT;
    if (is_referenced(type) && !is_lr)
        return false;
    if (is_differential(type) && (!is_lr || ((z % 2) == 1)))
        return false;
    if ((type == IOType::LVCMOS18D || type == IOType::LVDS) && (dir == PORT_OUT || PORT_INOUT) && z != 0)
        return false;
    return true;
}

NEXTPNR_NAMESPACE_END
<commit_msg>ecp5: Fix typo<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "io.h"

NEXTPNR_NAMESPACE_BEGIN

std::string iovoltage_to_str(IOVoltage v)
{
    switch (v) {
    case IOVoltage::VCC_3V3:
        return "3V3";
    case IOVoltage::VCC_2V5:
        return "2V5";
    case IOVoltage::VCC_1V8:
        return "1V8";
    case IOVoltage::VCC_1V5:
        return "1V5";
    case IOVoltage::VCC_1V35:
        return "1V35";
    case IOVoltage::VCC_1V2:
        return "1V2";
    }
    NPNR_ASSERT_FALSE("unknown IO voltage");
}

IOVoltage iovoltage_from_str(const std::string &name)
{
    if (name == "3V3")
        return IOVoltage::VCC_3V3;
    if (name == "2V5")
        return IOVoltage::VCC_2V5;
    if (name == "1V8")
        return IOVoltage::VCC_1V8;
    if (name == "1V5")
        return IOVoltage::VCC_1V5;
    if (name == "1V35")
        return IOVoltage::VCC_1V35;
    if (name == "1V2")
        return IOVoltage::VCC_1V2;
    NPNR_ASSERT_FALSE("unknown IO voltage");
}

std::string iotype_to_str(IOType type)
{
    if (type == IOType::TYPE_NONE)
        return "NONE";
#define X(t)                                                                                \
    if (type == IOType::t)                                                                                \
        return #t;
#include "iotypes.inc"
#undef X
    if (type == IOType::TYPE_UNKNOWN)
        return "<unknown>";
    NPNR_ASSERT_FALSE("unknown IO type");
}

IOType ioType_from_str(const std::string &name)
{
    if (name == "NONE")
        return IOType::TYPE_NONE;
#define X(t)                                                                                \
    if (name == #t)                                                                                \
        return IOType::t;
#include "iotypes.inc"
    return IOType::TYPE_UNKNOWN;
}

IOVoltage get_vccio(IOType type)
{
    switch (type) {
    case IOType::LVTTL33:
    case IOType::LVCMOS33:
    case IOType::LVCMOS33D:
    case IOType::LVPECL33:
    case IOType::LVPECL33E:
        return IOVoltage::VCC_3V3;
    case IOType::LVCMOS25:
    case IOType::LVCMOS25D:
    case IOType::LVDS:
    case IOType::SLVS:
    case IOType::SUBLVDS:
    case IOType::LVDS25E:
    case IOType::MLVDS25:
    case IOType::MLVDS25E:
    case IOType::BLVDS25:
        return IOVoltage::VCC_2V5;
    case IOType::LVCMOS18:
    case IOType::LVCMOS18D:
    case IOType::SSTL18_I:
    case IOType::SSTL18_II:
    case IOType::SSTL18D_I:
    case IOType::SSTL18D_II:
        return IOVoltage::VCC_1V8;
    case IOType::LVCMOS15:
    case IOType::SSTL15_I:
    case IOType::SSTL15_II:
    case IOType::SSTL15D_I:
    case IOType::SSTL15D_II:
        return IOVoltage::VCC_1V5;
    case IOType::SSTL135_I:
    case IOType::SSTL135_II:
    case IOType::SSTL135D_I:
    case IOType::SSTL135D_II:
        return IOVoltage::VCC_1V35;
    case IOType::LVCMOS12:
    case IOType::HSUL12:
    case IOType::HSUL12D:
        return IOVoltage::VCC_1V2;
    default:
        NPNR_ASSERT_FALSE("unknown IO type, unable to determine VccIO");
    }
}

bool is_strong_vccio_constraint(IOType type, PortType dir, IOSide side)
{
    if (dir == PORT_OUT || dir == PORT_INOUT)
        return true;
    switch (type) {
    case IOType::TYPE_NONE:
    case IOType::LVCMOS33D:
    case IOType::LVPECL33:
    case IOType::LVDS:
    case IOType::MLVDS25:
    case IOType::BLVDS25:
    case IOType::SLVS:
    case IOType::SUBLVDS:
    case IOType::LVCMOS12:
    case IOType::HSUL12:
    case IOType::HSUL12D:
        return false;
    case IOType::LVCMOS33:
    case IOType::LVTTL33:
    case IOType::LVCMOS25:
        return (side == IOSide::LEFT || side == IOSide::RIGHT);
    default:
        return true;
    }
}

bool is_differential(IOType type)
{
    switch (type) {
    case IOType::LVCMOS33D:
    case IOType::LVCMOS25D:
    case IOType::LVPECL33:
    case IOType::LVDS:
    case IOType::MLVDS25:
    case IOType::BLVDS25:
    case IOType::SLVS:
    case IOType::SUBLVDS:
    case IOType::LVCMOS18D:
    case IOType::SSTL18D_I:
    case IOType::SSTL18D_II:
    case IOType::SSTL15D_I:
    case IOType::SSTL15D_II:
    case IOType::SSTL135D_I:
    case IOType::SSTL135D_II:
    case IOType::HSUL12D:
        return true;
    default:
        return false;
    }
}

bool is_referenced(IOType type)
{
    switch (type) {
    case IOType::SSTL18_I:
    case IOType::SSTL18_II:
    case IOType::SSTL18D_I:
    case IOType::SSTL18D_II:
    case IOType::SSTL15_I:
    case IOType::SSTL15_II:
    case IOType::SSTL15D_I:
    case IOType::SSTL15D_II:
    case IOType::SSTL135_I:
    case IOType::SSTL135_II:
    case IOType::SSTL135D_I:
    case IOType::SSTL135D_II:
    case IOType::HSUL12:
    case IOType::HSUL12D:
        return true;
    default:
        return false;
    }
}

bool valid_loc_for_io(IOType type, PortType dir, IOSide side, int z)
{
    bool is_lr = side == IOSide::LEFT || side == IOSide::RIGHT;
    if (is_referenced(type) && !is_lr)
        return false;
    if (is_differential(type) && (!is_lr || ((z % 2) == 1)))
        return false;
    if ((type == IOType::LVCMOS18D || type == IOType::LVDS) && (dir == PORT_OUT || dir == PORT_INOUT) && z != 0)
        return false;
    return true;
}

NEXTPNR_NAMESPACE_END
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "temp_scaffolding_stubs.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/thread.h"
#include "base/path_service.h"
#include "base/string_piece.h"
#include "base/singleton.h"
#include "base/task.h"
#include "build/build_config.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/history_url_provider.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/cache_manager_host.h"
#include "chrome/browser/debugger/debugger_shell.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/history/in_memory_history_backend.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/render_widget_helper.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/tab_contents/web_contents.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/resource_bundle.h"
#include "net/url_request/url_request_context.h"
#include "webkit/glue/webcursor.h"
#include "webkit/glue/webkit_glue.h"

// static
size_t SessionRestore::num_tabs_to_load_ = 0;

//--------------------------------------------------------------------------

// static
size_t AutocompleteProvider::max_matches_;

// static
size_t AutocompleteResult::max_matches_;

//static
std::string AutocompleteInput::TypeToString(AutocompleteInput::Type type) {
  NOTIMPLEMENTED();
  return "";
}

//static
std::string AutocompleteMatch::TypeToString(AutocompleteMatch::Type type) {
  NOTIMPLEMENTED();
  return "";
}

//--------------------------------------------------------------------------

UserDataManager* UserDataManager::instance_ = NULL;

UserDataManager* UserDataManager::Create() {
  DCHECK(!instance_);
  std::wstring user_data;
  PathService::Get(chrome::DIR_USER_DATA, &user_data);
  instance_ = new UserDataManager(user_data);
  return instance_;
}

UserDataManager* UserDataManager::Get() {
  DCHECK(instance_);
  return instance_;
}

bool ShellIntegration::SetAsDefaultBrowser() {
  NOTIMPLEMENTED();
  return true;
}

bool ShellIntegration::IsDefaultBrowser() {
  NOTIMPLEMENTED();
  return true;
}

//--------------------------------------------------------------------------

namespace browser_shutdown {
bool delete_resources_on_shutdown = true;
void ReadLastShutdownInfo()  { NOTIMPLEMENTED(); }
void Shutdown() { NOTIMPLEMENTED(); }
void OnShutdownStarting(ShutdownType type) { NOTIMPLEMENTED(); }
}

// static
bool FirstRun::IsChromeFirstRun() {
  NOTIMPLEMENTED();
  return false;
}

// static
bool FirstRun::ProcessMasterPreferences(const FilePath& user_data_dir,
                                        const FilePath& master_prefs_path,
                                        int* preference_details) {
  NOTIMPLEMENTED();
  return false;
}

// static
int FirstRun::ImportNow(Profile* profile, const CommandLine& cmdline) {
  NOTIMPLEMENTED();
  return 0;
}

// static
bool Upgrade::IsBrowserAlreadyRunning() {
  NOTIMPLEMENTED();
  return false;
}

// static
bool Upgrade::RelaunchChromeBrowser(const CommandLine& command_line) {
  NOTIMPLEMENTED();
  return true;
}

// static
bool Upgrade::SwapNewChromeExeIfPresent() {
  NOTIMPLEMENTED();
  return true;
}

void OpenFirstRunDialog(Profile* profile) { NOTIMPLEMENTED(); }

GURL NewTabUIURL() {
  NOTIMPLEMENTED();
  return GURL();
}

//--------------------------------------------------------------------------

PluginService* PluginService::GetInstance() {
  return Singleton<PluginService>::get();
}

PluginService::PluginService()
    : main_message_loop_(MessageLoop::current()),
      resource_dispatcher_host_(NULL),
      ui_locale_(g_browser_process->GetApplicationLocale()),
      plugin_shutdown_handler_(NULL) {
}

PluginService::~PluginService() {
}

void PluginService::SetChromePluginDataDir(const FilePath& data_dir) {
  AutoLock lock(lock_);
  chrome_plugin_data_dir_ = data_dir;
}

//--------------------------------------------------------------------------

void InstallJankometer(const CommandLine&) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------

void Browser::Observe(NotificationType type,
                      const NotificationSource& source,
                      const NotificationDetails& details) {
  NOTIMPLEMENTED();
}

GURL Browser::GetHomePage() {
  NOTIMPLEMENTED();
  return GURL("http://dev.chromium.org");
}

void Browser::LoadingStateChanged(TabContents* source) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------

TabContents* TabContents::CreateWithType(TabContentsType type,
                                         Profile* profile,
                                         SiteInstance* instance) {
  TabContents* contents;

  switch (type) {
    case TAB_CONTENTS_WEB:
      contents = new WebContents(profile, instance, NULL, MSG_ROUTING_NONE,
                                 NULL);
      break;
    default:
      NOTREACHED() << "Don't know how to create tab contents of type " << type;
      contents = NULL;
  }

  if (contents)
    contents->CreateView();

  return contents;
}

void TabContents::SetupController(Profile* profile) {
  DCHECK(!controller_);
  controller_ = new NavigationController(this, profile);
}

Profile* TabContents::profile() const {
  return controller_ ? controller_->profile() : NULL;
}

void TabContents::CloseContents() {
  // Destroy our NavigationController, which will Destroy all tabs it owns.
  controller_->Destroy();
  // Note that the controller may have deleted us at this point,
  // so don't touch any member variables here.
}

void TabContents::Destroy() {
  // TODO(pinkerton): this isn't the real version of Destroy(), just enough to
  // get the scaffolding working.

  // Notify any observer that have a reference on this tab contents.
  NotificationService::current()->Notify(
      NotificationType::TAB_CONTENTS_DESTROYED,
      Source<TabContents>(this),
      NotificationService::NoDetails());

  // Notify our NavigationController.  Make sure we are deleted first, so
  // that the controller is the last to die.
  NavigationController* controller = controller_;
  TabContentsType type = this->type();

  delete this;

  controller->TabContentsWasDestroyed(type);
}

const GURL& TabContents::GetURL() const {
  // We may not have a navigation entry yet
  NavigationEntry* entry = controller_->GetActiveEntry();
  return entry ? entry->display_url() : GURL::EmptyGURL();
}

const std::wstring& TabContents::GetTitle() const {
  // We use the title for the last committed entry rather than a pending
  // navigation entry. For example, when the user types in a URL, we want to
  // keep the old page's title until the new load has committed and we get a new
  // title.
  // The exception is with transient pages, for which we really want to use
  // their title, as they are not committed.
  NavigationEntry* entry = controller_->GetTransientEntry();
  if (entry)
    return entry->GetTitleForDisplay();

  entry = controller_->GetLastCommittedEntry();
  if (entry)
    return entry->GetTitleForDisplay();
  else if (controller_->LoadingURLLazily())
    return controller_->GetLazyTitle();
  return EmptyWString();
}

void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
  if (delegate_)
    delegate_->NavigationStateChanged(this, changed_flags);
}

void TabContents::OpenURL(const GURL& url, const GURL& referrer,
                          WindowOpenDisposition disposition,
                          PageTransition::Type transition) {
  if (delegate_)
    delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
}

void TabContents::SetIsLoading(bool is_loading,
                               LoadNotificationDetails* details) {
  // TODO(port): this is a subset of SetIsLoading() as a stub
  is_loading_ = is_loading;
}

//--------------------------------------------------------------------------

bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
  NOTIMPLEMENTED();
  return false;
}

bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
                                    Event event) {
  NOTIMPLEMENTED();
  return false;
}

// This depends on porting all the plugin IPC messages.
bool IsPluginProcess() {
  NOTIMPLEMENTED();
  return false;
}

//--------------------------------------------------------------------------

namespace chrome_browser_net {

void EnableDnsPrefetch(bool) { NOTIMPLEMENTED(); }

void DnsPrefetchList(const std::vector<std::string>& hostnames) { NOTIMPLEMENTED(); }

}  // namespace chrome_browser_net

//--------------------------------------------------------------------------

// This is from chrome_plugin_util.cc.
void CPB_Free(void* memory) { NOTIMPLEMENTED(); }

//--------------------------------------------------------------------------

void RunJavascriptMessageBox(WebContents* web_contents,
                             int dialog_flags,
                             const std::wstring& message_text,
                             const std::wstring& default_prompt_text,
                             bool display_suppress_checkbox,
                             IPC::Message* reply_msg) {
  NOTIMPLEMENTED();
}

void RunBeforeUnloadDialog(WebContents* web_contents,
                           const std::wstring& message_text,
                           IPC::Message* reply_msg) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------

void RunRepostFormWarningDialog(NavigationController*) {
}

#if defined(OS_MACOSX)
ResourceBundle* ResourceBundle::g_shared_instance_ = NULL;

// GetBitmapNamed() will leak, but there's no way around it for stubs.
SkBitmap* ResourceBundle::GetBitmapNamed(int) {
  NOTIMPLEMENTED();
  return new SkBitmap();
}
ResourceBundle::ResourceBundle() { }
ResourceBundle& ResourceBundle::GetSharedInstance() {
  NOTIMPLEMENTED();
  if (!g_shared_instance_)
    g_shared_instance_ = new ResourceBundle;
  return *g_shared_instance_;
}

StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
  NOTIMPLEMENTED();
  return StringPiece();
}

std::string ResourceBundle::GetDataResource(int resource_id) {
  NOTIMPLEMENTED();
  return "";
}

#endif

LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
                                URLRequest* request,
                                MessageLoop* ui_loop) {
  NOTIMPLEMENTED();
  return NULL;
}

void ProcessWatcher::EnsureProcessTerminated(int) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------
namespace webkit_glue {

bool IsDefaultPluginEnabled() {
  NOTIMPLEMENTED();
  return false;
}

#if defined(OS_MACOSX)
bool ClipboardIsFormatAvailable(Clipboard::FormatType format) {
  NOTIMPLEMENTED();
  return false;
}
#endif

}  // webkit_glue

#ifndef CHROME_DEBUGGER_DISABLED
DebuggerShell::DebuggerShell(DebuggerInputOutput *io) { }
DebuggerShell::~DebuggerShell() { }
void DebuggerShell::Start() { NOTIMPLEMENTED(); }
void DebuggerShell::Debug(TabContents* tab) { NOTIMPLEMENTED(); }
void DebuggerShell::DebugMessage(const std::wstring& msg) { NOTIMPLEMENTED(); }
void DebuggerShell::OnDebugAttach() { NOTIMPLEMENTED(); }
void DebuggerShell::OnDebugDisconnect() { NOTIMPLEMENTED(); }
void DebuggerShell::DidConnect() { NOTIMPLEMENTED(); }
void DebuggerShell::DidDisconnect() { NOTIMPLEMENTED(); }
void DebuggerShell::ProcessCommand(const std::wstring& data) {
  NOTIMPLEMENTED();
}
#endif  // !CHROME_DEBUGGER_DISABLED

SSLPolicy* SSLPolicy::GetDefaultPolicy() {
  NOTIMPLEMENTED();
  return NULL;
}

void HistoryURLProvider::ExecuteWithDB(history::HistoryBackend*,
                                       history::URLDatabase*,
                                       HistoryURLProviderParams*) {
  NOTIMPLEMENTED();
}

namespace bookmark_utils {

bool MoreRecentlyAdded(BookmarkNode* n1, BookmarkNode* n2) {
  NOTIMPLEMENTED();
  return false;
}

std::vector<BookmarkNode*> GetMostRecentlyModifiedGroups(BookmarkModel* model,
                                                         size_t max_count) {
  NOTIMPLEMENTED();
  return std::vector<BookmarkNode*>();
}

}
<commit_msg>Stub out ~ScopableCPRequest().<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "temp_scaffolding_stubs.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/thread.h"
#include "base/path_service.h"
#include "base/string_piece.h"
#include "base/singleton.h"
#include "base/task.h"
#include "build/build_config.h"
#include "chrome/browser/autocomplete/autocomplete.h"
#include "chrome/browser/autocomplete/history_url_provider.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/cache_manager_host.h"
#include "chrome/browser/debugger/debugger_shell.h"
#include "chrome/browser/first_run.h"
#include "chrome/browser/history/in_memory_history_backend.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/renderer_host/render_widget_helper.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/browser/rlz/rlz.h"
#include "chrome/browser/search_engines/template_url_prepopulate_data.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/tab_contents/web_contents.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_plugin_util.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_service.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/resource_bundle.h"
#include "net/url_request/url_request_context.h"
#include "webkit/glue/webcursor.h"
#include "webkit/glue/webkit_glue.h"

// static
size_t SessionRestore::num_tabs_to_load_ = 0;

//--------------------------------------------------------------------------

// static
size_t AutocompleteProvider::max_matches_;

// static
size_t AutocompleteResult::max_matches_;

//static
std::string AutocompleteInput::TypeToString(AutocompleteInput::Type type) {
  NOTIMPLEMENTED();
  return "";
}

//static
std::string AutocompleteMatch::TypeToString(AutocompleteMatch::Type type) {
  NOTIMPLEMENTED();
  return "";
}

//--------------------------------------------------------------------------

UserDataManager* UserDataManager::instance_ = NULL;

UserDataManager* UserDataManager::Create() {
  DCHECK(!instance_);
  std::wstring user_data;
  PathService::Get(chrome::DIR_USER_DATA, &user_data);
  instance_ = new UserDataManager(user_data);
  return instance_;
}

UserDataManager* UserDataManager::Get() {
  DCHECK(instance_);
  return instance_;
}

bool ShellIntegration::SetAsDefaultBrowser() {
  NOTIMPLEMENTED();
  return true;
}

bool ShellIntegration::IsDefaultBrowser() {
  NOTIMPLEMENTED();
  return true;
}

//--------------------------------------------------------------------------

namespace browser_shutdown {
bool delete_resources_on_shutdown = true;
void ReadLastShutdownInfo()  { NOTIMPLEMENTED(); }
void Shutdown() { NOTIMPLEMENTED(); }
void OnShutdownStarting(ShutdownType type) { NOTIMPLEMENTED(); }
}

// static
bool FirstRun::IsChromeFirstRun() {
  NOTIMPLEMENTED();
  return false;
}

// static
bool FirstRun::ProcessMasterPreferences(const FilePath& user_data_dir,
                                        const FilePath& master_prefs_path,
                                        int* preference_details) {
  NOTIMPLEMENTED();
  return false;
}

// static
int FirstRun::ImportNow(Profile* profile, const CommandLine& cmdline) {
  NOTIMPLEMENTED();
  return 0;
}

// static
bool Upgrade::IsBrowserAlreadyRunning() {
  NOTIMPLEMENTED();
  return false;
}

// static
bool Upgrade::RelaunchChromeBrowser(const CommandLine& command_line) {
  NOTIMPLEMENTED();
  return true;
}

// static
bool Upgrade::SwapNewChromeExeIfPresent() {
  NOTIMPLEMENTED();
  return true;
}

void OpenFirstRunDialog(Profile* profile) { NOTIMPLEMENTED(); }

GURL NewTabUIURL() {
  NOTIMPLEMENTED();
  return GURL();
}

//--------------------------------------------------------------------------

PluginService* PluginService::GetInstance() {
  return Singleton<PluginService>::get();
}

PluginService::PluginService()
    : main_message_loop_(MessageLoop::current()),
      resource_dispatcher_host_(NULL),
      ui_locale_(g_browser_process->GetApplicationLocale()),
      plugin_shutdown_handler_(NULL) {
}

PluginService::~PluginService() {
}

void PluginService::SetChromePluginDataDir(const FilePath& data_dir) {
  AutoLock lock(lock_);
  chrome_plugin_data_dir_ = data_dir;
}

//--------------------------------------------------------------------------

void InstallJankometer(const CommandLine&) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------

void Browser::Observe(NotificationType type,
                      const NotificationSource& source,
                      const NotificationDetails& details) {
  NOTIMPLEMENTED();
}

GURL Browser::GetHomePage() {
  NOTIMPLEMENTED();
  return GURL("http://dev.chromium.org");
}

void Browser::LoadingStateChanged(TabContents* source) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------

TabContents* TabContents::CreateWithType(TabContentsType type,
                                         Profile* profile,
                                         SiteInstance* instance) {
  TabContents* contents;

  switch (type) {
    case TAB_CONTENTS_WEB:
      contents = new WebContents(profile, instance, NULL, MSG_ROUTING_NONE,
                                 NULL);
      break;
    default:
      NOTREACHED() << "Don't know how to create tab contents of type " << type;
      contents = NULL;
  }

  if (contents)
    contents->CreateView();

  return contents;
}

void TabContents::SetupController(Profile* profile) {
  DCHECK(!controller_);
  controller_ = new NavigationController(this, profile);
}

Profile* TabContents::profile() const {
  return controller_ ? controller_->profile() : NULL;
}

void TabContents::CloseContents() {
  // Destroy our NavigationController, which will Destroy all tabs it owns.
  controller_->Destroy();
  // Note that the controller may have deleted us at this point,
  // so don't touch any member variables here.
}

void TabContents::Destroy() {
  // TODO(pinkerton): this isn't the real version of Destroy(), just enough to
  // get the scaffolding working.

  // Notify any observer that have a reference on this tab contents.
  NotificationService::current()->Notify(
      NotificationType::TAB_CONTENTS_DESTROYED,
      Source<TabContents>(this),
      NotificationService::NoDetails());

  // Notify our NavigationController.  Make sure we are deleted first, so
  // that the controller is the last to die.
  NavigationController* controller = controller_;
  TabContentsType type = this->type();

  delete this;

  controller->TabContentsWasDestroyed(type);
}

const GURL& TabContents::GetURL() const {
  // We may not have a navigation entry yet
  NavigationEntry* entry = controller_->GetActiveEntry();
  return entry ? entry->display_url() : GURL::EmptyGURL();
}

const std::wstring& TabContents::GetTitle() const {
  // We use the title for the last committed entry rather than a pending
  // navigation entry. For example, when the user types in a URL, we want to
  // keep the old page's title until the new load has committed and we get a new
  // title.
  // The exception is with transient pages, for which we really want to use
  // their title, as they are not committed.
  NavigationEntry* entry = controller_->GetTransientEntry();
  if (entry)
    return entry->GetTitleForDisplay();

  entry = controller_->GetLastCommittedEntry();
  if (entry)
    return entry->GetTitleForDisplay();
  else if (controller_->LoadingURLLazily())
    return controller_->GetLazyTitle();
  return EmptyWString();
}

void TabContents::NotifyNavigationStateChanged(unsigned changed_flags) {
  if (delegate_)
    delegate_->NavigationStateChanged(this, changed_flags);
}

void TabContents::OpenURL(const GURL& url, const GURL& referrer,
                          WindowOpenDisposition disposition,
                          PageTransition::Type transition) {
  if (delegate_)
    delegate_->OpenURLFromTab(this, url, referrer, disposition, transition);
}

void TabContents::SetIsLoading(bool is_loading,
                               LoadNotificationDetails* details) {
  // TODO(port): this is a subset of SetIsLoading() as a stub
  is_loading_ = is_loading;
}

//--------------------------------------------------------------------------

bool RLZTracker::GetAccessPointRlz(AccessPoint point, std::wstring* rlz) {
  NOTIMPLEMENTED();
  return false;
}

bool RLZTracker::RecordProductEvent(Product product, AccessPoint point,
                                    Event event) {
  NOTIMPLEMENTED();
  return false;
}

// This depends on porting all the plugin IPC messages.
bool IsPluginProcess() {
  NOTIMPLEMENTED();
  return false;
}

//--------------------------------------------------------------------------

namespace chrome_browser_net {

void EnableDnsPrefetch(bool) { NOTIMPLEMENTED(); }

void DnsPrefetchList(const std::vector<std::string>& hostnames) { NOTIMPLEMENTED(); }

}  // namespace chrome_browser_net

//--------------------------------------------------------------------------

// This is from chrome_plugin_util.cc.
void CPB_Free(void* memory) { NOTIMPLEMENTED(); }

//--------------------------------------------------------------------------

void RunJavascriptMessageBox(WebContents* web_contents,
                             int dialog_flags,
                             const std::wstring& message_text,
                             const std::wstring& default_prompt_text,
                             bool display_suppress_checkbox,
                             IPC::Message* reply_msg) {
  NOTIMPLEMENTED();
}

void RunBeforeUnloadDialog(WebContents* web_contents,
                           const std::wstring& message_text,
                           IPC::Message* reply_msg) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------

void RunRepostFormWarningDialog(NavigationController*) {
}

#if defined(OS_MACOSX)
ResourceBundle* ResourceBundle::g_shared_instance_ = NULL;

// GetBitmapNamed() will leak, but there's no way around it for stubs.
SkBitmap* ResourceBundle::GetBitmapNamed(int) {
  NOTIMPLEMENTED();
  return new SkBitmap();
}
ResourceBundle::ResourceBundle() { }
ResourceBundle& ResourceBundle::GetSharedInstance() {
  NOTIMPLEMENTED();
  if (!g_shared_instance_)
    g_shared_instance_ = new ResourceBundle;
  return *g_shared_instance_;
}

StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
  NOTIMPLEMENTED();
  return StringPiece();
}

std::string ResourceBundle::GetDataResource(int resource_id) {
  NOTIMPLEMENTED();
  return "";
}

#endif

LoginHandler* CreateLoginPrompt(net::AuthChallengeInfo* auth_info,
                                URLRequest* request,
                                MessageLoop* ui_loop) {
  NOTIMPLEMENTED();
  return NULL;
}

void ProcessWatcher::EnsureProcessTerminated(int) {
  NOTIMPLEMENTED();
}

//--------------------------------------------------------------------------
namespace webkit_glue {

bool IsDefaultPluginEnabled() {
  NOTIMPLEMENTED();
  return false;
}

#if defined(OS_MACOSX)
bool ClipboardIsFormatAvailable(Clipboard::FormatType format) {
  NOTIMPLEMENTED();
  return false;
}
#endif

}  // webkit_glue

#ifndef CHROME_DEBUGGER_DISABLED
DebuggerShell::DebuggerShell(DebuggerInputOutput *io) { }
DebuggerShell::~DebuggerShell() { }
void DebuggerShell::Start() { NOTIMPLEMENTED(); }
void DebuggerShell::Debug(TabContents* tab) { NOTIMPLEMENTED(); }
void DebuggerShell::DebugMessage(const std::wstring& msg) { NOTIMPLEMENTED(); }
void DebuggerShell::OnDebugAttach() { NOTIMPLEMENTED(); }
void DebuggerShell::OnDebugDisconnect() { NOTIMPLEMENTED(); }
void DebuggerShell::DidConnect() { NOTIMPLEMENTED(); }
void DebuggerShell::DidDisconnect() { NOTIMPLEMENTED(); }
void DebuggerShell::ProcessCommand(const std::wstring& data) {
  NOTIMPLEMENTED();
}
#endif  // !CHROME_DEBUGGER_DISABLED

SSLPolicy* SSLPolicy::GetDefaultPolicy() {
  NOTIMPLEMENTED();
  return NULL;
}

void HistoryURLProvider::ExecuteWithDB(history::HistoryBackend*,
                                       history::URLDatabase*,
                                       HistoryURLProviderParams*) {
  NOTIMPLEMENTED();
}

namespace bookmark_utils {

bool MoreRecentlyAdded(BookmarkNode* n1, BookmarkNode* n2) {
  NOTIMPLEMENTED();
  return false;
}

std::vector<BookmarkNode*> GetMostRecentlyModifiedGroups(BookmarkModel* model,
                                                         size_t max_count) {
  NOTIMPLEMENTED();
  return std::vector<BookmarkNode*>();
}

}

ScopableCPRequest::~ScopableCPRequest() {
  NOTIMPLEMENTED();
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2015-2017.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "dll/neural/dense_layer.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/deconv_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "ae_config.hpp" // Must be first

#include "ae_conv.hpp"

#include "ae_evaluation.hpp"

namespace {

template<size_t N>
void hybrid_deep_evaluate(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches, float learning_rate, size_t epochs) {
    static constexpr size_t KK = 9;
    static constexpr size_t K1 = 9;

    static constexpr size_t NH1_1 = patch_height - K1 + 1;
    static constexpr size_t NH1_2 = patch_width - K1 + 1;

    using network_t = typename dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, patch_height, patch_width, KK, NH1_1, NH1_2>::layer_t,
            typename dll::dense_desc<KK * NH1_1 * NH1_2, N>::layer_t,
            typename dll::dense_desc<N, KK * NH1_1 * NH1_2>::layer_t,
            dll::deconv_desc<KK, NH1_1, NH1_2, 1, K1, K1>::layer_t
        >,
        dll::momentum,
        dll::weight_decay<dll::decay_type::L2>,
        dll::trainer<dll::sgd_trainer>,
        dll::batch_size<batch_size>,
        dll::shuffle
    >::dbn_t;

    auto net = std::make_unique<network_t>();

    net->display();

    // Configure the network
    net->learning_rate    = learning_rate;
    net->initial_momentum = 0.9;
    net->momentum         = 0.9;

    // Train as autoencoder
    net->fine_tune_ae(training_patches, epochs);

    auto folder = spot::evaluate_patches_ae<1, image_t>(dataset, set, conf, *net, train_word_names, test_image_names, false, params);
    std::cout << "AE-Result: Hybrid-Deep(" << N << "):" << folder << std::endl;
}

} // end of anonymous namespace

void hybrid_deep_evaluate_all(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches){
    if (conf.hybrid && !conf.rbm) {
        const auto lr = 1e-3;

        hybrid_deep_evaluate<10>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<20>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<30>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<40>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<50>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<60>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<70>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<80>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<90>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<100>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
    }
}
<commit_msg>Fix the number of kernels<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2015-2017.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "dll/neural/dense_layer.hpp"
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/deconv_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"

#include "ae_config.hpp" // Must be first

#include "ae_conv.hpp"

#include "ae_evaluation.hpp"

namespace {

template<size_t N>
void hybrid_deep_evaluate(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches, float learning_rate, size_t epochs) {
    static constexpr size_t KK = 6;
    static constexpr size_t K1 = 9;

    static constexpr size_t NH1_1 = patch_height - K1 + 1;
    static constexpr size_t NH1_2 = patch_width - K1 + 1;

    using network_t = typename dll::dbn_desc<
        dll::dbn_layers<
            dll::conv_desc<1, patch_height, patch_width, KK, NH1_1, NH1_2>::layer_t,
            typename dll::dense_desc<KK * NH1_1 * NH1_2, N>::layer_t,
            typename dll::dense_desc<N, KK * NH1_1 * NH1_2>::layer_t,
            dll::deconv_desc<KK, NH1_1, NH1_2, 1, K1, K1>::layer_t
        >,
        dll::momentum,
        dll::weight_decay<dll::decay_type::L2>,
        dll::trainer<dll::sgd_trainer>,
        dll::batch_size<batch_size>,
        dll::shuffle
    >::dbn_t;

    auto net = std::make_unique<network_t>();

    net->display();

    // Configure the network
    net->learning_rate    = learning_rate;
    net->initial_momentum = 0.9;
    net->momentum         = 0.9;

    // Train as autoencoder
    net->fine_tune_ae(training_patches, epochs);

    auto folder = spot::evaluate_patches_ae<1, image_t>(dataset, set, conf, *net, train_word_names, test_image_names, false, params);
    std::cout << "AE-Result: Hybrid-Deep(" << N << "):" << folder << std::endl;
}

} // end of anonymous namespace

void hybrid_deep_evaluate_all(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches){
    if (conf.hybrid && !conf.rbm) {
        const auto lr = 1e-3;

        hybrid_deep_evaluate<10>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<20>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<30>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<40>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<50>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<60>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<70>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<80>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<90>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
        hybrid_deep_evaluate<100>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, lr, epochs);
    }
}
<|endoftext|>