Beispiel #1
0
bool Object_writer::PutValue(Environment &env, const Value &value)
{
	Signal &sig = env.GetSignal();
	String str;
	if (value.IsInvalid()) {
		return true;
	} else if (value.Is_number()) {
		str = Formatter::FormatValueList(sig, _format.c_str(), ValueList(value));
	} else if (value.Is_complex()) {
		str = Formatter::FormatValueList(sig, _format.c_str(), ValueList(value));
	} else if (value.Is_string()) {
		str += '"';
		for (const char *p = value.GetString(); *p != '\0'; p++) {
			char ch = *p;
			str += ch;
			if (ch == '"') str += ch;
		}
		str += '"';
	} else {
		sig.SetError(ERR_TypeError, "can't output in CSV format");
		return false;
	}
	_pStreamDst->Print(sig, str.c_str());
	return true;
}
	void UIBinding::Log(Logger::Level level, std::string& message)
	{
		if (level > Logger::LWARN)
			return;

		std::string methodName("warn");
		if (level < Logger::LWARN)
			methodName = "error";

		std::string origMethodName(methodName);
		origMethodName.append("_orig");

		std::vector<AutoUserWindow>& openWindows = UIBinding::GetInstance()->GetOpenWindows();
		for (size_t i = 0; i < openWindows.size(); i++)
		{
			KObjectRef domWindow = openWindows[i]->GetDOMWindow();
			if (domWindow.isNull())
				continue;

			KObjectRef console = domWindow->GetObject("console", 0);
			if (console.isNull())
				continue;

			KMethodRef method = console->GetMethod(origMethodName.c_str(), 0);
			if (method.isNull())
				method = console->GetMethod(methodName.c_str(), 0);

			RunOnMainThread(method, ValueList(Value::NewString(message)), false);
		}
	}
	void TCPSocketBinding::ConnectThread()
	{
		static std::string error("Connection failed: ");
		try
		{
			// Give the connetion process and the reactor the same timeout.
			this->socket.connect(Poco::Net::SocketAddress(
				this->host, this->port), this->timeout);

			// Enable Keepalive mode on this socket. See:
			// http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/index.html
			this->socket.setKeepAlive(true);

			this->reactor.setTimeout(this->timeout);
			this->thread.start(this->reactor);
			this->opened = true;
			return;
		}
		catch (Poco::IOException &e)
		{
			error.append(e.displayText());
		}
		catch (std::exception &e)
		{
			error.append(e.what());
		}
		catch (...)
		{
			error.append("Unknown exception");
		}

		if (!this->onError.isNull())
			RunOnMainThread(this->onError, ValueList(Value::NewString(error)), false);
	}
bool NetworkStatus::GetStatus()
{
    if (!bus)
        return true;

    return RunOnMainThread(statusCheckWork, ValueList())->ToBool();
}
StringCondition::StringCondition(
  RCP<const ParameterEntry> parameter,
  std::string value):
  ParameterCondition(parameter), 
  values_(ValueList(1,value))
{
  checkParameterType();
}
	void TCPSocketBinding::OnTimeout(
		const Poco::AutoPtr<Poco::Net::TimeoutNotification>& n)
	{
		if (this->onTimeout.isNull())
		{
			return;
		}
		RunOnMainThread(this->onTimeout, ValueList(), false);
	}
Beispiel #7
0
	void Process::ExitMonitorSync()
	{
		this->exitCode = Value::NewInt(this->Wait());

		this->GetNativeStdin()->StopMonitors();
		this->GetNativeStdout()->StopMonitors();
		this->GetNativeStderr()->StopMonitors();
		if (!exitCallback.isNull())
			RunOnMainThread(exitCallback, ValueList());
	}
