KListRef Win32UserWindow::SelectDirectory(
	bool multiple,
	std::string& title,
	std::string& path,
	std::string& defaultName)
{
	KListRef results = new StaticBoundList();

	BROWSEINFO bi = { 0 };
	std::wstring titleW = UTF8ToWide(title);
	bi.lpszTitle = titleW.c_str();
	bi.hwndOwner = this->windowHandle;
	bi.ulFlags = BIF_RETURNONLYFSDIRS;
	LPITEMIDLIST pidl = SHBrowseForFolder(&bi);

	if (pidl != 0)
	{
		wchar_t in_path[MAX_PATH];
		if (SHGetPathFromIDList(pidl, in_path))
		{
			std::wstring inPathW = in_path;
			std::string inPath = WideToUTF8(inPathW);
			results->Append(Value::NewString(inPath));
		}

		IMalloc * imalloc = 0;
		if (SUCCEEDED(SHGetMalloc(&imalloc)))
		{
			imalloc->Free(pidl);
			imalloc->Release();
		}
	}
	return results;
}
	void FilesystemBinding::ResolveFileName(const ValueList& args, std::string& filename)
	{
		if (args.at(0)->IsList())
		{
			// you can pass in an array of parts to join
			KListRef list = args.at(0)->ToList();
			for (size_t c = 0; c < list->Size(); c++)
			{
				std::string arg = list->At(c)->ToString();
				filename = kroll::FileUtils::Join(filename.c_str(), arg.c_str(), NULL);
			}
		}
		else
		{
			// you can pass in vararg of strings which acts like  a join
			for (size_t c = 0; c < args.size(); c++)
			{
				std::string arg = FileSystemUtils::GetFileName(args.at(c))->c_str();
				filename = kroll::FileUtils::Join(filename.c_str(), arg.c_str(), NULL);
			}
		}
		if (filename.empty())
		{
			throw ValueException::FromString("invalid file type");
		}
	}
	void PropertiesBinding::SetList(const ValueList& args, KValueRef result)
	{
		if (args.size() >= 2 && args.at(0)->IsString() && args.at(1)->IsList())
		{
			std::string property = args.at(0)->ToString();
			KListRef list = args.at(1)->ToList();

			std::string value = "";
			for (unsigned int i = 0; i < list->Size(); i++)
			{
				KValueRef arg = list->At(i);
				if (arg->IsString())
				{
					value += list->At(i)->ToString();
					if (i < list->Size() - 1)
					{
						value += ",";
					}
				}
				else
				{
					std::cerr << "skipping object: " << arg->GetType() << std::endl;
				}
			}
			config->setString(property, value);
			if (file_path.size() > 0)
			{
				config->save(file_path);
			}
		}
	}
Esempio n. 4
0
void Properties::SetList(const ValueList& args, KValueRef result)
{
    args.VerifyException("setList", "s l");

    std::string property = args.at(0)->ToString();
    KListRef list = args.at(1)->ToList();

    std::string value = "";
    for (unsigned int i = 0; i < list->Size(); i++)
    {
        KValueRef arg = list->At(i);
        if (arg->IsString())
        {
            value += list->At(i)->ToString();
            if (i < list->Size() - 1)
            {
                value += ",";
            }
        }
        else
        {
            logger->Warn("Skipping list entry %ui, not a string", i);
        }
    }
    config->setString(property, value);
    this->SaveConfig();
    
}
Esempio n. 5
0
void Calc::Minimum(const ValueList& args, KValueRef result)
{
	if (args.at(0)->IsList())
	{
		KListRef list = args.at(0)->ToList();

		double *arr = NULL;

		arr = new double[list->Size()];

		for (unsigned int c = 0; c < list->Size(); c++)
		{
			KValueRef d = list->At(c);
			arr[c] = d->ToDouble();
		}

		double low = Min(arr, list->Size());

		result->SetDouble(low);

		delete [] arr;

   } else {
		throw ValueException::FromString("Minimum takes an array");
   }

}
Esempio n. 6
0
	void UIBinding::_GetOpenWindows(const ValueList& args, KValueRef result)
	{
		KListRef list = new StaticBoundList();
		std::vector<AutoUserWindow>::iterator w = openWindows.begin();
		while (w != openWindows.end()) {
			list->Append(Value::NewObject(*w++));
		}
		result->SetList(list);
	}
Esempio n. 7
0
 KListRef APIBinding::DependencyVectorToKList(std::vector<SharedDependency>& deps)
 {
     KListRef dependencyList = new StaticBoundList();
     std::vector<SharedDependency>::iterator i = deps.begin();
     while (i != deps.end())
     {
         KValueRef dValue = Value::NewObject(new DependencyBinding(*i++));
         dependencyList->Append(dValue);
     }
     return dependencyList;
 }
Esempio n. 8
0
/*
    Inspired by python's os.list2cmdline, ported to C++ by Marshall Culpepper
    
    Translate a sequence of arguments into a command line
    string, using the same rules as the MS C runtime:

    1) Arguments are delimited by white space, which is either a
       space or a tab.

    2) A string surrounded by double quotation marks is
       interpreted as a single argument, regardless of white space
       contained within.  A quoted string can be embedded in an
       argument.

    3) A double quotation mark preceded by a backslash is
       interpreted as a literal double quotation mark.

    4) Backslashes are interpreted literally, unless they
       immediately precede a double quotation mark.

    5) If backslashes immediately precede a double quotation mark,
       every pair of backslashes is interpreted as a literal
       backslash.  If the number of backslashes is odd, the last
       backslash escapes the next double quotation mark as
       described in rule 3.
    See
    http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
*/
std::string ProcessWin::ArgListToString(KListRef argList)
{
    
    std::string result = "";
    bool needQuote = false;
    for (int i = 0; i < argList->Size(); i++)
    {
        std::string arg = argList->At(i)->ToString();
        std::string backspaceBuf = "";
        
        // Add a space to separate this argument from the others
        if (result.size() > 0) {
            result += ' ';
        }

        needQuote = (arg.find_first_of(" \t") != std::string::npos) || arg == "";
        if (needQuote) {
            result += '"';
        }

        for (int j = 0; j < arg.size(); j++)
        {
            char c = arg[j];
            if (c == '\\') {
                // Don't know if we need to double yet.
                backspaceBuf += c;
            }
            else if (c == '"') {
                // Double backspaces.
                result.append(backspaceBuf.size()*2, '\\');
                backspaceBuf = "";
                result.append("\\\"");
            }
            else {
                // Normal char
                if (backspaceBuf.size() > 0) {
                    result.append(backspaceBuf);
                    backspaceBuf = "";
                }
                result += c;
            }
        }
        // Add remaining backspaces, if any.
        if (backspaceBuf.size() > 0) {
            result.append(backspaceBuf);
        }

        if (needQuote) {
            result.append(backspaceBuf);
            result += '"';
        }
    }
    return result;
}
Esempio n. 9
0
void HostBinding::GetAliases(const ValueList& args, KValueRef result)
{
    KListRef list = new StaticBoundList();
    std::vector<std::string> aliases = this->host.aliases();
    std::vector<std::string>::iterator iter = aliases.begin();
    while (iter!=aliases.end())
    {
        std::string alias = (*iter++);
        list->Append(Value::NewString(alias));
    }
    result->SetList(list);
}
Esempio n. 10
0
	void AppBinding::GetArguments(const ValueList& args, KValueRef result)
	{
		static KListRef argList(0);
		if (argList.isNull())
		{
			// Skip the first argument which is the filename to the executable
			argList = new StaticBoundList();
			for (int i = 1; i < host->GetCommandLineArgCount(); i++)
				argList->Append(Value::NewString(host->GetCommandLineArg(i)));
		}

		result->SetList(argList);
	}
