(function(Pitaya, window) { "use strict"; // Load dependencies var path = require('path'); var fs = require('fs'); var Handlebars = require('handlebars'); var cp = require("child_process"); var gui = require('nw.gui'); var minimist = require('minimist'); // Load templates var itemsListTpl = Handlebars.compile(Pitaya.DOM.select('#items-list-tpl').innerHTML); // Internal constants var DEFAULT_PROFILE = './default-profile.json'; /** * Start the app * * @param rootEl The application root element selector * @return Pitaya */ Pitaya.start = function(rootEl) { Pitaya._opts = minimist(gui.App.argv); Pitaya._rootEl = Pitaya.DOM.select(rootEl); Pitaya._initListeners(); var profilePath = Pitaya._opts.profile || DEFAULT_PROFILE; return Pitaya.loadProfile(profilePath) .then(function() { return Pitaya; }) ; }; /** * Load a profile file and render the application * * @param profilePath The path of the profile file * @return Promise */ Pitaya.loadProfile = function(profilePath) { return Pitaya._loadJSONFile(profilePath) .then(function(profile) { Pitaya._profile = profile; Pitaya.render(); return profile; }) ; }; /** * Update the application view * * @return Pitaya */ Pitaya.render = function() { var rootEl = Pitaya._rootEl; var profile = Pitaya._profile; rootEl.innerHTML = itemsListTpl(profile); }; /** * Initialize DOM event listeners * @private */ Pitaya._initListeners = function() { var rootEl = Pitaya._rootEl; rootEl.addEventListener('click', Pitaya._onItemClick); }; /** * App item click handler * @private */ Pitaya._onItemClick = function(evt) { var appItemEl = evt.srcElement.matches( '.app-item') ? evt.srcElement : Pitaya.DOM.getClosestAncestor(evt.srcElement, '.app-item') ; if( !appItemEl ) return; var execPath = appItemEl.dataset.exec; console.info('Launching application "'+execPath+'"...'); if(execPath) { appItemEl.classList.add('loading'); cp.exec(execPath, function(err) { appItemEl.classList.remove('loading'); if(err) return console.error(err.stack || err); console.info('Application closed "'+execPath+'".'); }); } }; /** * Load a JSON file * * @private * @param filePath The path of the json file * @return Promise */ Pitaya._loadJSONFile = function(filePath) { return new Promise(function(resolve, reject) { fs.readFile(filePath, 'utf8', function(err, fileContent) { if(err) return reject(err); try { var json = JSON.parse(fileContent); return resolve(json); } catch(err) { return reject(err); } }); }); }; }(window.Pitaya = window.Pitaya || {}, window));