mircobabini
1/15/2015 - 4:07 PM

IntelXDK (6121) fix for running third-party plugins in Emulation Mode

IntelXDK (6121) fix for running third-party plugins in Emulation Mode

/**
 * @license Copyright 2013 - 2014 Intel Corporation All Rights Reserved.
 *
 * The source code, information and material ("Material") contained herein is owned by Intel Corporation or its
 * suppliers or licensors, and title to such Material remains with Intel Corporation or its suppliers or
 * licensors. The Material contains proprietary information of Intel or its suppliers and licensors. The
 * Material is protected by worldwide copyright laws and treaty provisions. No part of the Material may be used,
 * copied, reproduced, modified, published, uploaded, posted, transmitted, distributed or disclosed in any way
 * without Intel's prior express written permission. No license under any patent, copyright or other intellectual
 * property rights in the Material is granted to or conferred upon you, either expressly, by implication,
 * inducement, estoppel or otherwise. Any license under such intellectual property rights must be express and
 * approved by Intel in writing.
 *
 * Unless otherwise agreed by Intel in writing, you may not remove or alter this notice or any other notice
 * embedded in Materials by Intel or Intel's suppliers or licensors in any way.
 */
define(["q"],function(e){function t(){return e()}function n(e){return E=new N(e.fullName),x.getPluginsCacheDir().then(function(e){c(e)}).fail(function(e){throw E.error("[cordova] retrieving plugins cache dir failed "+JSON.stringify(e)),new C({message:e.message,stackTrace:e.stack,componentName:"client:cordova",code:4})})}function r(e){var t,n=[];for(t=0;t<e.length;t+=1)n.push(e[t]);return n}function i(){var e=xdk.require("client:settings-db"),t=e.getSetting(e.Scope.global,"emulator","ripple");if(t){var n=t["tinyhippos-device-key"];if(n){var r=n.value;if("Droid2"===r||"GalaxyS"===r||"GalaxyTab2"===r||"Incredible"===r||"Nexus4"===r||"Nexus7"===r||"NookColor"===r||"Razr"===r||"LenovoK900"===r)return"android";if("iPad"===r||"iPhone3GS"===r||"iPhone4"===r||"iPhone5"===r||"iPhone6"===r)return"ios";if("Satellite"===r||"SurfacePro"===r||"Yoga"===r)return"windows";if("NokiaLumina920"===r)return"wp8"}}return null}function s(){S=xdk.require("client:project-manager"),S.onProjectOpened().listen(w);var e=S.getCurrentProject();null!==e&&(_||(_=e.onPluginReferencesChanged(),_.listen(y)))}function o(e){var t,n=r(e.getPlugins());for(t=0;t<n.length;t+=1){var i=n[t];if(i.getSelectedState()!==S.pluginSelectedStateEnum.XDK_PLUGIN_EXPLICITLY_EXCLUDED&&!i.isBuiltin())return!0}return!1}function u(t){var n,r,i=T.toBracketsName(t.getRootDirectory());return t.getSessionScratchDirectory().then(function(e){e=T.toBracketsName(e),r=e+"/platforms",n=o(t)?i+"/"+t.getCordovaPluginsDirectory():e+"/"+t.getCordovaPluginsDirectory();var s={rootDir:i,name:t.getName(),srcDir:t.getSourceDirectory(),pluginsDir:n,platformsDir:r};return s}).fail(function(t){return E.error("[cordova] serializing xdk project to cordova project failed "+JSON.stringify(t)),xdk.require("client:dialog-box").alert("Intel XDK failed to locate the scratch directory. Click Dismiss to continue."),e.reject(new Error("project manager failed to locate scratch folder."))})}function a(e){var t;for(t=0;t<M.length;t+=1){var n=M[t];if(n.id===e)return"both_matched"}return"id_unmatched"}function f(e){var t=k.readFileSync(e,"utf-8").replace("","");return new O.ElementTree(O.XML(t))}function l(e){var t=T.toBracketsName(e.getRootDirectory()),n=t+"/"+e.getCordovaPluginsDirectory();try{return k.readdirSync(n)}catch(r){return[]}}function c(e){var t,n=k.readdirSync(e);for(t=0;t<n.length;t+=1){var r=n[t],i=A.join(e,r,"plugin.xml"),s=f(i),o=s.getroot(),u=s.find("repo");M[t]={id:o.attrib.id,version:o.attrib.version,url:u?u.text:"",sourceLocation:A.join(e,r)}}}function h(){return 0===M.length&&c(),M}function p(e,t){var n,r=T.toBracketsName(e.getRootDirectory()),i=A.join(r,e.getCordovaPluginsDirectory(),t,"plugin.xml");try{n=f(i)}catch(s){return{}}var o=n.getroot(),u=n.find("repo"),a=n.find("name"),l=n.find("description"),c=n.find("issue"),h={id:o.attrib.id,version:o.attrib.version,name:a?a.text:"",description:l?l.text:"",url:u?u.text:"",issue:c?c.text:""};return h}function d(e){var t,n=r(e.getPlugins());for(t=0;t<n.length;t+=1){var i=n[t];if(i.getSelectedState()!=S.pluginSelectedStateEnum.XDK_PLUGIN_EXPLICITLY_EXCLUDED&&(!i.isIntel()||"com.intel.security"===i.getId()))return!0}return!1}function v(e,t,n){var r,i=xdk.require("client:cordova-registry"),s=[],o=n.pluginsDir;if(t.forEach(function(t){if(t.getSelectedState()!==S.pluginSelectedStateEnum.XDK_PLUGIN_EXPLICITLY_EXCLUDED){var o=t.getPlugin();if(!t.isIntel()||t.isFeatured()){if(r=o.getId(),"add"===e&&!o.inRegistry()&&(r=o.getOrigin(),o.getOriginType()===i.pluginOrigins.XDK_PLUGIN_ORIGIN_LOCAL)){var u=n.rootDir+"/";n.srcDir&&(u+=n.srcDir+"/"),r=u+r}console.log("[cordova] ",r);var a=t.getParameterValues();a&&(n.cli_variables=a),"org.apache.cordova.file"===o.getId()?s.unshift(r):s.push(r)}}}),!k.existsSync(o))throw new Error("PLUGINS directory should have been created. ");return x.plugin(e,s,n)}function m(t,n){var i,s=xdk.require("client:emulator"),o=xdk.require("client:dialog-box").loader({title:"Cordova preparing sources ...."}),a=!1;return s.isShown()&&(a=s.hasFocus(),o.show()),u(t).then(function(e){return i=e,x.platform("add",n,i)}).then(function(){var e=r(t.getPlugins());return v("add",e,i)}).then(function(){return i.platforms=[n],i.options=[],i.verbose=!1,i.silent=!0,x.prepare(i)}).then(function(){return i}).fail(function(t){var n;switch(t.getCode()){case 1:n="'cordova prepare'.</br>";break;case 2:n="'cordova plugin add'.</br>";break;case 3:n="'cordova plugin remove'.</br>";break;case 4:n="'cordova platform add'.</br>";break;default:throw new Error("unknown error code from Cordova Server")}return xdk.require("client:dialog-box").alert("Intel XDK failed to perform "+n+t.getMessage()+".</br>Click Dismiss to continue."),E.error("[cordova] prepare failed "+JSON.stringify(t)),e.reject(t)}).fin(function(){o.dismiss(),a&&s.foc()})}function g(t,n){var r,i,s;return E.log("[cordova] fetching custom plugin from "+n),u(t).then(function(e){return r=e,i=!o(t),i&&(s=r.pluginsDir,r.pluginsDir=r.rootDir+"/"+t.getCordovaPluginsDirectory(),b(s,r.pluginsDir)),x.plugin("add",n,r)}).fail(function(t){return E.log("[cordova] error in custom plugin add: "+JSON.stringify(t)),e.reject(t)})}function y(t,n,s){var f,c,h=n.getPlugin(),p=h.getId(),d=xdk.require("client:cordova-registry");if(E.log("[cordova] caught changeofPlugins signal for "+p),s!==S.projectSignalOperationEnum.XDK_SIGNAL_DATA_UPDATED&&s!==S.projectSignalOperationEnum.XDK_SIGNAL_VERSION_UPDATED&&s!==S.projectSignalOperationEnum.XDK_SIGNAL_VARIABLE_UPDATED&&(!n.isIntel()&&!n.isFeatured()||"com.intel.security"===p)){if(s===S.projectSignalOperationEnum.XDK_SIGNAL_ADDED?f="add":s===S.projectSignalOperationEnum.XDK_SIGNAL_REMOVED?f="rm":s===S.projectSignalOperationEnum.XDK_SIGNAL_VERSION_UPDATED?f="update_version":s===S.projectSignalOperationEnum.XDK_SIGNAL_VARIABLE_UPDATED&&(f="update_variable"),"rm"!==f&&!h.inRegistry()&&(p=h.getOrigin(),h.getOriginType()===d.pluginOrigins.XDK_PLUGIN_ORIGIN_LOCAL)){var m=T.toBracketsName(t.getRootDirectory()),g=t.getSourceDirectory(),y=m+"/";g&&(y+=g+"/"),p=y+p}return u(t).then(function(s){if(c=s,!k.existsSync(c.platformsDir)){try{k.mkdirSync(c.platformsDir),k.mkdirSync(c.pluginsDir)}catch(u){return xdk.require("client:dialog-box").alert("Intel XDK failed to locate the scratch directory. Click Dismiss to continue."),e.reject(new Error("project manager failed to locate scratch folder."))}var d=i();if(d){var m=r(t.getPlugins());x.platform("add",d,c).then(function(){v("add",m,c)}).fail(function(e){throw E.error("[cordova] cordova platform add failed: "+JSON.stringify(e)),e}).fin(function(){})}}var g=c.rootDir+"/"+t.getCordovaPluginsDirectory(),y=a(n.getId(),n.getVersion());if("both_matched"!==y)if("rm"!==f||o(t)){if("rm"!==f){var w=l(t);0===w.length&&(g=c.platformsDir.replace("platforms",t.getCordovaPluginsDirectory()),b(g,c.pluginsDir))}}else b(g,c.pluginsDir);return"update_version"===f?("both_matched"!==y||o(t)||b(g,c.pluginsDir),x.plugin("rm",h.getId(),c).then(function(){return x.plugin("add",p,c)})):"update_variable"===f?x.plugin("rm",h.getId(),c).then(function(){return x.plugin("add",p,c)}):x.plugin(f,p,c)}).fail(function(e){E.log("[cordova] error in plugin "+f+": "+e.message_)})}}function b(e,t){e!==t&&(E.log("[cordova] migrating from ",e," to ",t),k.existsSync(t)&&L.rm("-rf",t),L.cp("-rf",e+"/*",t),L.rm("-rf",e))}function w(e){if(E.log("[cordova] caught project open/create signal"),_||(_=e.onPluginReferencesChanged(),_.listen(y)),d(e)){var t=i();if(t)return m(e,t)}}var E,S,x=xdk.require("server:cordova-lib"),T=xdk.require("core:userfs-name-converter"),N=xdk.require("core:logger"),C=xdk.require("core:component-error"),k=require("fs"),L=require("shelljs"),A=require("path"),O=require("elementtree"),M=[],_=null;return{init:n,start:s,isCordova3Project:d,serializeProjectObject:u,isCustomPluginSelected:o,getCustomPluginIds:l,getPluginInfo:h,getCustomPluginInfo:p,fetchCustomPlugin:g,prepare:m,getNewQ:t}})
.importForm input[type=text]{display:inline-block;border-radius:5px;border:1px solid rgba(0,0,0,0);height:30px;line-height:30px;padding-left:10px;overflow:hidden;color:#525252;font-size:13px;width:70%}.importForm input.blankDirectory:empty::-webkit-input-placeholder::after{color:#fff;font-style:italic!important}.importForm a.directoryPickerButton::after{content:'<<Browse>>';text-transform:none}.importForm .directoryPicker{display:none}.importForm{margin:40px 0 0}.external .disclaimer{border-bottom:1px solid #555;background:url(../components/client/projects-tab/img/alert.png) no-repeat;background-size:2em;padding:0 1em 1em 2.5em;margin-top:1em;color:#999}.disclaimer strong{color:#FDB813}.external .actions{margin-top:.5em}.external .actions .message{display:inline-block;border-right:1px solid #555;padding-right:8px;margin-right:8px;font-weight:600}.external .actions>.xdkButton{text-transform:none}.external .actions>.localImport::after{content:'<<Import Local Plugin>>'}.external .actions>.webImport::after{content:'<<Get Plugin from the Web>>'}.external .noThirdParty{color:#999;font-style:italic;padding:.5em 0}.external .thirdParty{overflow:overlay;flex:1 1 50%;padding:.5em 0}.external .thirdParty header{-webkit-column-span:all}.external .thirdParty content{overflow-y:overlay;margin:0;display:block;-webkit-column-count:2;padding-top:.5em}.external .thirdParty content .plugin.row{background-color:#585353;display:flex;flex-flow:row nowrap;width:100%;margin:.6em .3em;padding:.25em;-webkit-column-break-inside:avoid}.external .thirdParty content .plugin.row:first-of-type{margin-top:0}.external .thirdParty content .plugin.row>*{display:inline-block;flex-grow:0;flex-shrink:0}.external .thirdParty content .plugin.row>.name{flex-grow:1}.external .thirdParty content .plugin.row .edit{display:flex;flex-flow:row nowrap}.external .thirdParty content .plugin.row>.icon{display:none}.external .thirdParty content .plugin.row:hover>.icon{display:inline-block}.external .verticalLine{border-left:thick solid #585353}.external.collapsible{flex-flow:column nowrap}.external.collapsible>.collapsible-wrapper{display:flex;flex-flow:row wrap;font-size:13px}.external .actions .info{white-space:nowrap}.external.collapsible>.collapsible-wrapper>div{padding:.5em 0;margin:0 1em}.external.collapsible>.collapsible-wrapper>div>.actions{display:flex;flex-flow:row wrap;justify-content:flex-start;align-items:center;align-content:flex-start}.external.collapsible>.collapsible-wrapper>div>.actions>div{flex:0 0 auto}.external.collapsible>.collapsible-wrapper>div>.actions>a.externalLink{flex:1 0 auto;text-align:end;padding:.25em}#localImport,#webImport{position:relative}a.externalLink{color:#00ADEE}#localImport a.externalLink{position:absolute;bottom:calc(-2em - 30px);left:0}#webImport a.externalLink{position:absolute;bottom:calc(-2.5em - 20px);left:0}input::-webkit-input-placeholder{font-style:italic}.importForm .parameter{display:flex;flex-flow:row nowrap;align-content:flex-start;align-items:center;justify-content:flex-start}.importForm .parameter.origin{opacity:0}.importForm .parameter.origin.visible{opacity:1}.importForm .parameter>*{padding:.25em;margin:.7em .3em .7em 0}.importForm .parameter>label{flex-grow:0;flex-grow:0;text-align:end;flex-basis:25%;max-width:165px}.importForm .parameter>.xdkInput{flex-grow:0;flex-shrink:1;flex-basis:60%}#localImport .importForm .parameter:last-of-type>.xdkInput{flex-basis:50%}#localImport .importForm .parameter:last-of-type>.xdkButton{flex-grow:0;flex-shrink:0;flex-basis:10%;margin:.7em 0 .7em .3em}.importForm .parameter>.xdkSelects.isRepo+label{white-space:nowrap}.importForm .parameter>select.xdkInput{flex-basis:initial}.autoImport::after{content:'Autoload'}
/*
 * @license Copyright(C) 2014 - 2014 Intel Corporation.  All Rights Reserved.
 *
 * The source code, information and material ("Material") contained herein is
 * owned by Intel Corporation or its suppliers or licensors, and title to such
 * Material remains with Intel Corporation or its suppliers or licensors. The
 * Material contains proprietary information of Intel or its suppliers and
 * licensors. The Material is protected by worldwide copyright laws and treaty
 * provisions. No part of the Material may be used, copied, reproduced,
 * modified, published, uploaded, posted, transmitted, distributed or disclosed
 * in any way without Intel's prior express written permission. No license under
 * any patent, copyright or other intellectual property rights in the Material
 * is granted to or conferred upon you, either expressly, by implication,
 * inducement, estoppel or otherwise. Any license under such intellectual
 * property rights must be express and approved by Intel in writing.
 *
 * Unless otherwise agreed by Intel in writing, you may not remove or alter this
 * notice or any other notice embedded in Materials by Intel or Intel's
 * suppliers or licensors in any way.
 */
define(["jquery","underscore","backbone","../projects-utils","text!./jsapp-plugins-import.tmpl","text!./jsapp-plugins-import-dialog.tmpl"],function(e,t,n,r,i,s){function o(e,t){var n=xdk.require("client:dialog-box");return new n({title:t,details:e,buttons:[{text:l("Cancel"),id:"cancel",style:"grey"},{text:l("Import"),id:"import",key:"enter"}],width:700,theme:"dark"})}function u(e){var t=e.getMessage?e.getMessage():e;window.parent.xdk.require("client:dialog-box").alert({title:l("Oops!  An error occured."),details:t})}var a=xdk.require("core:i18n-support"),f=xdk.require("core:analytics"),l=a.getComponentLocalization("client:projects-tab"),c=n.View.extend({CordovaReg:null,PM:null,userfsNC:null,externalLinks:null,template:t.template(l(i)),events:{"click .autoImport":"autoImport","click .localImport":"import","click .webImport":"import","click .remove":"removeThirdParty"},autoImport:function(){var e=this;e.initialize();e.PM=xdk.require("client:project-manager");e.userfsNC=xdk.require("core:userfs-name-converter");var n=e.model.getSourceDirectory()?"/"+e.model.getSourceDirectory():"";var r=e.userfsNC.toNativeName(e.model.getRootDirectory()+n);var i=r+"/plugins/";var s=require("fs");var o=require("path");s.readdir(i,function(n,u){u=u.filter(function(e){return e.indexOf(".DS_Store")==-1&&s.existsSync(o.join(i,e))&&s.statSync(o.join(i,e)).isDirectory()});t.each(e.model.getPlugins(),function(n){if(!n.isBuiltin()&&!n.isFeatured()){if(!t.contains(u,n.getId())){e.model.removePlugin(n)}}});t.each(u,function(t){var n=e.model.getPluginsById(t);if(n.length===0){var s=Object.create(e.CordovaReg.PluginPrototype);s.name_=t;s.ID_=t;var o=i+t;s.origin_=e.getRelPath(o,r);s.originType_=e.CordovaReg.pluginOrigins.XDK_PLUGIN_ORIGIN_LOCAL;e.model.addPlugin(s,"",e.PM.pluginSelectedStateEnum.XDK_PLUGIN_EXPLICITLY_INCLUDED)}})})},"import":function(n){var i=this,a=e(n.target).hasClass("localImport"),c=a?"#localImport":"#webImport",h=i.model.getSourceDirectory()?"/"+i.model.getSourceDirectory():"",p=i.userfsNC.toNativeName(i.model.getRootDirectory()+h),d=e(t.template(l(s),{workingDir:p}).replace(/\n/g,"")).find(c);i.externalLinks.activate(d);var v=l(a?"Add a Cordova Plugin from a folder":"Add a Cordova Plugin from the web");a?(d.find(".directoryPickerButton").on("click",r.triggerDirectoryPicker),d.find(".directoryPicker").on("change",{workingDir:p},i.chooseLocalDirectory)):d.find(".isRepo").on("change",i.showOrigin),o(d,v).show().then(function(e){if("import"===e.id){var t=Object.create(i.CordovaReg.PluginPrototype),n=!0;t.name_=d.find(".name").val(),t.ID_=d.find(".ID").val();var r=d.find(".labeldir").val();return a||(n=!d.find(".isRepo").is(":checked")),t.origin_=a?i.getRelPath(r,p):n?r:t.ID_,""===(t.name_&&t.ID_&&t.origin_)?void u(l("Please enter all information.")):(t.originType_=a?i.CordovaReg.pluginOrigins.XDK_PLUGIN_ORIGIN_LOCAL:n?i.CordovaReg.pluginOrigins.XDK_PLUGIN_ORIGIN_REPO:i.CordovaReg.pluginOrigins.XDK_PLUGIN_ORIGIN_CORDOVA_IO,i.model.addPlugin(t,"",i.PM.pluginSelectedStateEnum.XDK_PLUGIN_EXPLICITLY_INCLUDED),void f.sendEvent("projectManagement:CordovaPlugin","IMPORT_3RDPARTY_"+(a?"LOCAL":"CORDOVA_REPO"),t.ID_))}}).fail(function(e){u(e)}).done()},removeThirdParty:function(t){var n=this,r=e(t.target).closest(".plugin.row"),i=r.attr("data-plugin-id"),s=n.model.getPluginsById(i)[0];s&&(n.model.removePlugin(s),n.render(),f.sendEvent("projectManagement:CordovaPlugin","REMOVED_3RDPARTY",i))},showOrigin:function(){e(this).closest(".importForm").find(".origin").toggleClass("visible",!e(this).is(":checked"))},chooseLocalDirectory:function(t){var n=e(t.target).val();return n===t.data.workingDir?void u(l("Invalid directory choosen. You may not choose the project source directory as the plugin source directory. Please create a new plugin source directory within this directory.")):0!==n.indexOf(t.data.workingDir)?void u(l("Please choose a path within the project directory")):void r.updateDirectoryPickerImport(t)},getRelPath:function(e,t){var n=this.userfsNC.toUserfsName(e),r=this.userfsNC.toUserfsName(t);return n.replace(r,"").replace("/","")},pluginsChanged:function(){var e=this;e.render()},initialize:function(){var e=this;e.CordovaReg=xdk.require("client:cordova-registry"),e.PM=xdk.require("client:project-manager"),e.userfsNC=xdk.require("core:userfs-name-converter"),e.externalLinks=xdk.require("client:external-links"),e.model&&e.model.onPluginReferencesChanged().listen(function(t,n,r){e.pluginsChanged(t,n,r)})},render:function(){var e=this,n=[];t.each(e.model.getPlugins(),function(e){e.isBuiltin()||e.isFeatured()||n.push({id:e.getId(),name:e.getVisibleName(),version:e.getVersion(),state:!0,plugin:e})}),e.$el.empty().append(e.template({extra:n})),e.externalLinks.activate(e.$el)}}),h={createPluginImport:function(e){var t=new c({model:e});return t.render(),t}};return h})
    <div class = "actions">
        <div class ="message"><<Add a Third-Party Plugin >></div>
        <div class="xdkButton blue autoImport"></div>
        <div class="xdkButton blue localImport"></div>
        <div class="xdkButton blue webImport"></div>
        <a href = "<<http://plugins.cordova.io/#/>>" class="externalLink info" style="float:right">><<Explore the Apache Cordova Plugins Registry>></a>
    </div>
    <div class = "disclaimer"><<<strong>IMPORTANT: </strong> The Emulator and App Preview (on-device-testing) will not work with 3rd-party plugins (yet!).  These plugins were created and are supported by third-parties.  Please be sure to read each plugin's documentation and license prior to uploading and using them.>>
    </div>
<% if (extra.length > 0) { %>
    <div class = "thirdParty">
        <header><<Imported Plugins:>></header>
        <content>
<% _.each(extra, function(item,ind) { %>
            <div class="plugin row" data-ind="<%=ind%>" data-plugin-id="<%-item.id%>" data-plugin-version="<%-item.version%>">
                <label class="name"><%-item.name%></label>
                <div class="version"><%-item.version%></div>
                <span class="icon circle remove"></span>
            </div>
<% }); %>
        </content>
    </div>
<% } else { %>
    <div class="noThirdParty"><<You have not specified any third-party plugins for this project. >></div>
<% } %>