Esempio n. 11
0
 KListRef APIBinding::ManifestToKList(vector<pair<string, string> >& manifest)
 {
     KListRef list = new StaticBoundList();
     vector<pair<string, string> >::iterator i = manifest.begin();
     while (i != manifest.end())
     {
         KListRef entry = new StaticBoundList();
         entry->Append(Value::NewString(i->first));
         entry->Append(Value::NewString(i->second));
         list->Append(Value::NewList(entry));
         *i++;
     }
     return list;
 }
Esempio n. 12
0
	void AppBinding::GetArguments(const ValueList& args, KValueRef result)
	{
		static KListRef argList(0);
		if (argList.isNull())
		{
			// Skip the first argument which is the filename of the executable.
			std::vector<std::string>& args = host->GetApplication()->GetArguments();
			argList = new StaticBoundList();
			for (size_t i = 1; i < args.size(); i++)
				argList->Append(Value::NewString(args.at(i)));
		}

		result->SetList(argList);
	}
Esempio n. 13
0
void HostBinding::GetAddresses(const ValueList& args, KValueRef result)
{
    KListRef list = new StaticBoundList();
    std::vector<IPAddress> addresses = this->host.addresses();
    std::vector<IPAddress>::iterator iter = addresses.begin();
    while (iter!=addresses.end())
    {
        IPAddress address = (*iter++);
        KObjectRef obj = new IPAddressBinding(address);
        KValueRef addr = Value::NewObject(obj);
        list->Append(addr);
    }
    result->SetList(list);
}
Esempio n. 14
0
static void GetInterfaceList()
{
    if (!interfaceList.isNull())
        return;

    interfaceList = new StaticBoundList();
    std::vector<NetworkInterface> list = NetworkInterface::list();
    for (size_t i = 0; i < list.size(); i++)
    {
        NetworkInterface& interface = list[i];
        interfaceList->Append(Value::NewObject(new Interface(interface)));

        if (!interface.address().isLoopback() &&
            interface.address().isIPv4Compatible())
            firstIPv4Address = interface.address().toString();
    }
}
Esempio n. 15
0
	void Bytes::_Split(const ValueList& args, KValueRef result)
	{
		// This method now follows the spec located at:
		// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/split
		// Except support for regular expressions
		args.VerifyException("Bytes.split", "?s,i");

		KListRef list = new StaticBoundList();
		result->SetList(list);

		std::string target = "";
		if (this->size > 0)
		{
			target = this->buffer;
		}
		else
		{
			list->Append(Value::NewString(target));
			return;
		}

		if (args.size() <= 0)
		{
			list->Append(Value::NewString(target));
			return;
		}

		std::string separator = args.GetString(0);

		int limit = args.GetInt(1, INT_MAX);

		// We could use Poco's tokenizer here, but it doesn't split strings
		// like "abc,def,," -> ['abc', 'def', '', ''] correctly. It produces
		// ['abc', 'def', ''] which is a different behavior than the JS split.
		// So we roll our own for now -- it's not very efficient right now, but
		// it should be correct.
		size_t next = target.find(separator);
		while (target.size() > 0 && next != std::string::npos)
		{
			std::string token;
			if (separator.size() == 0)
			{
				token = target.substr(0, 1);
			}
			else
			{
				token = target.substr(0, next);
			}
			target = target.substr(next + 1);
			next = target.find(separator);

			if ((int) list->Size() >= limit)
				return;

			list->Append(Value::NewString(token));
		}

		if ((int) list->Size() < limit && separator.size() != 0)
			list->Append(Value::NewString(target));
	}
Esempio n. 16
0
    KListRef APIBinding::ComponentVectorToKList(
        vector<SharedComponent>& components,
        KComponentType filter)
    {
        KListRef componentList = new StaticBoundList();
        vector<SharedComponent>::iterator i = components.begin();
        while (i != components.end())
        {
            SharedComponent c = *i++;
            if (filter == UNKNOWN || filter == c->type)
            {
                KValueRef cValue = Value::NewObject(new ComponentBinding(c));
                componentList->Append(cValue);
            }
        }

        return componentList;
    }
	void FilesystemBinding::ExecuteAsyncCopy(const ValueList& args, KValueRef result)
	{
		if (args.size()!=3)
		{
			throw ValueException::FromString("invalid arguments - this method takes 3 arguments");
		}
		std::vector<std::string> files;
		if (args.at(0)->IsString())
		{
			files.push_back(args.at(0)->ToString());
		}
		else if (args.at(0)->IsList())
		{
			KListRef list = args.at(0)->ToList();
			for (unsigned int c = 0; c < list->Size(); c++)
			{
				KValueRef v = list->At(c);
				files.push_back(FileSystemUtils::GetFileName(v)->c_str());
			}
		}
		else
		{
			files.push_back(FileSystemUtils::GetFileName(args.at(0))->c_str());
		}
		KValueRef v = args.at(1);
		std::string destination(FileSystemUtils::GetFileName(v)->c_str());
		KMethodRef method = args.at(2)->ToMethod();
		KObjectRef copier = new ti::AsyncCopy(this,host,files,destination,method);
		result->SetObject(copier);
		asyncOperations.push_back(copier);
		// we need to create a timer thread that can cleanup operations
		if (timer==NULL)
		{
			this->SetMethod("_invoke",&FilesystemBinding::DeletePendingOperations);
			timer = new Poco::Timer(100,100);
			Poco::TimerCallback<FilesystemBinding> cb(*this, &FilesystemBinding::OnAsyncOperationTimer);
			timer->start(cb);
		}
		else
		{
			this->timer->restart(100);
		}
	}
Esempio n. 18
0
void KObject::GetStringList(const char *name, std::vector<std::string> &list)
{
    KValueRef prop = this->Get(name);
    if(!prop->IsUndefined() && prop->IsList())
    {
        KListRef values = prop->ToList();
        if (values->Size() > 0)
        {
            for (unsigned int c = 0; c < values->Size(); c++)
            {
                KValueRef v = values->At(c);
                if (v->IsString())
                {
                    const char *s = v->ToString();
                    list.push_back(s);
                }
            }
        }
    }
}
	void PropertiesBinding::GetList(const ValueList& args, KValueRef result)
	{
		KValueRef stringValue = Value::Null;
		GetString(args, stringValue);

		if (!stringValue->IsNull())
		{
			KListRef list = new StaticBoundList();
			std::string string = stringValue->ToString();
			Poco::StringTokenizer t(string, ",", Poco::StringTokenizer::TOK_TRIM);
			for (size_t i = 0; i < t.count(); i++)
			{
				KValueRef token = Value::NewString(t[i].c_str());
				list->Append(token);
			}

			KListRef list2 = list;
			result->SetList(list2);
		}
	}