StringCondition::StringCondition(std::string parameterName, Teuchos::RCP<Teuchos::ParameterList> parentList, std::string value, bool whenParamEqualsValue):
	ParameterCondition(parameterName, parentList, whenParamEqualsValue), values(ValueList(1,value))
{
	if(!parameter->isType<std::string>()){
		throw InvalidConditionException("The parameter of a String Condition "
		"must be of type string. \n"
		"Expected type: std::string\n"
		"Actual type: " + parameter->getAny().typeName() + "\n");
	}
}
Beispiel #9
0
void MenuItem::HandleClickEvent(KObjectRef source)
{
    if (this->FireEvent(Event::CLICKED)
        && this->IsCheck() && this->autoCheck)
    {
        // Execute this later on the main thread
        RunOnMainThread(this->Get("setState")->ToMethod(),
            ValueList(Value::NewBool(!this->GetState())), false);
    }
}
Beispiel #10
0
void Iterator::PrintfEach(Environment &env, Stream *pStream, const char *format)
{
	Signal &sig = env.GetSignal();
	Value value;
	while (Next(env, value)) {
		if (value.Is_list()) {
			pStream->PrintFmt(sig, format, value.GetList());
		} else {
			pStream->PrintFmt(sig, format, ValueList(value));
		}
		if (sig.IsSignalled()) break;
	}
}
Beispiel #11
0
	SharedValue AccessorBoundList::Get(const char *name)
	{
		std::string getter_name = "get" + Capitalize(name);
		SharedValue v = this->RawGet(getter_name.c_str());
		if (v->IsMethod())
		{
			SharedKMethod m = v->ToMethod();
			return m->Call(ValueList());
		}
		else
		{
			return this->RawGet(name);
		}
	}
void WorkerContext::DeliverMessage(KValueRef message)
{
    AutoPtr<Event> event(this->CreateEvent("worker.message"));
    event->Set("message", message);

    KValueRef callback = this->Get("onmessage");
    if (callback->IsMethod())
    {
        Host::GetInstance()->RunOnMainThread(
            callback->ToMethod(),
            ValueList(Value::NewObject(event)),
            false);
    }
}
Beispiel #13
0
    void APIBinding::RunInstaller()
    {
        START_KROLL_THREAD;

        SharedApplication app = host->GetApplication();
        BootUtils::RunInstaller(
            this->installerDependencies, app, "", app->GetSDKPath(), true);

        if (!this->installerCallback.isNull())
        {
            RunOnMainThread(this->installerCallback, ValueList(), false);
        }
        this->installerMutex.unlock();

        END_KROLL_THREAD;
    }
float
BChannelSlider::ThumbDeltaFor(int32 channel)
{
	float delta = 0.0;
	if (channel >= 0 && channel < MaxChannelCount()) {
		float range = ThumbRangeFor(channel);
		int32 limitRange = MaxLimitList()[channel] - MinLimitList()[channel];
		delta = (ValueList()[channel] - MinLimitList()[channel]) * range
			/ limitRange;

		if (fIsVertical)
			delta = range - delta;
	}

	return delta;
}
Beispiel #15
0
	static void FireEventCallback(KMethodRef callback, AutoPtr<Event> event,
		bool synchronous, KObjectRef thisObject)
	{
		try
		{
			RunOnMainThread(callback, thisObject,
				ValueList(Value::NewObject(event)), synchronous);
		}
		catch (ValueException& e)
		{
			Logger* logger = Logger::Get("KEventObject");
			SharedString ss = e.DisplayString();
			logger->Error("Exception caught during event callback (target=[%s]): %s",
				event->target->GetType().c_str(), ss->c_str());
		}
	}
	void HTTPClientBinding::ReceiveResponseBody(std::istream& in, int responseLength)
	{
		int dataReceived = 0;
		int readSize = 0;

		while (dataReceived < responseLength)
		{
			if (this->abort.tryWait(0))
			{
				this->FireEvent(Event::HTTP_ABORT);
				return;
			}

			in.read(buffer.begin(), buffer.size());
			readSize = in.gcount();
			if (readSize <= 0)
				break;

			if (this->outstream)
			{
				this->outstream->write(buffer.begin(), readSize);
			}
			else
			{
				// Pass data to handler on main thread
				std::string data(buffer.begin(), readSize);
				this->host->InvokeMethodOnMainThread(
					this->outputHandler,
					ValueList(Value::NewString(data))
				);
			}

			dataReceived += readSize;
			this->SetInt("dataReceived", dataReceived);
			this->FireEvent(Event::HTTP_DATA_RECEIVED);
		}

		// Set response text if no handler is set
		if (this->outstream)
		{
			std::string data = this->outstream->str();
			if (!data.empty())
			{
				this->SetString("responseText", data);
			}
		}
	}
Beispiel #17
0
	void Process::ExitMonitorAsync()
	{
		this->exitCode = Value::NewInt(this->Wait());

		// We want the onRead callbacks to fire before the exit
		// event, so we do a little hack here and stop the event
		// threads on the native pipes. It shouldn't matter anyhow
		// because these pipes are now dead and will be replaced on
		// next launch. Don't do this for synchronous process
		// launch becauase we are already on the main thread and that
		// will cause a deadlock.
		this->GetNativeStdin()->StopMonitors();
		this->GetNativeStdout()->StopMonitors();
		this->GetNativeStderr()->StopMonitors();

		if (!exitCallback.isNull())
			RunOnMainThread(exitCallback, ValueList());
	}
