Пример #1
0
	void AppBinding::AppURLToPath(const ValueList& args, SharedValue result)
	{
		//FIXME - use FileUtils for this... so we can a common implementation
		
		result->SetString("");

		if (args.size() < 0 || !args.at(0)->IsString())
			return;

//FIXME: take into consider the appid which is in the host position of the URL
		std::string url = std::string(args.at(0)->ToString());
		if (url.find("app://") == 0)
		{
			url = url.substr(6, url.length() - 6);
		}
		std::string path = Poco::Environment::get("KR_HOME", "");

		result->SetString(std::string(path + KR_PATH_SEP + kAppURLPrefix + KR_PATH_SEP + url).c_str());
	}
Пример #2
0
void SDLIntegration::capture(ValueList& axisValues, ValueList& buttonValues) const
{
    if (_joystick)
    {
        SDL_JoystickUpdate();
        
        axisValues.resize(_numAxes);
        for(int ai=0; ai<_numAxes; ++ai)
        {
            axisValues[ai] = SDL_JoystickGetAxis(_joystick, ai);
        }

        buttonValues.resize(_numButtons);
        for(int bi=0; bi<_numButtons; ++bi)
        {
            buttonValues[bi] = SDL_JoystickGetButton(_joystick, bi);
        }
    }
}
Пример #3
0
	void AppBinding::StdIn(const ValueList& args, KValueRef result)
	{
		args.VerifyException("stdin", "?ss");
		std::string input;
		char delimiter = '\n';

		if (args.size() >= 1)
		{
			std::cout << args.GetString(0);
		}

		if (args.size() >= 2)
		{
			delimiter = args.GetString(1).at(0);
		}

		getline(std::cin, input, delimiter);
		result->SetString(input);
	}
	void TCPSocketBinding::OnRead(const Poco::AutoPtr<ReadableNotification>& n)
	{
		std::string eprefix = "TCPSocketBinding::OnRead: ";
		try
		{
			// Always read bytes, so that the tubes get cleared.
			char data[BUFFER_SIZE + 1];
			int size = socket.receiveBytes(&data, BUFFER_SIZE);

			bool read_complete = (size <= 0);
			if (read_complete && !this->onReadComplete.isNull())
			{
				ValueList args;
				ti_host->InvokeMethodOnMainThread(this->onReadComplete, args, false);
			}
			else if (!read_complete && !this->onRead.isNull())
			{
				data[size] = '\0';

				ValueList args;
				args.push_back(Value::NewString(data));
				ti_host->InvokeMethodOnMainThread(this->onRead, args, false);
			}
		}
		catch(ValueException& e)
		{
			std::cerr << eprefix << *(e.GetValue()->DisplayString()) << std::endl;
			ValueList args(Value::NewString(e.ToString()));
			ti_host->InvokeMethodOnMainThread(this->onError, args, false);
		}
		catch(Poco::Exception &e)
		{
			std::cerr << eprefix << e.displayText() << std::endl;
			ValueList args(Value::NewString(e.displayText()));
			ti_host->InvokeMethodOnMainThread(this->onError, args, false);
		}
		catch(...)
		{
			std::cerr << eprefix << "Unknown exception" << std::endl;
			ValueList args(Value::NewString("Unknown exception"));
			ti_host->InvokeMethodOnMainThread(this->onError, args, false);
		}
	}
Пример #5
0
 void ResultSetBinding::FieldByName(const ValueList& args, KValueRef result)
 {
     result->SetNull();
     if (!rs.isNull())
     {
         args.VerifyException("fieldByName", "s");
         std::string name = args.at(0)->ToString();
         size_t count = rs->columnCount();
         for (size_t i = 0; i<count; i++)
         {
             const std::string &str = rs->columnName(i);
             if (str == name)
             {
                 TransformValue(i,result);
                 break;
             }
         }
     }
 }
Пример #6
0
	void Blob::Substr(const ValueList& args, SharedValue result)
	{
		// This method now follows the spec located at:
		// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/substr
		args.VerifyException("Blob.substr", "i,?i");
		std::string target = "";
		if (this->length > 0)
		{
			target = this->buffer;
		}

		int start = args.GetInt(0);
		if (start > 0 && start >= this->length)
		{
			result->SetString("");
			return;
		}

		if (start < 0 && (-1*start) > this->length)
		{
			start = 0;
		}
		else if (start < 0)
		{
			start = this->length + start;
		}

		int length = this->length - start;
		if (args.size() > 1)
		{
			length = args.GetInt(1);
		}

		if (length <= 0)
		{
			result->SetString("");
			return;
		}

		std::string r = target.substr(start, length);
		result->SetString(r);
	}