Esempio n. 20
0
	void PosixProcess::SetArguments(KListRef args)
	{
#if defined(OS_OSX)
		std::string cmd = args->At(0)->ToString();
		size_t found = cmd.rfind(".app");
		if (found != std::string::npos)
		{
			Poco::Path p(cmd);
			std::string fn = p.getFileName();
			found = fn.find(".app");
			fn = fn.substr(0,found);
			fn = kroll::FileUtils::Join(cmd.c_str(),"Contents","MacOS",fn.c_str(),NULL);
			if (FileUtils::IsFile(fn))
			{
				cmd = fn;
			}
		}
		args->At(0)->SetString(cmd.c_str());
#endif
		Process::SetArguments(args);
	}
Esempio n. 21
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);
        }
    }
Esempio n. 22
0
 static void GetBytes(KValueRef value, std::vector<BytesRef>& blobs)
 {
     if (value->IsObject())
     {
         blobs.push_back(value->ToObject().cast<Bytes>());
     }
     else if (value->IsString())
     {
         blobs.push_back(new Bytes(value->ToString()));
     }
     else if (value->IsList())
     {
         KListRef list = value->ToList();
         for (size_t j = 0; j < list->Size(); j++)
         {
             GetBytes(list->At((int)j), blobs);
         }
     }
     else if (value->IsNumber())
     {
         blobs.push_back(new Bytes(value->ToInt()));
     }
 }
	void FilesystemBinding::GetRootDirectories(const ValueList& args, KValueRef result)
	{
		try
		{
			Poco::Path path;
			std::vector<std::string> roots;
			path.listRoots(roots);

			KListRef rootList = new StaticBoundList();
			for(size_t i = 0; i < roots.size(); i++)
			{
				ti::File* file = new ti::File(roots.at(i));
				KValueRef value = Value::NewObject((KObjectRef) file);
				rootList->Append(value);
			}

			KListRef list = rootList;
			result->SetList(list);
		}
		catch (Poco::Exception& exc)
		{
			throw ValueException::FromString(exc.displayText());
		}
	}
