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); } } }
void UserWindow::PageLoaded(SharedKObject global_bound_object, std::string &url) { SharedKObject event = new StaticBoundObject(); event->Set("scope", Value::NewObject(global_bound_object)); event->Set("url", Value::NewString(url.c_str())); this->FireEvent(LOAD, event); }
HRESULT STDMETHODCALLTYPE ScriptEvaluator::evaluate(BSTR mimeType, BSTR sourceCode, int *context) { std::string type = BSTRToString(mimeType); std::string moduleName = GetModuleName(type); JSContextRef contextRef = reinterpret_cast<JSContextRef>(context); SharedKObject global = host->GetGlobalObject(); SharedValue moduleValue = global->Get(moduleName.c_str()); if (!moduleValue->IsNull()) { SharedValue evalValue = moduleValue->ToObject()->Get("evaluate"); if (!evalValue->IsNull() && evalValue->IsMethod()) { ValueList args; SharedValue typeValue = Value::NewString(type); SharedValue sourceCodeValue = Value::NewString(BSTRToString(sourceCode)); JSObjectRef globalObjectRef = JSContextGetGlobalObject(contextRef); SharedKObject contextObject = new KKJSObject(contextRef, globalObjectRef); SharedValue contextValue = Value::NewObject(contextObject); args.push_back(typeValue); args.push_back(sourceCodeValue); args.push_back(contextValue); evalValue->ToMethod()->Call(args); } } return S_OK; }
void UIBinding::_SetContextMenu(const ValueList& args, SharedValue result) { args.VerifyException("setContextMenu", "o|0"); SharedKObject argObj = args.GetObject(0, NULL); AutoMenu menu = NULL; if (!argObj.isNull()) { menu = argObj.cast<Menu>(); } this->SetContextMenu(menu); }
// A :responds_to? method for finding KObject properties in Ruby static VALUE RubyKObjectRespondTo(int argc, VALUE *argv, VALUE self) { SharedValue* dval = NULL; Data_Get_Struct(self, SharedValue, dval); SharedKObject object = (*dval)->ToObject(); VALUE mid, priv; // We ignore the priv argument rb_scan_args(argc, argv, "11", &mid, &priv); const char* name = rb_id2name(rb_to_id(mid)); SharedValue value = object->Get(name); return value->IsUndefined() ? Qfalse : Qtrue; }
void NetworkBinding::RemoveBinding(void* binding) { std::vector<SharedKObject>::iterator i = bindings.begin(); while(i!=bindings.end()) { SharedKObject b = (*i); if (binding == b.get()) { bindings.erase(i); break; } i++; } }
void MonkeyBinding::Callback(const ValueList &args, SharedValue result) { SharedKObject event = args.at(1)->ToObject(); std::string url_value = event->Get("url")->ToString(); std::vector< std::pair< std::pair< VectorOfPatterns,VectorOfPatterns >,std::string> >::iterator iter = scripts.begin(); while(iter!=scripts.end()) { std::pair< std::pair< VectorOfPatterns,VectorOfPatterns >, std::string> e = (*iter++); VectorOfPatterns include = e.first.first; VectorOfPatterns exclude = e.first.second; if (Matches(exclude,url_value)) { continue; } if (Matches(include,url_value)) { // I got a castle in brooklyn, that's where i dwell try { SharedKMethod eval = event->Get("scope")->ToObject()->Get("window")->ToObject()->Get("eval")->ToMethod(); #ifdef DEBUG std::cout << ">>> loading user script for " << url_value << std::endl; #endif eval->Call(Value::NewString(e.second)); } catch (ValueException &ex) { Logger* logger = Logger::Get("Monkey"); SharedString ss = ex.DisplayString(); int line = -1; if (ex.GetValue()->IsObject() && ex.GetValue()->ToObject()->Get("line")->IsNumber()) { line = ex.GetValue()->ToObject()->Get("line")->ToInt(); } logger->Error( "Exception generated evaluating user script for %s " "(line %i): %s", url_value.c_str(), line, ss->c_str()); } catch (std::exception &ex) { Logger* logger = Logger::Get("Monkey"); logger->Error("Exception generated evaluating user script for %s, Exception: %s",url_value.c_str(),ex.what()); } } } }
// A :method_missing method for finding KObject properties in Ruby static VALUE RubyKObjectMethodMissing(int argc, VALUE *argv, VALUE self) { SharedValue* dval = NULL; Data_Get_Struct(self, SharedValue, dval); SharedKObject object = (*dval)->ToObject(); // TODO: We should raise an exception instead if (object.isNull()) return Qnil; // This is the same error that ruby throws if (argc == 0 || !SYMBOL_P(argv[0])) { rb_raise(rb_eArgError, "no id given"); } // We need to determine the method that was invoked: // store the method name and arguments in separate variables VALUE r_name, args; rb_scan_args(argc, argv, "1*", &r_name, &args); const char* name = rb_id2name(SYM2ID(r_name)); // Check if this is an assignment SharedValue value = object->Get(name); if (name[strlen(name) - 1] == '=' && argc > 1) { char* mod_name = strdup(name); mod_name[strlen(mod_name) - 1] = '\0'; value = RubyUtils::ToKrollValue(argv[1]); object->Set(mod_name, value); free(mod_name); return argv[1]; } else if (value->IsUndefined()) // raise a method missing error { VALUE selfString = rb_obj_as_string(self); rb_raise(rb_eNoMethodError, "undefined method `%s' for %s", name, RubyUtils::ToString(selfString)); } else if (value->IsMethod()) // actually call a method { return RubyUtils::GenericKMethodCall(value->ToMethod(), args); } else // Plain old access { return RubyUtils::ToRubyValue(value); } }
static VALUE RubyKObjectMethods(VALUE self) { SharedValue* value = NULL; Data_Get_Struct(self, SharedValue, value); SharedKObject object = (*value)->ToObject(); VALUE* args = NULL; VALUE methods = rb_call_super(0, args); SharedStringList props = object->GetPropertyNames(); for (unsigned int i = 0; i < props->size(); i++) { SharedString prop_name = props->at(i); rb_ary_push(methods, rb_str_new2(prop_name->c_str())); } return methods; }
HRESULT STDMETHODCALLTYPE ScriptEvaluator::matchesMimeType(BSTR mimeType, BOOL *result) { std::string moduleName = GetModuleName(BSTRToString(mimeType)); SharedKObject global = host->GetGlobalObject(); SharedValue moduleValue = global->Get(moduleName.c_str()); *result = FALSE; if (!moduleValue->IsNull() && moduleValue->IsObject()) { if (!moduleValue->ToObject()->Get("evaluate")->IsNull() && !moduleValue->ToObject()->Get("evaluate")->IsUndefined() && moduleValue->ToObject()->Get("evaluate")->IsMethod()) { *result = TRUE; } } return S_OK; }
void UIBinding::_SetMenu(const ValueList& args, SharedValue result) { args.VerifyException("setMenu", "o|0"); SharedKObject argObj = args.GetObject(0, NULL); AutoMenu menu = NULL; if (!argObj.isNull()) { menu = argObj.cast<Menu>(); } this->SetMenu(menu); // platform-specific impl // Notify all windows that the app menu has changed. std::vector<AutoUserWindow>::iterator i = openWindows.begin(); while (i != openWindows.end()) { (*i++)->AppMenuChanged(); } }
void HTTPClientBinding::Send(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(); this->datastream = obj->Get("toString")->ToMethod()->Call()->ToString(); } else if (v->IsString()) { this->datastream = v->ToString(); } else if (v->IsNull() || v->IsUndefined()) { this->datastream = ""; } 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 (sync)"); Poco::Stopwatch sw; sw.start(); while (!this->shutdown && sw.elapsedSeconds() * 1000 < this->timeout) { this->thread->tryJoin(100); } PRINTD("HTTP Client thread finished (sync)"); } }
void IRCClientBinding::GetUsers(const ValueList& args, SharedValue result) { const char *channel = args.at(0)->ToString(); SharedKList list = new StaticBoundList(); channel_user* cu = irc.get_users(); while(cu) { if (!strcmp(cu->channel,(char*)channel) && cu->nick && strlen(cu->nick)>0) { SharedKObject entry = new StaticBoundObject(); entry->Set("name",Value::NewString(cu->nick)); entry->Set("operator",Value::NewBool(cu->flags & IRC_USER_OP)); entry->Set("voice",Value::NewBool(cu->flags & IRC_USER_VOICE)); list->Append(Value::NewObject(entry)); } cu = cu->next; } result->SetList(list); }
void HTTPClientBinding::SendFile(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()) { std::string file = obj->Get("toString")->ToMethod()->Call()->ToString(); this->filestream = new Poco::FileInputStream(file); Poco::Path p(file); this->filename = p.getFileName(); } else { this->datastream = obj->Get("toString")->ToMethod()->Call()->ToString(); } } else if (v->IsString()) { this->filestream = new Poco::FileInputStream(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(); } }
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); } }
// A :method method for pulling methods off of KObjects in Ruby static VALUE RubyKObjectMethod(int argc, VALUE *argv, VALUE self) { SharedValue* dval = NULL; Data_Get_Struct(self, SharedValue, dval); SharedKObject object = (*dval)->ToObject(); // TODO: We should raise an exception instead if (object.isNull()) return Qnil; if (argc < 1) return Qnil; VALUE meth_name = argv[0]; const char* name = rb_id2name(SYM2ID(meth_name)); SharedValue v = object->Get(name); if (v->IsMethod()) { return RubyUtils::ToRubyValue(v); } else { return Qnil; } }
void MonkeyBinding::EvaluateUserScript( SharedKObject event, std::string& url, SharedKObject windowObject, std::string& scriptSource) { static Logger *logger = Logger::Get("Monkey"); // I got a castle in brooklyn, that's where i dwell // Word, brother. if (!windowObject->Get("eval")->IsMethod()) { logger->Error("Found a window object without an " "eval function (%s) -- aborting", url.c_str()); return; } SharedKObject target = event->GetObject("target"); if (!windowObject->Get(GLOBAL_NS_VARNAME)->IsObject() && !target.isNull() && target->Get("insertAPI")->IsMethod()) { logger->Info("Forcing Titanium API into: %s\n", url.c_str()); target->CallNS("insertAPI", Value::NewObject(windowObject)); } SharedKMethod evalFunction = windowObject->GetMethod("eval"); logger->Info("Loading userscript for %s\n", url.c_str()); try { evalFunction->Call(Value::NewString(scriptSource)); } catch (ValueException &ex) { SharedString ss = ex.DisplayString(); int line = -1; if (ex.GetValue()->IsObject() && ex.GetValue()->ToObject()->Get("line")->IsNumber()) { line = ex.GetValue()->ToObject()->Get("line")->ToInt(); } logger->Error( "Exception generated evaluating user script for %s " "(line %i): %s", url.c_str(), line, ss->c_str()); } }
void UserWindow::_SetBounds(const kroll::ValueList& args, kroll::SharedValue result) { if (args.size() < 1 || !args.at(0)->IsObject()) { throw ValueException::FromString("setBounds takes an object with x, y, width and height properties."); return; } SharedKObject o = args.at(0)->ToObject(); if (!o->Get("x")->IsNumber() || !o->Get("y")->IsNumber() || !o->Get("width")->IsNumber() ||!o->Get("height")->IsNumber()) { throw ValueException::FromString("setBounds takes an object with x, y, width and height properties."); return; } double x = o->Get("x")->ToNumber(); double y = o->Get("y")->ToNumber(); double w = o->Get("width")->ToNumber(); double h = o->Get("height")->ToNumber(); w = UserWindow::Constrain(w, config->GetMinWidth(), config->GetMaxWidth()); h = UserWindow::Constrain(h, config->GetMinHeight(), config->GetMaxHeight()); this->config->SetX(x); this->config->SetY(y); this->config->SetWidth(w); this->config->SetHeight(h); if (this->active) { Bounds bounds; bounds.x = x; bounds.y = y; bounds.width = w; bounds.height = h; this->SetBounds(bounds); } }
void MonkeyBinding::Callback(const ValueList &args, SharedValue result) { SharedKObject event = args.at(0)->ToObject(); if (!event->Get("url")->IsString() || !event->Get("scope")->IsObject() || !event->GetObject("scope")->Get("window")) { throw ValueException::FromString( "ti.Monkey could not find required components of PAGE_LOADED events"); } std::string url = event->GetString("url"); SharedKObject windowObject = event->GetObject("scope")->GetObject("window"); vector<Script*>::iterator iter = scripts.begin(); while (iter != scripts.end()) { Script* script = (*iter++); if (script->Matches(url)) { EvaluateUserScript(event, url, windowObject, script->source); } } }
void UserWindow::ReadChooserDialogObject( SharedKObject o, bool& multiple, std::string& title, std::string& path, std::string& defaultName, std::vector<std::string>& types, std::string& typesDescription) { // Pass in a set of properties for chooser dialogs like this: // var selected = Titanium.UI.OpenFileChooserDialog(callback, // { // multiple:true, // title: "Select file to delete...", // defaultFile: "autoexec.bat", // path: "C:\" // types:['js','html'] // }); multiple = o->GetBool("multiple", true); title = o->GetString("title", title); path = o->GetString("path", path); defaultName = o->GetString("defaultName", defaultName); SharedKList listTypes = new StaticBoundList(); listTypes = o->GetList("types", listTypes); for (size_t i = 0; i < listTypes->Size(); i++) { if (listTypes->At(i)->IsString()) { types.push_back(listTypes->At(i)->ToString()); std::cout << "Found " << listTypes->At(i)->ToString() << std::endl; } } typesDescription = o->GetString("typesDescription", defaultName); }
void UserWindow::FireEvent(UserWindowEvent event_type, SharedKObject event) { std::string name; switch (event_type) { case FOCUSED: { name = "focused"; break; } case UNFOCUSED: { name = "unfocused"; break; } case OPEN: { name = "open"; break; } case OPENED: { name = "opened"; break; } case CLOSE: { name = "close"; break; } case CLOSED: { name = "closed"; break; } case HIDDEN: { name = "hidden"; break; } case SHOWN: { name = "shown"; break; } case FULLSCREENED: { name = "fullscreened"; break; } case UNFULLSCREENED: { name = "unfullscreened"; break; } case MAXIMIZED: { name = "maximized"; break; } case MINIMIZED: { name = "minimized"; break; } case RESIZED: { name = "resized"; break; } case MOVED: { name = "moved"; break; } case INIT: { name = "page.init"; break; } case LOAD: { name = "page.load"; break; } case CREATE: { name = "create"; break; } } std::string en = std::string("ti.UI.window.") + name; if (event.isNull()) { event = new StaticBoundObject(); } event->Set("window", Value::NewObject(this->shared_this)); this->api->Call(en.c_str(), Value::NewObject(event)); // If we don't have listeners here, we can just bail. if (this->listeners.size() == 0) { return; } ValueList args; args.push_back(Value::NewString(name)); args.push_back(Value::NewObject(event)); std::vector<Listener>::iterator it = this->listeners.begin(); while (it != this->listeners.end()) { SharedKMethod callback = (*it).callback; try { this->host->InvokeMethodOnMainThread(callback,args,false); } catch(std::exception &e) { std::cerr << "Caught exception dispatching window event callback: " << event << ", Error: " << e.what() << std::endl; } it++; } }
bool KObject::Equals(SharedKObject other) { return other.get() == this; }
UIBinding::UIBinding(Host *host) : AccessorBoundObject("UI"), host(host) { instance = this; // @tiproperty[Number, UI.CENTERED, since=1.0] The CENTERED event constant this->Set("CENTERED", Value::NewInt(UIBinding::CENTERED)); /** * @tiapi(method=True,name=UI.createMenu,version=1.0) * @tiapi Create a new menu * @tiresult[UI.Menu] A new menu */ this->SetMethod("createMenu", &UIBinding::_CreateMenu); /** * @tiapi(method=True,name=UI.createMenuItem,version=1.0) * @tiapi Create a new menu item. * @tiarg[String, label] The label for this menu item * @tiarg[Function, eventListener, optional=True] An event listener for this menu item * @tiarg[String, iconURL, optional=True] A URL to an icon to use for this menu item * @tiresult[UI.MenuItem] A new menu item */ this->SetMethod("createMenuItem", &UIBinding::_CreateMenuItem); /** * @tiapi(method=True,name=UI.createCheckMenuItem,version=1.0) * @tiapi Create a new CheckMenuItem object. * @tiarg[String, label] The label for this menu item * @tiarg[Function, eventListener, optional=True] An event listener for this menu item * @tiresult[UI.CheckMenuItem] The new CheckMenuItem object */ this->SetMethod("createCheckMenuItem", &UIBinding::_CreateCheckMenuItem); /** * @tiapi(method=True,name=UI.createSeperatorMenuItem,version=1.0) * @tiapi Create a new separator menu item. * @tiresult[UI.SeparatorMenuItem] A new separator menu item */ this->SetMethod("createSeparatorMenuItem", &UIBinding::_CreateSeparatorMenuItem); /** * @tiapi(method=True,name=UI.setMenu,version=0.2) Sets a menu for the application * @tiarg[UI.Menu|null, menu] A Menu object to use as the menu or null to unset the menu */ this->SetMethod("setMenu", &UIBinding::_SetMenu); /** * @tiapi(method=True,name=UI.getMenu,version=0.2) Returns the application's main MenuItem * @tiresult[UI.Menu|null] The application's main menu */ this->SetMethod("getMenu", &UIBinding::_GetMenu); /** * @tiapi(method=True,name=UI.setContextMenu,version=0.2) Sets the application's context menu * @tiarg(for=UI.setContextMenu,type=UI.Menu|null,name=menu) a MenuItem object or null to unset */ this->SetMethod("setContextMenu", &UIBinding::_SetContextMenu); /** * @tiapi(method=True,name=UI.getContextMenu,version=0.2) Returns the application context menu * @tiresult(for=UI.getContextMenu,type=UI.Menu|null) the application's context MenuItem object */ this->SetMethod("getContextMenu", &UIBinding::_GetContextMenu); /** * @tiapi(method=True,name=UI.setIcon,version=0.2) Sets the application's icon * @tiarg(for=UI.setIcon,type=String,name=menu) path to the icon */ this->SetMethod("setIcon", &UIBinding::_SetIcon); /** * @tiapi(method=True,name=UI.addTray,version=0.2,deprecated=True) * @tiapi Create and add a tray icon * @tiarg[String, iconURL] URL to the icon to use for this tray item * @tiarg[Function, eventListener, optional=True] Event listener to add for this item * @tiresult(for=UI.addTray,type=UI.Tray|null) the application's Tray icon object */ this->SetMethod("addTray", &UIBinding::_AddTray); /** * @tiapi(method=True,name=UI.clearTray,version=0.2) * @tiapi Empty the tray of all this application's tray items */ this->SetMethod("clearTray", &UIBinding::_ClearTray); /** * @tiapi(method=True,name=UI.setDockIcon,version=0.2) Sets the dock icon * @tiarg(for=UI.setDockIcon,type=String,name=icon) path to the icon */ this->SetMethod("setDockIcon", &UIBinding::_SetDockIcon); /** * @tiapi(method=True,name=UI.setDockMenu,version=0.2) Sets the dock menu * @tiarg(for=UI.setDockMenu,type=UI.Menu,name=menu) The new menu for the dock */ this->SetMethod("setDockMenu", &UIBinding::_SetDockMenu); /** * @tiapi(method=True,name=UI.setBadge,version=0.2) Sets the application's badge value * @tiarg(for=UI.setBadge,type=String,name=badge) badge value */ this->SetMethod("setBadge", &UIBinding::_SetBadge); /** * @tiapi(method=True,name=UI.setBadgeImage,version=0.2) Sets the application's badge image * @tiarg(for=UI.setBadge,type=String,name=badge_image) path to badge image */ this->SetMethod("setBadgeImage", &UIBinding::_SetBadgeImage); /** * @tiapi(method=True,name=UI.getIdleTime,version=0.2) * @tiapi Returns the user's idle time (for the desktop, not just the application) * @tiresult(for=UI.getIdleTime,type=Number) Number of milliseconds of idle time. */ this->SetMethod("getIdleTime", &UIBinding::_GetIdleTime); /** * @tiapi(method=True,name=UI.getOpenWindows,version=0.4) Returns the list of currently open windows * @tiresult(for=UI.getOpenWindows,type=Array<UI.UserWindow>) the list of open windows */ /** * @tiapi(method=True,name=UI.getWindows,version=0.4) Returns the list of currently open windows * @tiresult(for=UI.getWindows,type=Array<UI.UserWindow>) the list of open windows */ this->SetMethod("getOpenWindows", &UIBinding::_GetOpenWindows); this->SetMethod("getWindows", &UIBinding::_GetOpenWindows); /** * @tiapi(method=True,name=UI.getMainWindow,version=1.0) * @tiapi Return the application's main window * @tiresult[UI.UserWindow] The main window for this application */ this->SetMethod("getMainWindow", &UIBinding::_GetMainWindow); SharedKObject global = host->GetGlobalObject(); SharedValue ui_binding_val = Value::NewObject(this); global->Set("UI", ui_binding_val); }
MonkeyBinding::MonkeyBinding(Host *host, SharedKObject global) : global(global), registration(0), logger(Logger::Get("Monkey")) { std::string resourcesPath = host->GetApplication()->GetResourcesPath(); std::string userscriptsPath = FileUtils::Join( resourcesPath.c_str(), "userscripts", NULL); if (FileUtils::IsDirectory(userscriptsPath)) { logger->Debug("Found userscripts directory at: %s\n", userscriptsPath.c_str()); std::vector<std::string> files; FileUtils::ListDir(userscriptsPath,files); if (files.size()>0) { std::vector<std::string>::iterator iter = files.begin(); while(iter!=files.end()) { std::string file = (*iter++); std::string fn = FileUtils::Join(userscriptsPath.c_str(),file.c_str(),NULL); Poco::Path path(fn); if (path.getExtension() == "js") { Poco::FileInputStream f(fn); std::string line; std::ostringstream str; bool found = false, start = false; VectorOfPatterns includes; VectorOfPatterns excludes; while (!f.eof()) { std::getline(f, line); if (line.find("// ==UserScript==") == 0) { found = true; } else if (found && !start) { std::string::size_type i = line.find("// @include"); if (i == 0) { std::string url = FileUtils::Trim(line.substr(i+12).c_str()); includes.push_back(PatternMatcher(url)); continue; } i = line.find("// @exclude"); if (i == 0) { std::string url = FileUtils::Trim(line.substr(i+12).c_str()); excludes.push_back(PatternMatcher(url)); } else if (line.find("// ==/UserScript==") == 0) { start = true; str << "(function(){\n"; } //TODO: @require } else if (start) { str << line << "\n"; } } if (found && start) { str << "\n})();"; try { std::pair<VectorOfPatterns,VectorOfPatterns> r(includes,excludes); scripts.push_back(std::pair<std::pair< VectorOfPatterns,VectorOfPatterns >,std::string>(r,str.str())); } catch(Poco::RegularExpressionException &e) { std::cerr << "Exception loading user script: " << fn << " Exception: " << e.what() << std::endl; } } } } if (scripts.size()>0) { this->SetMethod("callback",&MonkeyBinding::Callback); SharedValue v = global->CallNS("API.register",Value::NewString("ti.UI.window.page.load"),this->Get("callback")); this->registration = v->ToInt(); } } } }
AppBinding::AppBinding(Host *host, SharedKObject global) : host(host), global(global) { /** * @tiapi(method=True,immutable=True,name=App.getID,since=0.2) Returns the application id * @tiresult(for=App.getID,type=string) returns the id */ this->SetMethod("getID", &AppBinding::GetID); /** * @tiapi(method=True,immutable=True,name=App.getName,since=0.2) Returns the application name * @tiresult(for=App.getName,type=string) returns the name */ this->SetMethod("getName", &AppBinding::GetName); /** * @tiapi(method=True,immutable=True,name=App.getVersion,since=0.2) Returns the application version * @tiresult(for=App.getVersion,type=string) returns the version */ this->SetMethod("getVersion", &AppBinding::GetVersion); /** * @tiapi(method=True,immutable=True,name=App.getPublisher,since=0.4) Returns the application publisher * @tiresult(for=App.getPublisher,type=string) returns the publisher */ this->SetMethod("getPublisher", &AppBinding::GetPublisher); /** * @tiapi(method=True,immutable=True,name=App.getURL,since=0.4) Returns the application url * @tiresult(for=App.getURL,type=string) returns the url for the app */ this->SetMethod("getURL", &AppBinding::GetURL); /** * @tiapi(method=True,immutable=True,name=App.getDescription,since=0.4) Returns the application description * @tiresult(for=App.getDescription,type=string) returns the description for the app */ this->SetMethod("getDescription", &AppBinding::GetDescription); /** * @tiapi(method=True,immutable=True,name=App.getCopyright,since=0.4) Returns the application copyright information * @tiresult(for=App.getCopyright,type=string) returns the copyright for the app */ this->SetMethod("getCopyright", &AppBinding::GetCopyright); /** * @tiapi(method=True,immutable=True,name=App.getGUID,since=0.2) Returns the application globally unique id * @tiresult(for=App.getGUID,type=string) returns the unique id */ this->SetMethod("getGUID", &AppBinding::GetGUID); /** * @tiapi(method=True,immutable=True,name=App.getStreamURL,since=0.4) Returns the application stream URL for the update channel * @tiresult(for=App.getStreamURL,type=string) returns the stream URL */ this->SetMethod("getStreamURL", &AppBinding::GetStreamURL); /** * @tiapi(method=True,immutable=True,name=App.appURLToPath,since=0.2) Returns the full path equivalent of an app: protocol path * @tiresult(for=App.appURLToPath,type=string) returns the path */ this->SetMethod("appURLToPath", &AppBinding::AppURLToPath); /** * @tiapi(property=True,immutable=True,type=string,name=App.path,since=0.2) Returns the full path to the application */ this->Set("path",Value::NewString(host->GetCommandLineArg(0))); /** * @tiapi(property=True,immutable=True,type=string,name=App.home,since=0.4) Returns the full path to the application home directory */ this->Set("home",Value::NewString(host->GetApplicationHomePath())); /** * @tiapi(property=True,immutable=True,type=string,name=App.version,since=0.2) The Titanium product version */ SharedValue version = Value::NewString(STRING(PRODUCT_VERSION)); global->Set("version", version); /** * @tiapi(property=True,immutable=True,type=string,name=App.platform,since=0.2) The Titanium platform */ SharedValue platform = Value::NewString(host->GetPlatform()); global->Set("platform",platform); // skip the first argument which is the filepath to the // executable SharedKList argList = new StaticBoundList(); for (int i = 1; i < Host::GetInstance()->GetCommandLineArgCount(); i++) { argList->Append(Value::NewString(Host::GetInstance()->GetCommandLineArg(i))); } SharedValue arguments = Value::NewList(argList); /** * @tiapi(property=True,immutable=True,type=list,name=App.arguments,since=0.2) The command line arguments */ Set("arguments", arguments); /** * @tiapi(method=True,immutable=True,name=App.exit,since=0.2) Exits the application */ this->SetMethod("exit",&AppBinding::Exit); /** * @tiapi(method=True,name=App.loadProperties,since=0.2) Loads a properties list from a file path * @tiarg(for=App.loadProperties,type=string,name=path) path to properties file * @tiresult(for=App.loadProperties,type=list) returns the properties as a list */ this->SetMethod("loadProperties", &AppBinding::LoadProperties); /** * @tiapi(method=True,name=App.stdout,since=0.4) Writes to stdout * @tiarg(for=App.stdout,type=string,name=data) data to write */ this->SetMethod("stdout", &AppBinding::StdOut); /** * @tiapi(method=True,name=App.stderr,since=0.4) Writes to stderr * @tiarg(for=App.stderr,type=string,name=data) data to write */ this->SetMethod("stderr", &AppBinding::StdErr); /** * @tiapi(method=True,name=App.getSystemProperties,since=0.4) get the system properties defined in tiapp.xml * @tiresult(for=App.getSystemProperties,type=Properties) returns the system properties object (see Titanium.App.Properties) */ this->SetMethod("getSystemProperties", &AppBinding::GetSystemProperties); /** * @tiapi(method=True,name=App.getIcon,since=0.4) Returns the application icon * @tiresult(for=App.getIcon,type=string) returns the icon path */ this->SetMethod("getIcon", &AppBinding::GetIcon); }
void GtkUserWindow::Open() { if (this->gtk_window == NULL) { WebKitWebView* web_view = WEBKIT_WEB_VIEW (webkit_web_view_new ()); g_signal_connect( G_OBJECT(web_view), "window-object-cleared", G_CALLBACK(window_object_cleared_cb), this); g_signal_connect( G_OBJECT(web_view), "navigation-requested", G_CALLBACK(navigation_requested_cb), this); g_signal_connect( G_OBJECT(web_view), "new-window-navigation-requested", G_CALLBACK(new_window_navigation_requested_cb), this); g_signal_connect( G_OBJECT(web_view), "populate-popup", G_CALLBACK(populate_popup_cb), this); g_signal_connect( G_OBJECT(web_view), "load-finished", G_CALLBACK(load_finished_cb), this); // Tell Titanium what Webkit is using for a user-agent SharedKObject global = host->GetGlobalObject(); if (global->Get("userAgent")->IsUndefined()) { gchar* user_agent = webkit_web_view_get_user_agent(G_OBJECT(web_view)); global->Set("userAgent", Value::NewString(user_agent)); g_free(user_agent); } WebKitWebSettings* settings = webkit_web_settings_new(); g_object_set(G_OBJECT(settings), "enable-developer-extras", TRUE, NULL); webkit_web_view_set_settings(WEBKIT_WEB_VIEW(web_view), settings); GtkWidget* view_container = NULL; if (this->IsUsingScrollbars()) { /* web view scroller */ GtkWidget* scrolled_window = gtk_scrolled_window_new (NULL, NULL); gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW(scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_container_add( GTK_CONTAINER (scrolled_window), GTK_WIDGET (web_view)); view_container = scrolled_window; } else // No scrollin' fer ya. { view_container = GTK_WIDGET(web_view); } /* main window vbox */ this->vbox = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX (vbox), GTK_WIDGET(view_container), TRUE, TRUE, 0); /* main window */ GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_set_name(window, this->config->GetTitle().c_str()); gtk_window_set_title(GTK_WINDOW(window), this->config->GetTitle().c_str()); this->destroy_cb_id = g_signal_connect( G_OBJECT(window), "destroy", G_CALLBACK(destroy_cb), this); g_signal_connect(G_OBJECT(window), "event", G_CALLBACK(event_cb), this); gtk_container_add(GTK_CONTAINER (window), vbox); webkit_web_view_register_url_scheme_as_local("app"); webkit_web_view_register_url_scheme_as_local("ti"); this->gtk_window = GTK_WINDOW(window); this->web_view = web_view; //this->SetupTransparency(); gtk_widget_realize(window); this->SetupDecorations(); this->SetupSize(); this->SetupSizeLimits(); this->SetupPosition(); this->SetupMenu(); this->SetupIcon(); this->SetTopMost(config->IsTopMost()); this->SetCloseable(config->IsCloseable()); gtk_widget_grab_focus(GTK_WIDGET (web_view)); webkit_web_view_open(web_view, this->config->GetURL().c_str()); if (this->IsVisible()) { gtk_widget_show_all(window); } if (this->config->IsFullScreen()) { gtk_window_fullscreen(this->gtk_window); } UserWindow::Open(); this->FireEvent(OPENED); } else { this->Show(); } }
void UserWindow::RegisterJSContext(JSGlobalContextRef context) { JSObjectRef global_object = JSContextGetGlobalObject(context); KJSUtil::RegisterGlobalContext(global_object, context); KJSUtil::ProtectGlobalContext(context); // Produce a delegating object to represent the top-level // Titanium object. When a property isn't found in this object // it will look for it in global_tibo. SharedKObject global_tibo = this->host->GetGlobalObject(); KObject* ti_object = new DelegateStaticBoundObject(global_tibo); SharedKObject shared_ti_obj = SharedKObject(ti_object); SharedValue ui_api_value = ti_object->Get("UI"); if (ui_api_value->IsObject()) { // Create a delegate object for the UI API. SharedKObject ui_api = ui_api_value->ToObject(); KObject* delegate_ui_api = new DelegateStaticBoundObject(ui_api); // Place currentWindow in the delegate. SharedValue user_window_val = Value::NewObject(this->GetSharedPtr()); delegate_ui_api->Set("currentWindow", user_window_val); delegate_ui_api->Set("getCurrentWindow", this->Get("getCurrentWindow")); // Place currentWindow.createWindow in the delegate. SharedValue create_window_value = this->Get("createWindow"); delegate_ui_api->Set("createWindow", create_window_value); // Place currentWindow.openFiles in the delegate. delegate_ui_api->Set("openFileChooserDialog", this->Get("openFileChooserDialog")); delegate_ui_api->Set("openFolderChooserDialog", this->Get("openFolderChooserDialog")); delegate_ui_api->Set("openSaveAsDialog", this->Get("openSaveAsDialog")); ti_object->Set("UI", Value::NewObject(delegate_ui_api)); } else { std::cerr << "Could not find UI API point!" << std::endl; } // Get the global object into a KKJSObject SharedKObject frame_global = new KKJSObject(context, global_object); // Copy the document and window properties to the Titanium object SharedValue doc_value = frame_global->Get("document"); ti_object->Set("document", doc_value); SharedValue window_value = frame_global->Get("window"); ti_object->Set("window", window_value); // Place the Titanium object into the window's global object SharedValue ti_object_value = Value::NewObject(shared_ti_obj); frame_global->Set(GLOBAL_NS_VARNAME, ti_object_value); // bind the window into currentWindow so you can call things like // Titanium.UI.currentWindow.getParent().window to get the parents // window and global variable scope this->Set("window", window_value); SharedKObject event = new StaticBoundObject(); event->Set("scope", Value::NewObject(frame_global)); this->FireEvent(INIT, event); }