Пример #7
0
void  Compiler::operator()( ValueListMore &  values,
                            boost::optional< Value > &  value_first,
                            ValueList &  values_middle,
                            boost::optional< Value > &  value_last ) const
{
  if ( value_first )
  {
    Value &  value = *value_first;
    values.data_.emplace_back( std::move( value ) );
    values.has_front_any_ = false;
  }
  std::move( values_middle.begin(), values_middle.end(),
             std::back_inserter( values.data_ ) );
  if ( value_last )
  {
    Value &  value = *value_last;
    values.data_.emplace_back( std::move( value ) );
    values.has_back_any_ = false;
  }
}
Пример #8
0
	void Worker::PostMessage(const ValueList& args, SharedValue result)
	{
		// store the message in our queue (waiting for the lock) and
		// then signal the thread to wake up to process the message
		SharedValue message = args.at(0);
		{
			Poco::ScopedLock<Poco::Mutex> lock(mutex);
			this->messages.push_back(message);
		}
		this->condition.signal();
	}
Пример #9
0
void NetworkBinding::AddConnectivityListener(const ValueList& args, SharedValue result)
{
    ArgUtils::VerifyArgsException("addConnectivityListener", args, "m");
    SharedBoundMethod target = args.at(0)->ToMethod();

    Listener listener = Listener();
    listener.id = this->next_listener_id++;
    listener.callback = target;
    this->listeners.push_back(listener);
    result->SetInt(listener.id);
}
Пример #10
0
	void Bytes::_LastIndexOf(const ValueList& args, KValueRef result)
	{
		// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/lastIndexOf
		args.VerifyException("Bytes.lastIndexOf", "s,?i");

		std::string target(this->AsString());
		int start = args.GetInt(1, target.length() + 1);
		if (start < 0) start = 0;
		size_t pos = target.rfind(args.GetString(0), start);

		if (pos == std::string::npos)
		{
			// No matches found
			result->SetInt(-1);
		}
		else
		{
			result->SetInt(pos);
		}
	}
Пример #11
0
	void NetworkBinding::RemoveConnectivityListener(
		const ValueList& args,
		SharedValue result)
	{
		args.VerifyException("removeConnectivityListener", "n");
		int id = args.at(0)->ToInt();

		std::vector<Listener>::iterator it = this->listeners.begin();
		while (it != this->listeners.end())
		{
			if ((*it).id == id)
			{
				this->listeners.erase(it);
				result->SetBool(true);
				return;
			}
			it++;
		}
		result->SetBool(false);
	}
Пример #12
0
// Convert a DATAList flag into a long integer value
long list_flag_value_complete( DATAExpression *flag, struct flag_type *flag_table ) {
  ValueList *list = flag->eval().asList();
  char flagString[MAX_STRING_LENGTH];
  flagString[0] = '\0';

  if ( list->size == 0 || ( list->size == 1 && !str_cmp( "none", list->elems[0].asStr() ) ) )
    return 0;
  
  // Convert the list into a string
  for ( int i = 0; i < list->size; i++ ) {
    strcat( flagString, list->elems[i].asStr() );
    if ( i < list->size-1 )
      strcat( flagString, " " );
  }

  list->explicit_free();

  // Send the string to flag_value
  return flag_value_complete( flag_table, flagString );
}
	void WorkerContext::ImportScripts(const ValueList &args, SharedValue result)
	{
		Logger *logger = Logger::Get("WorkerContext");
		
		SharedKMethod appURLToPath = host->GetGlobalObject()->GetNS("App.appURLToPath")->ToMethod();
		AutoPtr<Worker> _worker = worker.cast<Worker>();
		JSGlobalContextRef context = KJSUtil::GetGlobalContext(_worker->GetGlobalObject());
		
		for (size_t c = 0; c < args.size(); c++)
		{
			// first convert the path to a full URL file path
			ValueList a;
			a.push_back(args.at(c));
			SharedValue result = appURLToPath->Call(a);
			const char *path = result->ToString();

			logger->Debug("attempting to import worker script = %s",path);
			KJSUtil::EvaluateFile(context, (char*)path);
		}
	}