KListRef Win32UserWindow::SelectFile(bool saveDialog, bool multiple, std::string& title,
	std::string& path, std::string& defaultName, std::vector<std::string>& types,
	std::string& typesDescription)
{
	std::wstring filter;
	std::wstring typesDescriptionW = ::UTF8ToWide(typesDescription);
	if (types.size() > 0)
	{
		//"All\0*.*\0Test\0*.TXT\0";
		if (typesDescription.size() == 0)
		{
			// Reasonable default?
			typesDescriptionW = L"Selected Files";
		}
		filter.append(typesDescriptionW);
		filter.push_back(L'\0');
		
		for (int i = 0; i < types.size(); i++)
		{
			std::string type = types.at(i);
			std::wstring typeW = ::UTF8ToWide(type);
			//multiple filters: "*.TXT;*.DOC;*.BAK"
			size_t found = type.find("*.");
			if (found != 0)
			{
				filter.append(L"*.");
			}
			filter.append(typeW);
			filter.append(L";");
		}
		filter.push_back(L'\0');
	}

	OPENFILENAME ofn;

	std::wstring pathW = ::UTF8ToWide(path);
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = this->windowHandle;

	// Windows may not null-terminate the string it puts here, so we zero it.
	wchar_t filenameW[MAX_FILE_DIALOG_STRING];
	ZeroMemory(&filenameW, MAX_FILE_DIALOG_STRING * sizeof(wchar_t));
	wcscpy(filenameW, ::UTF8ToWide(defaultName).c_str());
	ofn.lpstrFile = filenameW;

	ofn.nMaxFile = MAX_FILE_DIALOG_STRING;
	ofn.lpstrFilter = (LPWSTR) (filter.size() == 0 ? 0 : filter.c_str());
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = 0;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = (LPWSTR) (pathW.length() == 0 ? 0 : pathW.c_str());
	ofn.Flags = OFN_EXPLORER;

	std::wstring titleW;
	if (!title.empty())
	{
		titleW = ::UTF8ToWide(title);
		ofn.lpstrTitle = titleW.c_str();
	}

	if (!saveDialog)
	{
		ofn.Flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
	}

	if (multiple)
	{
		ofn.Flags |= OFN_ALLOWMULTISELECT;
	}

	
	BOOL result;
	if (saveDialog)
	{
		result = ::GetSaveFileName(&ofn);
	}
	else
	{
		result = ::GetOpenFileName(&ofn);
	}

	// A zero-return value here indicates either an error or that the user
	// cancelled the action (CommDlgExtendedError returns 0). We should
	// return a helpful exception if it's an error.
	if (!result)
	{
		DWORD code = CommDlgExtendedError();
		if (code == 0)
			return new StaticBoundList();

		throw ValueException::FromFormat(
			"File dialog action failed with error code: %i", code);
	}

	// From:  http://msdn.microsoft.com/en-us/library/ms646839(VS.85).aspx
	// If multiple files have been selected there will be two '\0' characters
	// at the end of this array of characters, so if we enabled multiple file
	// selected, just check for that second '\0'.
	KListRef results = new StaticBoundList();
	if (multiple && ofn.lpstrFile[ofn.nFileOffset - 1] == L'\0')
	{
		std::vector<std::wstring> files;
		ParseMultipleSelectedFiles(&ofn, files);
		for (size_t i = 0; i < files.size(); i++)
		{
			results->Append(Value::NewString(
				::WideToUTF8(files[i])));
		}
	}
	else
	{
		results->Append(Value::NewString(::WideToUTF8(
			ofn.lpstrFile)));
	}

	return results;
}
Esempio n. 25
0
KListRef Win32UserWindow::SelectFile(
 	bool saveDialog,
	bool multiple,
	std::string& title,
	std::string& path,
	std::string& defaultName,
	std::vector<std::string>& types,
	std::string& typesDescription)
{
	std::wstring filter;
	std::wstring typesDescriptionW = UTF8ToWide(typesDescription);
	if (types.size() > 0)
	{
		//"All\0*.*\0Test\0*.TXT\0";
		filter.append(typesDescriptionW);
		filter.push_back(L'\0');
		for (int i = 0; i < types.size(); i++)
		{
			std::string type = types.at(i);
			std::wstring typeW = UTF8ToWide(type);
			//multiple filters: "*.TXT;*.DOC;*.BAK"
			size_t found = type.find("*.");
			if (found != 0)
			{
				filter.append(L"*.");
			}
			filter.append(typeW);
			filter.append(L";");
		}
		filter.push_back(L'\0');
	}

	OPENFILENAME ofn;
	wchar_t filenameW[1024];
	wcscpy(filenameW, UTF8ToWide(defaultName).c_str());
	
	// init OPENFILE
	std::wstring pathW = UTF8ToWide(path);
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = this->windowHandle;
	ofn.lpstrFile = filenameW;
	if (wcslen(filenameW) == 0)
	{
		ofn.lpstrFile[0] = L'\0';
	}
	ofn.nMaxFile = 1024;
	ofn.lpstrFilter = (LPWSTR) (filter.size() == 0 ? NULL : filter.c_str());
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = (LPWSTR) (pathW.length() == 0 ? NULL : pathW.c_str());
	ofn.Flags = OFN_EXPLORER;

	if (!title.empty())
	{
		std::wstring titleW = UTF8ToWide(title);
		ofn.lpstrTitle = titleW.c_str();
	}

	if (!saveDialog)
	{
		ofn.Flags |= OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
	}

	if (multiple)
	{
		ofn.Flags |= OFN_ALLOWMULTISELECT;
	}

	KListRef results = new StaticBoundList();
	// display the open dialog box
	BOOL result;

	if (saveDialog)
	{
		result = ::GetSaveFileName(&ofn);
	}
	else
	{
		result = ::GetOpenFileName(&ofn);
	}

	if (result)
	{
		// if the user selected multiple files, ofn.lpstrFile is a NULL-separated list of filenames
		// if the user only selected one file, ofn.lpstrFile is a normal string

		std::vector<std::string> tokens;
		ParseStringNullSeparated(ofn.lpstrFile, tokens);

		if (tokens.size() == 1)
		{
			results->Append(Value::NewString(tokens.at(0)));
		}
		else if (tokens.size() > 1)
		{
			std::string directory(tokens.at(0));
			for (int i = 1; i < tokens.size(); i++)
			{
				std::string n;
				n.append(directory.c_str());
				n.append("\\");
				n.append(tokens.at(i).c_str());
				results->Append(Value::NewString(n));
			}
		}
	}
	else
	{
		DWORD error = CommDlgExtendedError();
		std::string errorMessage = Win32Utils::QuickFormatMessage(error);
		Logger::Get("UI.Win32UserWindow")->Error("Error while opening files: %s", errorMessage.c_str());
		/*
		printf("Error when opening files: %d\n", error);
		switch(error)
		{
			case CDERR_DIALOGFAILURE: printf("CDERR_DIALOGFAILURE\n"); break;
			case CDERR_FINDRESFAILURE: printf("CDERR_FINDRESFAILURE\n"); break;
			case CDERR_NOHINSTANCE: printf("CDERR_NOHINSTANCE\n"); break;
			case CDERR_INITIALIZATION: printf("CDERR_INITIALIZATION\n"); break;
			case CDERR_NOHOOK: printf("CDERR_NOHOOK\n"); break;
			case CDERR_LOCKRESFAILURE: printf("CDERR_LOCKRESFAILURE\n"); break;
			case CDERR_NOTEMPLATE: printf("CDERR_NOTEMPLATE\n"); break;
			case CDERR_LOADRESFAILURE: printf("CDERR_LOADRESFAILURE\n"); break;
			case CDERR_STRUCTSIZE: printf("CDERR_STRUCTSIZE\n"); break;
			case CDERR_LOADSTRFAILURE: printf("CDERR_LOADSTRFAILURE\n"); break;
			case FNERR_BUFFERTOOSMALL: printf("FNERR_BUFFERTOOSMALL\n"); break;
			case CDERR_MEMALLOCFAILURE: printf("CDERR_MEMALLOCFAILURE\n"); break;
			case FNERR_INVALIDFILENAME: printf("FNERR_INVALIDFILENAME\n"); break;
			case CDERR_MEMLOCKFAILURE: printf("CDERR_MEMLOCKFAILURE\n"); break;
			case FNERR_SUBCLASSFAILURE: printf("FNERR_SUBCLASSFAILURE\n"); break;
		}*/
	}
	return results;
}
Esempio n. 26
0
namespace Titanium {

static KListRef interfaceList(0);
static std::string firstIPv4Address = "127.0.0.1";

static void GetInterfaceList()
{
    if (!interfaceList.isNull())
        return;

    interfaceList = new StaticBoundList();
    std::vector<NetworkInterface> list = NetworkInterface::list();
    for (size_t i = 0; i < list.size(); i++)
    {
        NetworkInterface& interface = list[i];
        interfaceList->Append(Value::NewObject(new Interface(interface)));

        if (!interface.address().isLoopback() &&
            interface.address().isIPv4Compatible())
            firstIPv4Address = interface.address().toString();
    }
}

Network::Network()
    : KAccessorObject("Network")
    , global(kroll::Host::GetInstance()->GetGlobalObject())
{
    GetInterfaceList();
    KValueRef online = Value::NewBool(true);

    /**
     * @tiapi(property=True,name=Network.online,since=0.2)
     * @tiapi Whether or not the system is connected to the internet
     * @tiresult[Boolean] True if the system is connected to the internet, false if otherwise
     */
    this->Set("online", online);

    // methods that are available on Titanium.Network
    /**
     * @tiapi(method=True,name=Network.createTCPSocket,since=0.2) Creates a TCPSocket object
     * @tiarg(for=Network.createTCPSocket,name=host,type=String) the hostname to connect to
     * @tiarg(for=Network.createTCPSocket,name=port,type=Number) the port to use
     * @tiresult(for=Network.createTCPSocket,type=Network.TCPSocket) a TCPSocket object
     */
    this->SetMethod("createTCPSocket",&Network::_CreateTCPSocket);
    /**
     * @tiapi(method=True,name=Network.createTCPServerSocket,since=1.2) Creates a TCPServerSocket object
     * @tiarg(for=Network.createTCPServerSocket,name=callback,type=Function) the callback to receive a new connection
     * @tiresult(for=Network.createTCPServerSocket,type=Network.TCPServerSocket) a TCPServerSocket object
     */
    this->SetMethod("createTCPServerSocket",&Network::_CreateTCPServerSocket);
    /**
     * @tiapi(method=True,name=Network.createIRCClient,since=0.2) Creates an IRCClient object
     * @tiresult(for=Network.createIRCClient,type=Network.IRCClient) an IRCClient object
     */
    this->SetMethod("createIRCClient",&Network::_CreateIRCClient);
    /**
     * @tiapi(method=True,name=Network.createIPAddress,since=0.2) Creates an IPAddress object
     * @tiarg(for=Network.createIPAddress,name=address,type=String) the IP address
     * @tiresult(for=Network.createIPAddress,type=Network.IPAddress) an IPAddress object
     */
    this->SetMethod("createIPAddress",&Network::_CreateIPAddress);
    /**
     * @tiapi(method=True,name=Network.createHTTPClient,since=0.3) Creates an HTTPClient object
     * @tiresult(for=Network.createHTTPClient,type=Network.HTTPClient) an HTTPClient object
     */
    this->SetMethod("createHTTPClient",&Network::_CreateHTTPClient);
    /**
     * @tiapi(method=True,name=Network.createHTTPServer,since=0.4) Creates an HTTPServer object
     * @tiresult(for=Network.createHTTPServer,type=Network.HTTPServer) a HTTPServer object
     */
    this->SetMethod("createHTTPServer",&Network::_CreateHTTPServer);
    /**
     * @tiapi(method=True,name=Network.createHTTPCookie,since=0.7) Creates a new HTTPCookie object
     * @tiresult(for=Network.createHTTPCookie,type=Network.HTTPCookie) a HTTPCookie object
     */
    this->SetMethod("createHTTPCookie",&Network::_CreateHTTPCookie);
    /**
     * @tiapi(method=True,name=Network.getHostByName,since=0.2) Returns a Host object using a hostname
     * @tiarg(for=Network.getHostByName,name=name,type=String) the hostname
     * @tiresult(for=Network.getHostByName,type=Network.Host) a Host object referencing the hostname
     */
    this->SetMethod("getHostByName",&Network::_GetHostByName);
    /**
     * @tiapi(method=True,name=Network.getHostByAddress,since=0.2) Returns a Host object using an address
     * @tiarg(for=Network.getHostByAddress,name=address,type=String) the address
     * @tiresult(for=Network.getHostByAddress,type=Network.Host) a Host object referencing the address
     */
    this->SetMethod("getHostByAddress",&Network::_GetHostByAddress);
    /**
     * @tiapi(method=True,name=Network.encodeURIComponent,since=0.3) Encodes a URI Component
     * @tiarg(for=Network.encodeURIComponent,name=value,type=String) value to encode
     * @tiresult(for=Network.encodeURIComponent,type=String) the encoded value
     */
    this->SetMethod("encodeURIComponent",&Network::_EncodeURIComponent);
    /**
     * @tiapi(method=True,name=Network.decodeURIComponent,since=0.3) Decodes a URI component
     * @tiarg(for=Network.decodeURIComponent,name=value,type=String) value to decode
     * @tiresult(for=Network.decodeURIComponent,type=String) the decoded value
     */
    this->SetMethod("decodeURIComponent",&Network::_DecodeURIComponent);

    /**
     * @tiapi(method=True,name=Network.addConnectivityListener,since=0.2)
     * @tiapi Adds a connectivity change listener that fires when the system
     * @tiapi connects or disconnects from the internet
     * @tiarg(for=Network.addConnectivityListener,type=Function,name=listener) 
     * @tiarg A callback method to be fired when the system connects or disconnects from the internet
     * @tiresult(for=Network.addConnectivityListener,type=Number) a callback id for the event
     */
    this->SetMethod("addConnectivityListener",&Network::_AddConnectivityListener);
    /**
     * @tiapi(method=True,name=Network.removeConnectivityListener,since=0.2) Removes a connectivity change listener
     * @tiarg(for=Network.removeConnectivityListener,type=Number,name=id) the callback id of the method
     */
    this->SetMethod("removeConnectivityListener",&Network::_RemoveConnectivityListener);

    /**
     * @tiapi(method=True,name=Network.setHTTPProxy,since=0.7)
     * @tiapi Override application proxy autodetection with a proxy URL.
     * @tiarg[String, hostname] The full proxy hostname.
     */
    this->SetMethod("setHTTPProxy", &Network::_SetHTTPProxy);
    this->SetMethod("setProxy", &Network::_SetHTTPProxy);

    /**
     * @tiapi(method=True,name=Network.getHTTPProxy,since=0.7) 
     * @tiapi Return the proxy override, if one is set.
     * @tiresult[String|null] The full proxy override URL or null if none is set.
     */
    this->SetMethod("getHTTPProxy", &Network::_GetHTTPProxy);
    this->SetMethod("getProxy", &Network::_GetHTTPProxy);

    /**
     * @tiapi(method=True,name=Network.setHTTPSProxy,since=0.7)
     * @tiapi Override application proxy autodetection with a proxy URL.
     * @tiarg[String, hostname] The full proxy hostname.
     */
    this->SetMethod("setHTTPSProxy", &Network::_SetHTTPSProxy);

    /**
     * @tiapi(method=True,name=Network.getHTTPSProxy,since=0.7)
     * @tiapi Return the proxy override, if one is set.
     * @tiresult[String|null] The full proxy override URL or null if none is set.
     */
    this->SetMethod("getHTTPSProxy", &Network::_GetHTTPSProxy);

    /**
     * @tiapi(method=True,name=Network.getInterfaces,since=0.9)
     * Get a list of interfaces active on this machine.
     * @tiresult[Array<Netowrk.Interface>] An array of active interfaces.
     */
    this->SetMethod("getInterfaces", &Network::_GetInterfaces);

    /**
     * @tiapi(method=True,name=Network.getFirstIPAddress,since=0.9)
     * Get the first IPv4 address in this machine's list of interfaces.
     * @tiarg[String, address] The first IPv4 address in this system's list of interfaces.
     */ 
    this->SetMethod("getFirstIPAddress", &Network::_GetFirstIPAddress);
    this->SetMethod("getAddress", &Network::_GetFirstIPAddress); // COMPATBILITY

    /**
     * @tiapi(method=True,name=Network.getFirstMACAddress,since=0.9)
     * Get the first MAC address in this system's list of interfaces.
     * @tiarg[String, adress] The first MAC address in this system's list of interfaces.
     */
    this->SetMethod("getFirstMACAddress", &Network::_GetFirstMACAddress);
    this->SetMethod("getMACAddress", &Network::_GetFirstMACAddress);

    this->netStatus = new NetworkStatus(this);
    this->netStatus->Start();
}

Network::~Network()
{
    delete this->netStatus;
}

void Network::Shutdown()
{
    listeners.clear();
}

AutoPtr<Host> Network::GetHostBinding(const std::string& hostname)
{
    AutoPtr<Host> binding(new Host(hostname));
    if (binding->IsInvalid())
        throw ValueException::FromString("Could not resolve address");

    return binding;
}

void Network::_GetHostByAddress(const ValueList& args, KValueRef result)
{
    if (args.at(0)->IsObject())
    {
        KObjectRef obj = args.at(0)->ToObject();
        AutoPtr<IPAddress> b = obj.cast<IPAddress>();
        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
            Poco::Net::IPAddress addr(b->GetAddress()->toString());
            AutoPtr<Host> binding = new Host(addr);
            if (binding->IsInvalid())
            {
                throw ValueException::FromString("Could not resolve address");
            }
            result->SetObject(binding);
            return;
        }
        else
        {
            KMethodRef toStringMethod = obj->GetMethod("toString");
            if (toStringMethod.isNull())
                throw ValueException::FromString("Unknown object passed");

            result->SetObject(GetHostBinding(toStringMethod->Call()->ToString()));
            return;
        }
    }
    else if (args.at(0)->IsString())
    {
        // in this case, they just passed in a string so resolve as normal
        result->SetObject(GetHostBinding(args.GetString(0)));
    }
}