Beispiel #18
0
	/*static*/
	bool SnarlWin32::MessageHandler(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
	{
		if (message != SnarlWin32::snarlWindowMessage)
			return false;

		long id = (long) lParam;
		std::map<long, KMethodRef>::iterator i = snarlCallbacks.find(id);

		if (i != snarlCallbacks.end())
		{
			if (wParam == SnarlInterface::SNARL_NOTIFICATION_CLICKED)
			{
				Host::GetInstance()->InvokeMethodOnMainThread(
					i->second, ValueList(), false);
			}
			else if (wParam == SnarlInterface::SNARL_NOTIFICATION_TIMED_OUT)
			{
				snarlCallbacks.erase(i);
			}
		}

		return true;
	}
Beispiel #19
0
void NetworkBinding::NetworkStatusChange(bool online)
{
    PRINTD("ti.Network: Online status changed ==> " << online);
    this->Set("online", Value::NewBool(online));

    ValueList args = ValueList();
    args.push_back(Value::NewBool(online));
    std::vector<Listener>::iterator it = this->listeners.begin();
    while (it != this->listeners.end())
    {
        SharedBoundMethod callback = (*it++).callback;
        try
        {
            host->InvokeMethodOnMainThread(callback, args, false);
        }
        catch(ValueException& e)
        {
            SharedString ss = e.GetValue()->DisplayString();
            std::cerr << "ti.Network.NetworkStatusChange callback failed: "
                      << *ss << std::endl;
        }
    }
}
Beispiel #20
0
void Network::NetworkStatusChange(bool online)
{
    static Logger* log = Logger::Get("NetworkStatus");
    log->Debug("ti.Network: Online status changed ==> %i", online);
    this->Set("online", Value::NewBool(online));

    ValueList args = ValueList();
    args.push_back(Value::NewBool(online));
    std::vector<Listener>::iterator it = this->listeners.begin();
    while (it != this->listeners.end())
    {
        KMethodRef callback = (*it++).callback;
        try
        {
            RunOnMainThread(callback, args, false);
        }
        catch(ValueException& e)
        {
            SharedString ss = e.GetValue()->DisplayString();
            log->Error("Network.NetworkStatus callback failed: %s", ss->c_str());
        }
    }
}
Beispiel #21
0
void KEventObject::FireEvent(const char* event)
{
    FireEvent(event, ValueList());
}
Beispiel #22
0
void KEventObject::FireErrorEvent(std::exception& e)
{
    FireEvent("error", ValueList(Value::NewString(e.what())));
}
Beispiel #23
0
    void TCPSocket::ReadThread()
    {
        try
        {
            this->socket.connect(this->address);

            {
                Poco::FastMutex::ScopedLock lock(this->mutex);
                this->state = DUPLEX;
            }

            FireEvent("connect");
        }
        catch (Poco::Exception& e)
        {
            HandleError(e);
            return;
        }

        BytesRef buffer = new Bytes(READ_BUFFER_SIZE);
        size_t usedSpace = 0;

        while (true)
        {
            // Re-allocate a new read buffer if the current
            // one has become too small.
            int freeSpace = READ_BUFFER_SIZE - usedSpace;
            if (freeSpace < READ_BUFFER_MIN_SIZE)
            {
                buffer = new Bytes(READ_BUFFER_SIZE);
                usedSpace = 0;
                freeSpace = READ_BUFFER_SIZE;
            }

            // Attempt to read data from socket into buffer.
            try
            {
                char* bufferPtr = buffer->Pointer() + usedSpace;
                int bytesRecv = this->socket.receiveBytes(bufferPtr, freeSpace);
                if (bytesRecv > 0)
                {
                    BytesRef data = new Bytes(buffer, usedSpace, bytesRecv);
                    usedSpace += bytesRecv;
                    this->FireEvent("data", ValueList(Value::NewObject(data)));
                }
                else
                {
                    // Remote host sent FIN, we are now write only.
                    {
                        Poco::FastMutex::ScopedLock lock(this->mutex);
                        this->state = WRITEONLY;
                    }

                    FireEvent("end");
                    return;
                }
            }
            catch (Poco::TimeoutException& e)
            {
                this->FireEvent("timeout");
            }
            catch (Poco::Exception& e)
            {
                HandleError(e);
                return;
            }
        }
    }
Beispiel #24
0
 KValueRef KMethod::Call()
 {
     return this->Call(ValueList());
 }