Пример #14
0
void MenuItem::_SetSubmenu(const ValueList& args, KValueRef result)
{
    args.VerifyException("setSubmenu", "o|0");
    AutoPtr<Menu> newSubmenu = NULL;

    if (args.at(0)->IsObject())
    {
        KObjectRef o = args.at(0)->ToObject();
        o = KObject::Unwrap(o);
        newSubmenu = o.cast<Menu>();
    }

    if (!newSubmenu.isNull() && newSubmenu->ContainsItem(this))
    {
        throw ValueException::FromString("Tried to construct a recursive menu");
    }

    this->submenu = newSubmenu;
    this->SetSubmenuImpl(newSubmenu);
}
Пример #15
0
	void FileStream::Write(const ValueList& args, SharedValue result)
	{
		char *text = NULL;
		int size = 0;
		if (args.at(0)->IsObject())
		{
			SharedKObject b = args.at(0)->ToObject();
			SharedPtr<Blob> blob = b.cast<Blob>();
			if (!blob.isNull())
			{
				text = (char*)blob->Get();
				size = (int)blob->Length();
			}
		}
		else if (args.at(0)->IsString())
		{
			text = (char*)args.at(0)->ToString();
		}
		else if (args.at(0)->IsInt())
		{
			std::stringstream ostr;
			ostr << args.at(0)->ToInt();
			text = (char*)ostr.str().c_str();
			size = ostr.str().length();
		}
		else if (args.at(0)->IsDouble())
		{
			std::stringstream ostr;
			ostr << args.at(0)->ToDouble();
			text = (char*)ostr.str().c_str();
			size = ostr.str().length();
		}

		if (size==0)
		{
			size = strlen(text);
		}

		if (text == NULL)
		{
			result->SetBool(false);
			return;
		}
		if (size <= 0)
		{
			result->SetBool(false);
			return;
		}
		Write(text,size);
		result->SetBool(true);
	}
Пример #16
0
	void NetworkBinding::GetHostByAddress(const ValueList& args, SharedValue result)
	{
		if (args.at(0)->IsObject())
		{
			SharedKObject obj = args.at(0)->ToObject();
			SharedPtr<IPAddressBinding> b = obj.cast<IPAddressBinding>();
			if (!b.isNull())
			{
				// in this case, they've passed us an IPAddressBinding
				// object, which we can just retrieve the ipaddress
				// instance and resolving using it
				IPAddress addr(b->GetAddress()->toString());
				SharedPtr<HostBinding> binding = new HostBinding(addr);
				if (binding->IsInvalid())
				{
					throw ValueException::FromString("Could not resolve address");
				}
				result->SetObject(binding);
				return;
			}
			else
			{
				SharedValue bo = obj->Get("toString");
				if (bo->IsMethod())
				{
					SharedKMethod m = bo->ToMethod();
					ValueList args;
					SharedValue tostr = m->Call(args);
					this->_GetByHost(tostr->ToString(),result);
					return;
				}
				throw ValueException::FromString("Unknown object passed");
			}
		}
		else if (args.at(0)->IsString())
		{
			// in this case, they just passed in a string so resolve as
			// normal
			this->_GetByHost(args.at(0)->ToString(),result);
		}
	}
Пример #17
0
	void Pipe::Read(const ValueList& args, SharedValue result)
	{
		if (closed)
		{
			throw ValueException::FromString("Pipe is already closed");
		}
		Poco::PipeInputStream *is = dynamic_cast<Poco::PipeInputStream*>(pipe);
		if (is==NULL)
		{
			throw ValueException::FromString("Stream is not readable");
		}
		char *buf = NULL;
		try
		{
			int size = 1024;
			// allow the size of the returned buffer to be 
			// set by the caller - defaults to 1024 if not specified
			if (args.size()>0 && args.at(0)->IsInt())
			{
				size = args.at(0)->ToInt();
			}
			buf = new char[size];
			is->read(buf,size);
			int count = is->gcount();
			if (count <=0)
			{
				result->SetNull();
			}
			else
			{
				buf[count] = '\0';
				result->SetString(buf);
			}
			delete [] buf;
		}
		catch (Poco::ReadFileException &e)
		{
			if (buf) delete[] buf;
			throw ValueException::FromString(e.what());
		}
	}