void Network::_GetHostByName(const ValueList& args, KValueRef result)
{
    result->SetObject(GetHostBinding(args.GetString(0)));
}

void Network::_CreateIPAddress(const ValueList& args, KValueRef result)
{
    AutoPtr<IPAddress> binding = new IPAddress(args.at(0)->ToString());
    if (binding->IsInvalid())
    {
        throw ValueException::FromString("Invalid address");
    }
    result->SetObject(binding);
}

void Network::_CreateTCPSocket(const ValueList& args, KValueRef result)
{
    args.VerifyException("createTCPSocket", "sn");
    std::string host(args.GetString(0));
    int port = args.GetInt(1);
    result->SetObject(new TCPSocket(host, port));
}

void Network::_CreateTCPServerSocket(const ValueList& args, KValueRef result)
{
    args.VerifyException("createTCPServerSocket", "m");
    KMethodRef target = args.at(0)->ToMethod();
    result->SetObject(new TCPServerSocket(target));
}

void Network::_CreateIRCClient(const ValueList& args, KValueRef result)
{
    Logger::Get("Network")->Warn("DEPRECATED: IRCClient will be removed.");
    AutoPtr<IRCClient> irc = new IRCClient();
    result->SetObject(irc);
}

void Network::_CreateHTTPClient(const ValueList& args, KValueRef result)
{
    result->SetObject(new HTTPClient());
}

void Network::_CreateHTTPServer(const ValueList& args, KValueRef result)
{
    result->SetObject(new HTTPServer());
}

void Network::_CreateHTTPCookie(const ValueList& args, KValueRef result)
{
    result->SetObject(new HTTPCookie());
}

void Network::_AddConnectivityListener(const ValueList& args, KValueRef result)
{
    args.VerifyException("addConnectivityListener", "m");
    KMethodRef target = args.at(0)->ToMethod();

    static long nextListenerId = 0;
    Listener listener = Listener();
    listener.id = nextListenerId++;
    listener.callback = target;
    this->listeners.push_back(listener);
    result->SetInt(listener.id);
}

void Network::_RemoveConnectivityListener(
    const ValueList& args, KValueRef 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);
}

bool Network::HasNetworkStatusListeners()
{
    return this->listeners.size() > 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());
        }
    }
}

void Network::_EncodeURIComponent(const ValueList &args, KValueRef result)
{
    if (args.at(0)->IsNull() || args.at(0)->IsUndefined())
    {
        result->SetString("");
    }
    else if (args.at(0)->IsString())
    {
        std::string src = args.at(0)->ToString();
        std::string sResult = URLUtils::EncodeURIComponent(src);
        result->SetString(sResult);
    }
    else if (args.at(0)->IsDouble())
    {
        std::stringstream str;
        str << args.at(0)->ToDouble();
        result->SetString(str.str().c_str());
    }
    else if (args.at(0)->IsBool())
    {
        std::stringstream str;
        str << args.at(0)->ToBool();
        result->SetString(str.str().c_str());
    }
    else if (args.at(0)->IsInt())
    {
        std::stringstream str;
        str << args.at(0)->ToInt();
        result->SetString(str.str().c_str());
    }
    else
    {
        throw ValueException::FromString("Could not encodeURIComponent with type passed");
    }
}

void Network::_DecodeURIComponent(const ValueList &args, KValueRef result)
{
    if (args.at(0)->IsNull() || args.at(0)->IsUndefined())
    {
        result->SetString("");
    }
    else if (args.at(0)->IsString())
    {
        std::string src = args.at(0)->ToString();
        std::string sResult = URLUtils::DecodeURIComponent(src);
        result->SetString(sResult);
    }
    else
    {
        throw ValueException::FromString("Could not decodeURIComponent with type passed");
    }
}

static SharedProxy ArgumentsToProxy(const ValueList& args, const std::string& scheme)
{
    if (args.at(0)->IsNull())
        return 0;

    std::string entry(args.GetString(0));
    if (entry.empty())
        return 0;

    // Do not pass the third argument entryScheme, because it overrides
    // any scheme set in the proxy string.
    return ProxyConfig::ParseProxyEntry(entry, scheme, std::string());
}

void Network::_SetHTTPProxy(const ValueList& args, KValueRef result)
{
    args.VerifyException("setHTTPProxy", "s|0 ?s s s");
    SharedProxy proxy(ArgumentsToProxy(args, "http"));
    ProxyConfig::SetHTTPProxyOverride(proxy);
}

void Network::_GetHTTPProxy(const ValueList& args, KValueRef result)
{
    SharedProxy proxy = ProxyConfig::GetHTTPProxyOverride();

    if (proxy.isNull())
        result->SetNull();
    else
        result->SetString(proxy->ToString().c_str());
}

void Network::_SetHTTPSProxy(const ValueList& args, KValueRef result)
{
    args.VerifyException("setHTTPSProxy", "s|0 ?s s s");
    SharedProxy proxy(ArgumentsToProxy(args, "https"));
    ProxyConfig::SetHTTPSProxyOverride(proxy);
}

void Network::_GetHTTPSProxy(const ValueList& args, KValueRef result)
{
    SharedProxy proxy = ProxyConfig::GetHTTPSProxyOverride();

    if (proxy.isNull())
        result->SetNull();
    else
        result->SetString(proxy->ToString().c_str());
}

void Network::_GetFirstMACAddress(const ValueList& args, KValueRef result)
{
    result->SetString(PlatformUtils::GetFirstMACAddress().c_str());
}

void Network::_GetFirstIPAddress(const ValueList& args, KValueRef result)
{
    static std::string address(Network::GetFirstIPAddress());
    result->SetString(address.c_str());
}

/*static*/
const std::string& Network::GetFirstIPAddress()
{
    return firstIPv4Address;
}

void Network::_GetInterfaces(const ValueList& args, KValueRef result)
{
    result->SetList(interfaceList);
}

} // namespace Titanium
Esempio n. 27
0
void Database::Execute(const ValueList& args, KValueRef result)
{
    args.VerifyException("execute", "s");

    if (!session)
        throw ValueException::FromString("Tried to call execute, but database was closed.");

    std::string sql(args.GetString(0));
    GetLogger()->Debug("Execute called with %s", sql.c_str());
    
    Statement select(*this->session);
    
    try
    {
        ValueBinding binding;
        
        select << sql;
        
        if (args.size()>1)
        {
            
            for (size_t c=1;c<args.size();c++)
            {
                KValueRef anarg = args.at(c);
                if (anarg->IsList())
                {
                    KListRef list = anarg->ToList();
                    for (size_t a=0;a<list->Size();a++)
                    {
                        KValueRef arg = list->At(a);
                        binding.convert(select,arg);
                    }
                }
                else
                {
                    binding.convert(select,anarg);
                }
            }
        }
        Poco::UInt32 count = select.execute();

        GetLogger()->Debug("sql returned: %d rows for result",count);

        this->SetInt("rowsAffected",count);

        // get the row insert id
        Statement ss(*this->session);
        ss << "select last_insert_rowid()", now;
        RecordSet rr(ss);
        Poco::DynamicAny value = rr.value(0);
        int i;
        value.convert(i);
        this->SetInt("lastInsertRowId",i);

        
        if (count > 0)
        {
            RecordSet rs(select);
            KObjectRef r = new ResultSet(rs);
            result->SetObject(r);
        }
        else
        {
            KObjectRef r = new ResultSet();
            result->SetObject(r);
        }
    }
    catch (Poco::Data::DataException &e)
    {
        GetLogger()->Error("Exception executing: %s, Error was: %s", sql.c_str(),
            e.what());
        throw ValueException::FromString(e.what());
    }
}
Esempio n. 28
0
namespace ti
{
    static KListRef interfaceList(0);
    static std::string firstIPv4Address = "127.0.0.1";