Пример #18
0
Value * CodeGenerator::genIndirectCall(const tart::IndirectCallExpr* in) {
  const Expr * fn = in->function();
  const Type * fnType = dealias(fn->type().unqualified());
  bool saveIntermediateStackRoots = true;

  Value * fnValue;
  ValueList args;
  size_t savedRootCount = rootStackSize();

  if (const FunctionType * ft = dyn_cast<FunctionType>(fnType)) {
    fnValue = genArgExpr(fn, saveIntermediateStackRoots);

    if (fnValue != NULL) {
      if (ft->isStatic()) {
        //fnValue = builder_.CreateLoad(fnValue);
      } else {
        //DFAIL("Implement");
      }
    }
  } else {
    diag.info(in) << in->function() << " - " << in->function()->exprType();
    TFAIL << "Invalid function type: " << in->function() << " - " << in->function()->exprType();
  }

  const ExprList & inArgs = in->args();
  for (ExprList::const_iterator it = inArgs.begin(); it != inArgs.end(); ++it) {
    Expr * arg = *it;
    Value * argVal = genArgExpr(arg, saveIntermediateStackRoots);
    if (argVal == NULL) {
      return NULL;
    }

    args.push_back(argVal);
  }

  llvm::Value * result = genCallInstr(fnValue, args, "indirect");

  // Clear out all the temporary roots
  popRootStack(savedRootCount);
  return result;
}
	void WorkerContext::PostMessage(const ValueList &args, KValueRef result)
	{
		Logger *logger = Logger::Get("WorkerContext");
		KValueRef message(args.at(0));

		logger->Debug("PostMessage called with %s", message->DisplayString()->c_str());
		{
			Poco::ScopedLock<Poco::Mutex> lock(mutex);
			messages.push_back(message);
		}
		SendQueuedMessages();
	}
Пример #20
0
StructuredModuleEditor::ValueList StructuredModuleEditor::getUseChain(
		Value *V) {
	ValueList Vals;

	for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
			++UI) {
		Value *ValueToPush;

		Instruction *Inst = dyn_cast<Instruction>(*UI);
		if (Inst && Inst->getOpcode() == Instruction::Store) {
			StoreInst *StInst = dyn_cast<StoreInst>(Inst);
			Value *Storee = StInst->getPointerOperand();
			ValueToPush = Storee;
		} else
			ValueToPush = *UI;

		Vals.push_back(ValueToPush);
	}

	return Vals;
}
	void IRCClientBinding::Join(const ValueList& args, SharedValue result)
	{
		bool connected = this->Get("connected")->ToBool();
		if (connected)
		{
			const char *channel = args.at(0)->ToString();
#ifdef DEBUG
			PRINTD("JOIN " << channel);
#endif
			this->irc.join((char*)channel);
		}
	}
Пример #22
0
	AllocaInsn::AllocaInsn(const VariablePtr& variable, const ValuePtr& size, const ValueList& dimensions) :
		Insn(IC_Stack, IT_Alloca), size(size), variable(variable), dimensions(dimensions) {
		assert(variable && "variable must not be null");
		assert(variable->getValueType() == Value::VT_Memory && "variable must not be a temporary");
		assert(size && "size must not be null");
		assert(size->getType()->isInt() && "size must be of type int");

		if (analysis::types::isArray(variable->getType())) {
			auto type = cast<ArrayType>(variable->getType());
			assert(type->getNumOfDimensions() == dimensions.size() && "dimension information mismatch with type");
		}
	}
Пример #23
0
void UserWindow::_RemoveEventListener(const ValueList& args, SharedValue result)
{
	if (args.size() != 1 || !args.at(0)->IsNumber())
	{
		throw ValueException::FromString("invalid argument");
	}
	int id = args.at(0)->ToInt();

	std::vector<Listener>::iterator it = this->listeners.begin();
	while (it != this->listeners.end())
	{
		if ((*it).id == id)
		{
			this->listeners.erase(it);
			result->SetBool(true);
			return;
		}
		it++;
	}
	result->SetBool(false);
}
Пример #24
0
    void TCPSocket::_Write(const ValueList& args, KValueRef result)
    {
        args.VerifyException("write", "s|o");

        BytesRef data;
        if (args.at(0)->IsString())
        {
            std::string dataStr(args.GetString(0));
            data = new Bytes(dataStr);
        }
        else
        {
            data = args.GetObject(0).cast<Bytes>();
            if (data.isNull())
            {
                throw ValueException::FromString("Argument is not Bytes object");
            }
        }

        Write(data);
    }
Пример #25
0
void MenuItem::_AddItem(const ValueList& args, KValueRef result)
{
    args.VerifyException("addItem", "?s m|0 s|0");
    UI* binding = UI::GetInstance();

    // Create a menu item object and add it to this item's submenu
    AutoPtr<MenuItem> newItem = binding->__CreateMenuItem(args);
    this->EnsureHasSubmenu();
    this->submenu->AppendItem(newItem);

    result->SetObject(newItem);
}
Пример #26
0
void Apollo::ValueList::operator=(ValueList& l)
{
  List::Empty();

  for (ValueElem* e = 0; (e = l.nextElem(e)) != 0; ) {
    switch (e->getType()) {
      case ValueElem::TypeInt: add(e->getInt()); break;
      case ValueElem::TypeString: add(e->getString()); break;
      case ValueElem::TypeHandle: add(e->getHandle()); break;
    }
  }
}
Пример #27
0
	void AppBinding::CreateProperties(const ValueList& args, SharedValue result)
	{
		AutoPtr<PropertiesBinding> properties = new PropertiesBinding();
		result->SetObject(properties);
		
		if (args.size() > 0 && args.at(0)->IsObject())
		{
			SharedKObject p = args.at(0)->ToObject();
			SharedStringList names = p->GetPropertyNames();
			for (size_t i = 0; i < names->size(); i++)
			{
				SharedValue value = p->Get(names->at(i));
				ValueList setterArgs;
				setterArgs.push_back(Value::NewString(names->at(i)));
				setterArgs.push_back(value);
				PropertiesBinding::Type type;
				
				if (value->IsList()) type = PropertiesBinding::List;
				else if (value->IsInt()) type = PropertiesBinding::Int;
				else if (value->IsDouble()) type = PropertiesBinding::Double;
				else if (value->IsBool()) type = PropertiesBinding::Bool;
				else type = PropertiesBinding::String;
				
				properties->Setter(setterArgs, type);
			}
		}
	}
Пример #28
0
    void APIBinding::_InstallDependencies(const ValueList& args, KValueRef result)
    {
        args.VerifyException("installDependencies", "l,m");
        KListRef dependenciesList = args.GetList(0);
        KMethodRef callback = args.GetMethod(1, 0);
        vector<SharedDependency> dependencies;

        for (unsigned int i = 0; i < dependenciesList->Size(); i++)
        {
            if (!dependenciesList->At(i)->IsObject())
            {
                continue;
            }

            AutoPtr<DependencyBinding> d =
                dependenciesList->At(i)->ToObject().cast<DependencyBinding>();
            if (!d.isNull())
            {
                dependencies.push_back(d->GetDependency());
            }
        }

        if (dependencies.size() > 0)
        {
            if (!this->installerMutex.tryLock())
            {
                throw ValueException::FromString(
                    "Tried to launch more than one instance of the installer");
            }

            if (this->installerThread)
            {
                delete this->installerThread;
            }
            this->installerDependencies = dependencies;
            this->installerCallback = callback;
            this->installerThread = new Poco::Thread();
            this->installerThread->start(*this->installerThreadAdapter);
        }
    }
Пример #29
0
void UserWindow::_CreateWindow(const ValueList& args, SharedValue result)
{
	//TODO: wrap in sharedptr
	WindowConfig *config = NULL;

	if (args.size() > 0 && args.at(0)->IsObject())
	{
		SharedKObject props = SharedKObject(new StaticBoundObject());
		config = new WindowConfig();
		props = args.at(0)->ToObject();
		config->UseProperties(props);
	}
	else if (args.size() > 0 && args.at(0)->IsString())
	{
		// String might match a url spec
		std::string url = args.at(0)->ToString();
		WindowConfig* matchedConfig = AppConfig::Instance()->GetWindowByURL(url);

		url = AppConfig::Instance()->InsertAppIDIntoURL(url);
		config = new WindowConfig(matchedConfig, url);
	}
	else
	{
		config = new WindowConfig();
	}

	SharedUserWindow new_window = this->binding->CreateWindow(config, shared_this);
	result->SetObject(new_window);
}
Пример #30
0
	void HTTPClientBinding::SendDir(const ValueList& args, SharedValue result)
	{
		if (this->Get("connected")->ToBool())
		{
			throw ValueException::FromString("already connected");
		}
		if (args.size()==1)
		{
			// can be a string of data or a file
			SharedValue v = args.at(0);
			if (v->IsObject())
			{
				// probably a file
				SharedKObject obj = v->ToObject();
				if (obj->Get("isFile")->IsMethod())
				{
					this->dirstream = obj->Get("toString")->ToMethod()->Call()->ToString();
				}
				else
				{
					this->dirstream = obj->Get("toString")->ToMethod()->Call()->ToString();
				}
			}
			else if (v->IsString())
			{
				this->dirstream = v->ToString();
			}
			else
			{
				throw ValueException::FromString("unknown data type");
			}
		}
		this->thread = new Poco::Thread();
		this->thread->start(&HTTPClientBinding::Run,(void*)this);
		if (!this->async)
		{
			PRINTD("Waiting on HTTP Client thread to finish");
			this->thread->join();
		}
	}