    static void GetInterfaceList()
    {
        if (!interfaceList.isNull())
            return;

        interfaceList = new StaticBoundList();
        std::vector<NetworkInterface> list = NetworkInterface::list();
        for (size_t i = 0; i < list.size(); i++)
        {
            NetworkInterface& interface = list[i];
            interfaceList->Append(Value::NewObject(new InterfaceBinding(interface)));

            if (!interface.address().isLoopback() &&
                interface.address().isIPv4Compatible())
                firstIPv4Address = interface.address().toString();
        }
    }

    NetworkBinding::NetworkBinding(Host* host) :
        KAccessorObject("Network"),
        host(host),
        global(host->GetGlobalObject())
    {
        GetInterfaceList();

        // methods that are available on Ti.Network
        /**
         * @tiapi(method=True,name=Network.createTCPSocket,since=0.2) Creates a TCPSocket object
         * @tiarg(for=Network.createTCPSocket,name=host,type=String) the hostname to connect to
         * @tiarg(for=Network.createTCPSocket,name=port,type=Number) the port to use
         * @tiresult(for=Network.createTCPSocket,type=Network.TCPSocket) a TCPSocket object
         */
        this->SetMethod("createTCPSocket",&NetworkBinding::_CreateTCPSocket);
        /**
         * @tiapi(method=True,name=Network.createTCPServerSocket,since=1.2) Creates a TCPServerSocket object
         * @tiarg(for=Network.createTCPServerSocket,name=callback,type=Function) the callback to receive a new connection
         * @tiresult(for=Network.createTCPServerSocket,type=Network.TCPServerSocket) a TCPServerSocket object
         */
        this->SetMethod("createTCPServerSocket",&NetworkBinding::_CreateTCPServerSocket);
        /**
         * @tiapi(method=True,name=Network.createIRCClient,since=0.2) Creates an IRCClient object
         * @tiresult(for=Network.createIRCClient,type=Network.IRCClient) an IRCClient object
         */
        this->SetMethod("createIRCClient",&NetworkBinding::_CreateIRCClient);
        /**
         * @tiapi(method=True,name=Network.createIPAddress,since=0.2) Creates an IPAddress object
         * @tiarg(for=Network.createIPAddress,name=address,type=String) the IP address
         * @tiresult(for=Network.createIPAddress,type=Network.IPAddress) an IPAddress object
         */
        this->SetMethod("createIPAddress",&NetworkBinding::_CreateIPAddress);
        /**
         * @tiapi(method=True,name=Network.createHTTPClient,since=0.3) Creates an HTTPClient object
         * @tiresult(for=Network.createHTTPClient,type=Network.HTTPClient) an HTTPClient object
         */
        this->SetMethod("createHTTPClient",&NetworkBinding::_CreateHTTPClient);
        /**
         * @tiapi(method=True,name=Network.createHTTPServer,since=0.4) Creates an HTTPServer object
         * @tiresult(for=Network.createHTTPServer,type=Network.HTTPServer) a HTTPServer object
         */
        this->SetMethod("createHTTPServer",&NetworkBinding::_CreateHTTPServer);
        /**
         * @tiapi(method=True,name=Network.createHTTPCookie,since=0.7) Creates a new HTTPCookie object
         * @tiresult(for=Network.createHTTPCookie,type=Network.HTTPCookie) a HTTPCookie object
         */
        this->SetMethod("createHTTPCookie",&NetworkBinding::_CreateHTTPCookie);
        /**
         * @tiapi(method=True,name=Network.getHostByName,since=0.2) Returns a Host object using a hostname
         * @tiarg(for=Network.getHostByName,name=name,type=String) the hostname
         * @tiresult(for=Network.getHostByName,type=Network.Host) a Host object referencing the hostname
         */
        this->SetMethod("getHostByName",&NetworkBinding::_GetHostByName);
        /**
         * @tiapi(method=True,name=Network.getHostByAddress,since=0.2) Returns a Host object using an address
         * @tiarg(for=Network.getHostByAddress,name=address,type=String) the address
         * @tiresult(for=Network.getHostByAddress,type=Network.Host) a Host object referencing the address
         */
        this->SetMethod("getHostByAddress",&NetworkBinding::_GetHostByAddress);
        /**
         * @tiapi(method=True,name=Network.encodeURIComponent,since=0.3) Encodes a URI Component
         * @tiarg(for=Network.encodeURIComponent,name=value,type=String) value to encode
         * @tiresult(for=Network.encodeURIComponent,type=String) the encoded value
         */
        this->SetMethod("encodeURIComponent",&NetworkBinding::_EncodeURIComponent);
        /**
         * @tiapi(method=True,name=Network.decodeURIComponent,since=0.3) Decodes a URI component
         * @tiarg(for=Network.decodeURIComponent,name=value,type=String) value to decode
         * @tiresult(for=Network.decodeURIComponent,type=String) the decoded value
         */
        this->SetMethod("decodeURIComponent",&NetworkBinding::_DecodeURIComponent);

        /**
         * @tiapi(method=True,name=Network.setHTTPProxy,since=0.7)
         * @tiapi Override application proxy autodetection with a proxy URL.
         * @tiarg[String, hostname] The full proxy hostname.
         */
        this->SetMethod("setHTTPProxy", &NetworkBinding::_SetHTTPProxy);
        this->SetMethod("setProxy", &NetworkBinding::_SetHTTPProxy);

        /**
         * @tiapi(method=True,name=Network.getHTTPProxy,since=0.7) 
         * @tiapi Return the proxy override, if one is set.
         * @tiresult[String|null] The full proxy override URL or null if none is set.
         */
        this->SetMethod("getHTTPProxy", &NetworkBinding::_GetHTTPProxy);
        this->SetMethod("getProxy", &NetworkBinding::_GetHTTPProxy);

        /**
         * @tiapi(method=True,name=Network.setHTTPSProxy,since=0.7)
         * @tiapi Override application proxy autodetection with a proxy URL.
         * @tiarg[String, hostname] The full proxy hostname.
         */
        this->SetMethod("setHTTPSProxy", &NetworkBinding::_SetHTTPSProxy);

        /**
         * @tiapi(method=True,name=Network.getHTTPSProxy,since=0.7)
         * @tiapi Return the proxy override, if one is set.
         * @tiresult[String|null] The full proxy override URL or null if none is set.
         */
        this->SetMethod("getHTTPSProxy", &NetworkBinding::_GetHTTPSProxy);

        /**
         * @tiapi(method=True,name=Network.getInterfaces,since=0.9)
         * Get a list of interfaces active on this machine.
         * @tiresult[Array<Netowrk.Interface>] An array of active interfaces.
         */
        this->SetMethod("getInterfaces", &NetworkBinding::_GetInterfaces);

        /**
         * @tiapi(method=True,name=Network.getFirstIPAddress,since=0.9)
         * Get the first IPv4 address in this machine's list of interfaces.
         * @tiarg[String, address] The first IPv4 address in this system's list of interfaces.
         */ 
        this->SetMethod("getFirstIPAddress", &NetworkBinding::_GetFirstIPAddress);
        this->SetMethod("getAddress", &NetworkBinding::_GetFirstIPAddress); // COMPATBILITY

        /**
         * @tiapi(method=True,name=Network.getFirstMACAddress,since=0.9)
         * Get the first MAC address in this system's list of interfaces.
         * @tiarg[String, adress] The first MAC address in this system's list of interfaces.
         */
        this->SetMethod("getFirstMACAddress", &NetworkBinding::_GetFirstMACAddress);
        this->SetMethod("getMACAddress", &NetworkBinding::_GetFirstMACAddress);
    }

    NetworkBinding::~NetworkBinding()
    {
    }

    AutoPtr<HostBinding> NetworkBinding::GetHostBinding(std::string hostname)
    {
        AutoPtr<HostBinding> binding(new HostBinding(hostname));
        if (binding->IsInvalid())
            throw ValueException::FromString("Could not resolve address");

        return binding;
    }

    void NetworkBinding::_GetHostByAddress(const ValueList& args, KValueRef result)
    {
        if (args.at(0)->IsObject())
        {
            KObjectRef obj = args.at(0)->ToObject();
            AutoPtr<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());
                AutoPtr<HostBinding> binding = new HostBinding(addr);
                if (binding->IsInvalid())
                {
                    throw ValueException::FromString("Could not resolve address");
                }
                result->SetObject(binding);
                return;
            }
            else
            {
                KMethodRef toStringMethod = obj->GetMethod("toString");
                if (toStringMethod.isNull())
                    throw ValueException::FromString("Unknown object passed");

                result->SetObject(GetHostBinding(toStringMethod->Call()->ToString()));
                return;
            }
        }
        else if (args.at(0)->IsString())
        {
            // in this case, they just passed in a string so resolve as normal
            result->SetObject(GetHostBinding(args.GetString(0)));
        }
    }

    void NetworkBinding::_GetHostByName(const ValueList& args, KValueRef result)
    {
        result->SetObject(GetHostBinding(args.GetString(0)));
    }

    void NetworkBinding::_CreateIPAddress(const ValueList& args, KValueRef result)
    {
        AutoPtr<IPAddressBinding> binding = new IPAddressBinding(args.at(0)->ToString());
        if (binding->IsInvalid())
        {
            throw ValueException::FromString("Invalid address");
        }
        result->SetObject(binding);
    }

    void NetworkBinding::_CreateTCPSocket(const ValueList& args, KValueRef result)
    {
        args.VerifyException("createTCPSocket", "sn");
        std::string host(args.GetString(0));
        int port = args.GetInt(1);
        result->SetObject(new TCPSocket(host, port));
    }

    void NetworkBinding::_CreateTCPServerSocket(const ValueList& args, KValueRef result)
    {
        args.VerifyException("createTCPServerSocket", "m");
        KMethodRef target = args.at(0)->ToMethod();
        result->SetObject(new TCPServerSocketBinding(host,target));
    }

    void NetworkBinding::_CreateIRCClient(const ValueList& args, KValueRef result)
    {
        AutoPtr<IRCClientBinding> irc = new IRCClientBinding(host);
        result->SetObject(irc);
    }

    void NetworkBinding::_CreateHTTPClient(const ValueList& args, KValueRef result)
    {
        result->SetObject(new HTTPClientBinding(host));
    }

    void NetworkBinding::_CreateHTTPServer(const ValueList& args, KValueRef result)
    {
        result->SetObject(new HTTPServerBinding(host));
    }

    void NetworkBinding::_CreateHTTPCookie(const ValueList& args, KValueRef result)
    {
        result->SetObject(new HTTPCookie());
    }

    void NetworkBinding::_EncodeURIComponent(const ValueList &args, KValueRef result)
    {
        if (args.at(0)->IsNull() || args.at(0)->IsUndefined())
        {
            result->SetString("");
        }
        else if (args.at(0)->IsString())
        {
            std::string src = args.at(0)->ToString();
            std::string sResult = URLUtils::EncodeURIComponent(src);
            result->SetString(sResult);
        }
        else if (args.at(0)->IsDouble())
        {
            std::stringstream str;
            str << args.at(0)->ToDouble();
            result->SetString(str.str().c_str());
        }
        else if (args.at(0)->IsBool())
        {
            std::stringstream str;
            str << args.at(0)->ToBool();
            result->SetString(str.str().c_str());
        }
        else if (args.at(0)->IsInt())
        {
            std::stringstream str;
            str << args.at(0)->ToInt();
            result->SetString(str.str().c_str());
        }
        else
        {
            throw ValueException::FromString("Could not encodeURIComponent with type passed");
        }
    }

    void NetworkBinding::_DecodeURIComponent(const ValueList &args, KValueRef result)
    {
        if (args.at(0)->IsNull() || args.at(0)->IsUndefined())
        {
            result->SetString("");
        }
        else if (args.at(0)->IsString())
        {
            std::string src = args.at(0)->ToString();
            std::string sResult = URLUtils::DecodeURIComponent(src);
            result->SetString(sResult);
        }
        else
        {
            throw ValueException::FromString("Could not decodeURIComponent with type passed");
        }
    }

    static SharedProxy ArgumentsToProxy(const ValueList& args, const std::string& scheme)
    {
        if (args.at(0)->IsNull())
            return 0;

        std::string entry(args.GetString(0));
        if (entry.empty())
            return 0;

        // Do not pass the third argument entryScheme, because it overrides
        // any scheme set in the proxy string.
        return ProxyConfig::ParseProxyEntry(entry, scheme, std::string());
    }

    void NetworkBinding::_SetHTTPProxy(const ValueList& args, KValueRef result)
    {
        args.VerifyException("setHTTPProxy", "s|0 ?s s s");
        SharedProxy proxy(ArgumentsToProxy(args, "http"));
        ProxyConfig::SetHTTPProxyOverride(proxy);
    }

    void NetworkBinding::_GetHTTPProxy(const ValueList& args, KValueRef result)
    {
        SharedProxy proxy = ProxyConfig::GetHTTPProxyOverride();

        if (proxy.isNull())
            result->SetNull();
        else
            result->SetString(proxy->ToString().c_str());
    }

    void NetworkBinding::_SetHTTPSProxy(const ValueList& args, KValueRef result)
    {
        args.VerifyException("setHTTPSProxy", "s|0 ?s s s");
        SharedProxy proxy(ArgumentsToProxy(args, "https"));
        ProxyConfig::SetHTTPSProxyOverride(proxy);
    }

    void NetworkBinding::_GetHTTPSProxy(const ValueList& args, KValueRef result)
    {
        SharedProxy proxy = ProxyConfig::GetHTTPSProxyOverride();

        if (proxy.isNull())
            result->SetNull();
        else
            result->SetString(proxy->ToString().c_str());
    }

    Host* NetworkBinding::GetHost()
    {
        return this->host;
    }

    void NetworkBinding::_GetFirstMACAddress(const ValueList& args, KValueRef result)
    {
        result->SetString(PlatformUtils::GetFirstMACAddress().c_str());
    }

    void NetworkBinding::_GetFirstIPAddress(const ValueList& args, KValueRef result)
    {
        static std::string address(NetworkBinding::GetFirstIPAddress());
        result->SetString(address.c_str());
    }

    /*static*/
    const std::string& NetworkBinding::GetFirstIPAddress()
    {
        return firstIPv4Address;
    }

    void NetworkBinding::_GetInterfaces(const ValueList& args, KValueRef result)
    {
        result->SetList(interfaceList);
    }
}