示例#1
0
文件: main.js 项目: Jicheng-Yan/rodeo
    mainWindow.webContents.on('did-finish-load', function() {
      // keep track of the app version the user is on. this is convenient for
      // reporting bugs
      var rc = preferences.getPreferences();
      var isFirstRun = false;
      if (rc.version==null) {
        isFirstRun = true;
        preferences.setPreferences('version', app.getVersion());
        mainWindow.webContents.send('prompt-for-sticker');
      }
      if (rc.version && rc.version != app.getVersion() && ! rc.email) {
        preferences.setPreferences('version', app.getVersion());
        if (! rc.email) {
          mainWindow.webContents.send('prompt-for-sticker');
        }
      }

      createPythonKernel(rc.pythonCmd, isFirstRun, mainWindow);
      var wd;
      if (process.argv.length == 5) {
        wd = process.argv[4];
        USER_WD = wd;
      }
      if (wd) {
        mainWindow.webContents.send('log', "[INFO]: working directory passed as argument: `" + wd + "`");
        if (! fs.existsSync(wd)) {
          console.log("[ERROR]: directory `" + wd + "` does not exist");
          return;
        }
        mainWindow.webContents.send('set-wd', wd);
      }
    });
示例#2
0
      return request.send(options).then(function(response){
        if(!response) throw new Error('Having issues with getting manifest file.');
        if(!response.raw_body) throw new Error('Having issues with getting manifest file raw body.');

        var remoteManifestJSON = JSON.parse(response.raw_body);
        //console.log('Latest online version is: ', remoteManifestJSON.version);
        //console.log('Current app version is: ', app.getVersion());

        if(semver.lt(app.getVersion(), remoteManifestJSON.version)){
          //console.log('Update is available.');

          return downloadUpdate(remoteManifestJSON.updates.linkToLatest, true)
          .then(function(destination){
            return applyUpdate(destination);
          })
          .then(function(){
            //console.log('update is applied');
          })
          .catch(function(error){
            //console.log('Update was not applied.');
            //console.log(error);
          });
        }

        //console.log('Already running at the latest version');
      }).catch(function(err){
示例#3
0
文件: main.js 项目: MSylvia/fireball
 AutoUpdater.on('checking-for-update', function() {
     status = 'checking';
     Fire.log("Checking for update, current version: " + App.getVersion());
     plugin.sendToPanel('default', 'auto-updater:status-changed', {
         status: status
     });
 });
示例#4
0
function getMenuTemplate() {
  var template = [{
    label: 'Suunto Dive Manager',
    submenu: [
      { label: 'Backup Database', click: backup.runBack },
      { label: 'Open Database Folder', click: backup.openFolder },
    ]}
  ];

  if (process.platform == 'darwin') {
    var name = require('app').getName();
    template.unshift({
      label: name,
      submenu: [
        { label: 'About ' + name, role: 'about' },
        { label: 'Version ' + app.getVersion(), enabled: false },
        { label: 'Check for Update', click: autoUpdate.checkForUpdates },
        { label: 'Install Update', click: autoUpdate.quitAndInstall, enabled: false, visible: false, id: 'install-update' },
        { type: 'separator' },
        { label: 'Services', role: 'services', submenu: [] },
        { type: 'separator' },
        { label: `Hide ${name}`, accelerator: 'Command+H', role: 'hide' },
        { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' },
        { label: 'Show All', role: 'unhide' },
        { type: 'separator' },
        { label: 'Quit', accelerator: 'Command+Q', click: function() { app.quit(); } },
      ]
    });
  }

  return template;
};
function checkUpdate(callback) {
    var app = require('app');
    var request = require('request');
    var currentVersion = app.getVersion();
    //var currentVersion = '0.1.7'; // for testing, use app.getVersion for production
    request('http://fireball-x.com/api/checkupdate?version=v' + currentVersion,
        function(err, res, body) {
        if (!err && res.statusCode === 200) {
            //console.log(body);
            var download = JSON.parse(body);
            var downloadUrl = Fire.isDarwin ? download.url : download.winurl;
            var arr = downloadUrl.split('/');
            var filename = arr[arr.length - 1];
            //TODO: insert confirmation dialog
            Fire.log('Found new version, downloading ' + filename);
            console.log(filename);
            console.log(downloadUrl);
            return callback({
                downloadUrl: downloadUrl,
                filename: filename
            });
            //downloadFireball(downloadUrl, filename);
        } else if (err) {
          console.log(err);
            return callback({error: err});
        } else if (res.statusCode === 204){
            Fire.log('You got latest Fireball, no need to update.');
            console.log("Got error: " + err);
            return callback({error: err});
        }
    });
}
示例#6
0
var showAboutDialog = function() {
  dialog.showMessageBox({
    type    : "info",
    buttons : [],
    title   : "About Parrot",
    message : "About Parrot",
    detail  : "Parrot Desktop v"  + app.getVersion() + "\nCopyright Parrot 2016",
  });
};
示例#7
0
 exports.check_updates = function () {
   var child = cp.spawn(updateDotExe, [
       "--update",
       "https://net-tsinghua.herokuapp.com/update/win32/" + app.getVersion()
     ], { detached: true });
   child.on('close', function(code) {
     console.log('Updating is done.');
   });
 };
示例#8
0
function parseArgs() {
  optimist.usage("\nLight Table " + app.getVersion() + "\n" +
                 // TODO: Use a consistent name for executables or vary executable
                 // name per platform. $0 currently gives an unwieldy name
                 "Usage: light [options] [path ...]\n\n"+
                 "Paths are either a file or a directory.\n"+
                 "Files can take a line number e.g. file:line.");
  optimist.alias('h', 'help').boolean('h').describe('h', 'Print help');
  optimist.alias('a', 'add').boolean('a').describe('a', 'Add path(s) to workspace');
  global.browserParsedArgs = optimist.parse(process.argv);

  if (global.browserParsedArgs.help) {
    optimist.showHelp();
    process.exit(0);
  }
}
示例#9
0
 return new Promise(function(resolve, reject) {
   console.log('checking for updates ...');
   var options = {
     repo: 'joeferraro/mavensmate-app',
     currentVersion: app.getVersion()
   };
   var updateChecker = new GitHubReleases(options);
   updateChecker.check()
     .then(function(updateCheckResult) {
       console.log('update check result: ', updateCheckResult);
       if (updateCheckResult && updateCheckResult.needsUpdate) {
         mainWindow.webContents.send('needsUpdate', updateCheckResult);
       }
       resolve();
     })
     .catch(function(err) {
       console.error(err);
       reject(err);
     });
 });
示例#10
0
文件: main.js 项目: Jicheng-Yan/rodeo
  function checkForUpdates(displayNoUpdate) {
    var platform = os.platform() + '_' + os.arch();
    var version = app.getVersion();
    updateUrl = "http://localhost:3000/?" + "platform=" + platform + "&version=" + version;
    updateUrl = "https://rodeo-updates.yhat.com?" + "platform=" + platform + "&version=" + version;

    autoUpdater.on('error', function(err, msg) {
      mainWindow.webContents.send('log', "[ERROR]: " + msg);
    });

    autoUpdater.on('update-available', function(data) {
      mainWindow.webContents.send('log', "UPDATE AVAILABLE");
      mainWindow.webContents.send('log', JSON.stringify(data));
    });

    autoUpdater.on('update-not-available', function(data) {
      if (displayNoUpdate==true) {
        mainWindow.webContents.send('no-update');
      }
    });

    autoUpdater.on('update-downloaded', function(evt, releaseNotes, releaseName, releaseDate, udpateURL) {
      mainWindow.webContents.send('log', releaseNotes + '---' + releaseName + '---' + releaseDate + '---' + udpateURL);
      mainWindow.webContents.send('update-ready', { platform: 'osx' });
    });

    setTimeout(function() {
      if (/win32/.test(platform)) {
        https.get(updateUrl, function(res) {
          if (res.statusCode!=204) {
            mainWindow.webContents.send('update-ready', { platform: 'windows' });
          }
        }).on('error', function(err) {
          console.error("[ERROR]: could not check for windows update.");
        });
      } else {
        autoUpdater.setFeedURL(updateUrl);
        autoUpdater.checkForUpdates();
      }
    }, 2000);
  }
示例#11
0
 exports.init_updater = function () {
   autoUpdater.on('error', function (event, message) {
     console.log(message);
   });
   autoUpdater.on('checking-for-update', function () {
     console.log('Checking for update.');
   });
   autoUpdater.on('update-available', function () {
     console.log('Update available.');
   });
   autoUpdater.on('update-not-available', function () {
     console.log('Update not available.');
   });
   autoUpdater.on('update-downloaded', function (
       event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
     console.log('Update downloaded, quit and update.');
     quitAndUpdate();
   });
   autoUpdater.setFeedUrl('https://net-tsinghua.herokuapp.com/update/osx/' +
                          app.getVersion());
 };
  mainWindow.webContents.on('did-finish-load', function() {
    mainWindow.setTitle(settings.title);
    mainWindow.show();
    mainWindow.focus();

    if (openURL) {
      mainWindow.webContents.send('application:open-url', {
        url: openURL
      });
    }
    app.on('open-url', function (event, url) {
      event.preventDefault();
      mainWindow.webContents.send('application:open-url', {
        url: url
      });
    });

    if (process.env.NODE_ENV !== 'development' && settings.autoUpdater.enabled) {
      var feedUrl = settings.feedUrl.replace('[version]', app.getVersion()).replace('[beta]', !!settings.beta);
      autoUpdater.setFeedUrl(feedUrl);
    }
  });
示例#13
0
var parseCommandLine = function parseCommandLine() {
    var version = app.getVersion();

    var yargs = require('yargs')
        .alias('d', 'dev').boolean('d').describe('d', 'Run in development mode.')
        .alias('h', 'help').boolean('h').describe('h', 'Print this usage message.')
        .alias('l', 'log-file').string('l').describe('l', 'Log all output to file.')
        .alias('t', 'test').boolean('t').describe('t', 'Run the specified specs and exit with error code on failures.')
        .alias('v', 'version').boolean('v').describe('v', 'Print the version');

    var args = yargs.parse(process.argv.slice(1));

    process.stdout.write(`${JSON.stringify(args)}\n`);

    if (args.help) {
        var help = "";
        yargs.showHelp(helpString => help += helpString);
        process.stdout.write(`${help}\n`);
        proces.exit(0);
    }

    if (args.version) {
        process.stdout.write(`${version}\n`);
        process.exit(0);
    }

    var devMode = args['dev'];
    var test = args['test'];
    var exitWhenDone = test;
    var logFile = args['log-file'];

    return {
        devMode,
        test,
        exitWhenDone,
        logFile
    };
};
示例#14
0
var BrowserWindow = require('browser-window');
var env = require('./vendor/electron_boilerplate/env_config');
var devHelper = require('./vendor/electron_boilerplate/dev_helper');
var windowStateKeeper = require('./vendor/electron_boilerplate/window_state');
var gh_releases = require('electron-gh-releases');
var shell = require('shell');
var moment = require('moment');

var mainWindow;

moment().format();

// github release updater options
var options = {
  repo: 'SmartApps4/OnGolf-Desktop',
  currentVersion: app.getVersion()
}

var update = new gh_releases(options, function (auto_updater) {
  // Auto updater event listener
  auto_updater.on('update-downloaded', function (e, rNotes, rName, rDate, uUrl, quitAndUpdate) {
    // Install the update
    quitAndUpdate()
  })
})

// Preserver of the window size and position between app launches.
var mainWindowState = windowStateKeeper('main', {
    width: 512,
    height: 768
});
示例#15
0
const helpSubmenu = [
	{
		label: `${appName} Website...`,
		click() {
			shell.openExternal('https://github.com/kvasir/hipsterchat');
		}
	},
	{
		label: 'Report an Issue...',
		click() {
			const body = `
**Please succinctly describe your issue and steps to reproduce it.**

-

${app.getName()} ${app.getVersion()}
${process.platform} ${process.arch} ${os.release()}`;

			shell.openExternal(`https://github.com/kvasir/hipsterchat/issues/new?body=${encodeURIComponent(body)}`);
		}
	}
];

let tpl;
if (process.platform === 'darwin') {
	tpl = darwinTpl;
} else {
	tpl = linuxTpl;
}

tpl[tpl.length - 1].submenu = helpSubmenu;
示例#16
0
  mainWindow.webContents.on('did-finish-load', function() {
    mainWindow.setTitle('Kitematic');
    mainWindow.show();
    mainWindow.focus();

    if (openURL) {
      mainWindow.webContents.send('application:open-url', {
        url: openURL
      });
    }
    app.on('open-url', function (event, url) {
      event.preventDefault();
      mainWindow.webContents.send('application:open-url', {
        url: url
      });
    });

    if (process.env.NODE_ENV !== 'development') {
      autoUpdater.setFeedUrl('https://updates.kitematic.com/releases/latest?version=' + app.getVersion() + '&beta=' + !!settingsjson.beta + '&platform=' + os.platform());
    }
  });
示例#17
0
var appData = app.getPath('appData');
if (!exports.isBuiltTicino) {
    app.setPath('userData', path.join(appData, 'Ticino-Development'));
}
else if (exports.flavor) {
    app.setPath('userData', path.join(appData, exports.flavor));
}
// !!!
exports.appNameShort = 'Code';
exports.appNameLong = 'Visual Studio Code';
exports.isWindows = (process.platform === 'win32');
exports.isMac = (process.platform === 'darwin');
exports.isLinux = (process.platform === 'linux');
exports.runningInstanceHandle = getRunningInstanceHandle();
exports.appRoot = getAppRoot();
exports.version = app.getVersion();
exports.cliArgs = parseCli();
exports.appHome = app.getPath('userData');
exports.appSettingsHome = path.join(exports.appHome, 'User');
if (!fs.existsSync(exports.appSettingsHome)) {
    fs.mkdirSync(exports.appSettingsHome);
}
exports.appSettingsPath = path.join(exports.appSettingsHome, 'settings.json');
exports.appKeybindingsPath = path.join(exports.appSettingsHome, 'keybindings.json');
exports.welcomePath = path.join(__dirname, 'welcome-win.md');
if (exports.isMac) {
    exports.welcomePath = path.join(__dirname, 'welcome-mac.md');
}
function log() {
    var a = [];
    for (var _i = 0; _i < arguments.length; _i++) {
示例#18
0
文件: main.js 项目: Greqs/Whatsie
(function() {
  // Define the CLI arguments and parse them
  const cliArgs = process.argv.slice(1, process.argv.length);
  const options = yargs(cliArgs)
    .usage('Usage: $0 [options]')
    .option('os-startup', {
      type: 'boolean',
      description: 'Flag to indicate the app is being run by the OS on startup.'
    })
    .option('portable', {
      type: 'boolean',
      description: 'Run in portable mode.'
    })
    .option('debug', {
      type: 'boolean',
      description: 'Run in debug mode.'
    })
    .option('repl', {
      type: 'boolean',
      description: 'Listen for REPL connections.'
    })
    .option('repl-port', {
      type: 'number',
      description: 'The port to listen for REPL connections on.',
      default: 3499
    })
    .option('mas', {
      type: 'boolean',
      description: 'Run in Mac App Store release mode.'
    })
    .option('version', {
      type: 'boolean',
      description: 'Print the app version.',
      alias: 'v'
    })
    .option('squirrel-install', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is installed.'
    })
    .option('squirrel-uninstall', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called after the app is updated.'
    })
    .option('squirrel-updated', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is uninstalled.'
    })
    .option('squirrel-obsolete', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called before updating to a new version.'
    })
    .option('squirrel-firstrun', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called only once after installation.'
    })
    .help('help', 'Print this help message.').alias('help', 'h')
    .epilog('Coded with <3 by ' + global.manifest.author)
    .argv;

  options.mas = options.mas || !!process.mas;
  options.portable = options.portable || !!global.manifest.portable;
  options.debug = options.debug || !!process.env.DEBUG;
  global.options = options;

  // Force-enable debug
  if (options.debug && !process.env.DEBUG) {
    process.env.DEBUG = global.manifest.name + ':*';
    debug.enable(process.env.DEBUG);
  }

  // Log args
  const simplifiedOptions = {};
  Object.keys(options).filter(key => !key.includes('-'))
    .forEach(key => simplifiedOptions[key] = options[key]);
  log('cli args parsed', simplifiedOptions);

  // Check for debug mode
  if (options.debug) {
    log('running in debug mode');
  }

  // Check for mas mode
  if (options.mas) {
    log('running in mas mode');
  }

  // Change the userData path if in portable mode
  if (options.portable) {
    log('running in portable mode');
    const userDataPath = path.join(filePaths.getAppDirPath(), 'data');
    log('setting userData path', userDataPath);
    app.setPath('userData', userDataPath);
  }

  // Check for Squirrel.Windows CLI args
  if (platform.isWindows) {
    const SquirrelEvents = require('browser/components/squirrel-events').default;
    if (SquirrelEvents.check(options)) {
      log('Squirrel.Windows event detected');
      return;
    }
  }

  // Quit the app immediately if required
  if (prefs.get('launch-quit')) {
    log('launch-quit pref is true, quitting');
    prefs.unsetSync('launch-quit');
    return app.quit();
  }

  // Print the version and exit
  if (options.version) {
    console.log(`${app.getName()} ${app.getVersion()}`);
    console.log(`Electron ${process.versions.electron}`);
    console.log(`Chromium ${process.versions.chrome}`);
    return app.quit();
  }

  // Enforce single instance
  const isDuplicateInstance = app.makeSingleInstance(() => {
    if (global.application) {
      global.application.mainWindowManager.showOrCreate();
    }
    return true;
  });

  // Quit if another instance is already running
  if (isDuplicateInstance) {
    log('another instance of the app is already running');
    return app.quit();
  }

  // Listen for app ready-ness
  app.on('ready', function() {
    log('ready, registering protocol', global.manifest.name);
    const protocol = require('protocol');
    protocol.registerFileProtocol(global.manifest.name, function(request, callback) {
      log('protocol handle', request.url);
      callback({
        path: path.join(app.getAppPath(), url.parse(request.url).pathname)
      });
    }, function (err) {
      if (err) {
        logFatal(err);
        log('protocol registration failed, not going to launch the app anymore');
        return;
      }

      log('launching app');
      const Application = require('browser/application').default;
      global.application = new Application();
      global.application.init();
      global.ready = true;
    });
  });

  // If the REPL is enabled, launch it
  if (options.repl) {
    const repl = require('browser/utils/repl');
    repl.createServer(options.replPort);
  }
})();
示例#19
0
        if ( formatter ) {
            return formatter(text);
        }

        return text;
    }
});

// ---------------------------
// initialize Commander
// ---------------------------

// NOTE: commander only get things done barely in core level,
//       it doesn't touch the page level, so it should not put into App.on('ready')
Commander
    .version(App.getVersion())
    .option('--dev', 'Run in development mode')
    .option('--test <path>', 'Run tests in path' )
    .option('--show-devtools', 'Open devtools automatically when main window loaded')
    .option('--debug <port>', 'Open in browser context debug mode', parseInt )
    .option('--debug-brk <port>', 'Open in browser context debug mode, and break at first.', parseInt)
    ;

// EXAMPLE:

// usage
// Commander
//     .usage('[options] <file ...>')
//     ;

// command
示例#20
0
var BrowserWindow = electron.BrowserWindow;  // Module to create native browser window.
var request = require('request');
var os = require('os');
var autoUpdater = require('auto-updater');
var menu = require('menu');
var tray = require('tray');
var ipcMain = require('ipc-main');
var ini = require('ini');

var launched_from_installer = false;
var platform = os.platform();
switch(platform) {
  case "darwin":
    platform = "mac";
}
var version = app.getVersion();
var trayMenu = null;
var subpy = null;

var open_url = null; // This is for if someone opens a URL before the client is open

if (argv.userData) {
  try {
    app.setPath('userData', argv.userData);
  } catch (e) {
    throw new Error('The passed in userData directory does not appear to be valid: ' + e);
  }
}

var handleStartupEvent = function() {
  if (process.platform !== 'win32') {
示例#21
0
文件: main.js 项目: Joriks/Whatsie
(function() {
  // Define the CLI arguments and parse them
  const cliArgs = process.argv.slice(1, process.argv.length);
  const options = yargs(cliArgs)
    .usage('Usage: $0 [options]')
    .option('os-startup', {
      type: 'boolean',
      description: 'Flag to indicate the app is being run by the OS on startup.'
    })
    .option('portable', {
      type: 'boolean',
      description: 'Run in portable mode.'
    })
    .option('debug', {
      type: 'boolean',
      description: 'Run in debug mode.'
    })
    .option('repl', {
      type: 'boolean',
      description: 'Listen for REPL connections on port 3499.'
    })
    .option('mas', {
      type: 'boolean',
      description: 'Run in Mac App Store release mode.'
    })
    .option('version', {
      type: 'boolean',
      description: 'Print the app version.',
      alias: 'v'
    })
    .option('squirrel-install', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is installed.'
    })
    .option('squirrel-uninstall', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called after the app is updated.'
    })
    .option('squirrel-updated', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called when the app is uninstalled.'
    })
    .option('squirrel-obsolete', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called before updating to a new version.'
    })
    .option('squirrel-firstrun', {
      type: 'boolean',
      description: 'Squirrel.Windows flag, called only once after installation.'
    })
    .help('help', 'Print this help message.').alias('help', 'h')
    .epilog('Coded with <3 by ' + manifest.author)
    .argv;

  global.manifest = manifest;
  global.options = options;

  options.mas = options.mas || !!process.mas;
  options.portable = options.portable || !!manifest.portable;
  options.debug = options.debug || !!process.env.DEBUG;

  // Force-enable debug
  if (options.debug && !process.env.DEBUG) {
    debug.enable(manifest.name + ':*');
  }

  log('cli args parsed', options);
  if (options.debug) {
    log('debug mode enabled');
  }

  // Change the userData path if in portable mode
  if (options.portable) {
    log('running in portable mode');
    const userDataPath = path.join(filePaths.getAppDir(), 'data');
    log('set userData path', userDataPath);
    app.setPath('userData', userDataPath);
  }

  // Import prefs now so the correct userData path is used
  const prefs = require('./utils/prefs').default;

  // Check for Squirrel.Windows CLI args
  if (process.platform == 'win32') {
    const SquirrelEvents = require('./components/squirrel-events').default;
    if (SquirrelEvents.check(options)) {
      log('Squirrel.Windows event detected');
      return;
    }
  }

  // Quit the app immediately if this pref is set
  if (prefs.get('launch-quit')) {
    log('launch-quit pref is true, quitting');
    prefs.unsetSync('launch-quit');
    return app.quit();
  }

  // Print the version and exit
  if (options.version) {
    console.log(`${app.getName()} ${app.getVersion()}`);
    console.log(`Electron ${process.versions.electron}`);
    console.log(`Chromium ${process.versions.chrome}`);
    return app.quit();
  }

  // Enforce single instance
  const isDuplicateInstance = app.makeSingleInstance(() => {
    if (global.application) {
      const mainWindow = global.application.mainWindowManager.window;
      if (mainWindow) {
        if (mainWindow.isMinimized()) {
          mainWindow.restore();
        }
        mainWindow.focus();
      }
    }
    return true;
  });

  if (isDuplicateInstance) {
    log('another instance of the app is already running');
    return app.quit();
  }

  // Enable the crash reporter
  if (!options.mas) {
    if (manifest.crashReporter && manifest.crashReporter.url) {
      if (prefs.get('analytics-track')) {
        app.on('will-finish-launching', function() {
          log('will finish launching');

          // Crash reporter
          const reporterOptions = {
            productName: manifest.productName,
            companyName: manifest.win.companyName,
            submitURL: manifest.crashReporter.url,
            autoSubmit: true
          };

          log('starting crash reporter', JSON.stringify(reporterOptions));
          const CrashReporter = require('crash-reporter');
          CrashReporter.start(reporterOptions);
        });
      } else {
        log('analytics disabled, so crash reporter disabled');
      }
    } else {
      log('crash reporter url not configured');
    }
  } else {
    log('mas release, crash reporter disabled');
  }

  // Create the main app object and init
  app.on('ready', function() {
    log('ready, launching app');
    const Application = require('./application').default;
    global.application = new Application(manifest, options);
    global.application.init();
    global.ready = true;
  });

  // If the REPL is enabled, launch it
  if (options.repl) {
    require('./utils/repl').createServer(3499);
  }
})();
示例#22
0
文件: main.js 项目: MSylvia/fireball
    load: function (plugin) {
        if ( Editor.isDev ) {
            plugin.on('auto-updater:open', function () {
                Fire.warn('auto-updater only works in release version.');
            });
            return;
        }

        AutoUpdater.on('checking-for-update', function() {
            status = 'checking';
            Fire.log("Checking for update, current version: " + App.getVersion());
            plugin.sendToPanel('default', 'auto-updater:status-changed', {
                status: status
            });
        });

        AutoUpdater.on('update-available', function(notes) {
            status = 'downloading';
            Fire.log('Downloading...');
            plugin.sendToPanel('default', 'auto-updater:status-changed', {
                status: status
            });
        });

        AutoUpdater.on('update-not-available', function() {
            status = 'not-available';
            plugin.sendToPanel('default', 'auto-updater:status-changed', {
                status: status
            });
            Fire.info('You are in latest version.');
        });

        AutoUpdater.on('update-downloaded', function() {
            status = 'downloaded';
            Fire.info('Download success, ready to install');

            var dialog = require('dialog');
            var result = dialog.showMessageBox({
                type: "warning",
                buttons: ["Quite and install now","later"],
                title: "Install Update",
                message: "install update now?",
                detail: "If you choose \"later\", Fireball will update itself after you quit the app."
            });

            if (result === 0) {
                AutoUpdater.quitAndInstall();
            }
            else if (result === 1) {
                //TODO: 发IPC给MainWindow,让MainWindow在关闭的时候调用AutoUpdater.quitAndInstall();
            }
            ignoreDialog = true;

            plugin.sendToPanel('default', 'auto-updater:status-changed', {
                status: status,
                ignoreDialog: ignoreDialog
            });
        });

        AutoUpdater.on('error', function () {
            Fire.error(arguments[1]);
            status = "error";
            plugin.openPanel('default', {
                status: status
            });
            plugin.sendToPanel('default', 'auto-updater:status-changed', {
                status: status,
            });
        });
        AutoUpdater.setFeedUrl('http://fireball-x.com/api/checkupdate?version=v' + App.getVersion());

        plugin.on('auto-updater:open', function () {
            ignoreDialog = false;
            plugin.openPanel('default', {
                status: status,
                ignoreDialog: ignoreDialog
            });
        });

        plugin.on('auto-updater:start', function () {
            AutoUpdater.checkForUpdates();
        });

        plugin.on('auto-updater:ignore-dialog', function () {
            ignoreDialog = true;
        });
    },
示例#23
0
var App=require("app"),Path=require("fire-path"),Fs=require("fire-fs"),Url=require("fire-url"),Commander=require("commander"),Chalk=require("chalk"),Winston=require("winston");process.removeAllListeners("uncaughtException"),process.on("uncaughtException",function(r){Editor&&Editor.sendToWindows&&Editor.sendToWindows("console:error",r.stack||r),Winston.uncaught(r.stack||r)}),global.Editor={},global.Fire={},Editor.name=App.getName(),Editor.cwd=__dirname,Editor.dataPath=Path.join(App.getPath("home"),"."+Editor.name),Fs.existsSync(Editor.dataPath)||Fs.makeTreeSync(Editor.dataPath);var settingsPath=Path.join(Editor.dataPath,"settings");Fs.existsSync(settingsPath)||Fs.mkdirSync(settingsPath),Editor.App=require("./app.js");var _logpath="";_logpath="darwin"===process.platform?Path.join(App.getPath("home"),"Library/Logs/"+Editor.name):App.getPath("appData"),Fs.existsSync(_logpath)||Fs.makeTreeSync(_logpath);var _logfile=Path.join(_logpath,Editor.name+".log");Fs.existsSync(_logfile)&&Fs.unlinkSync(_logfile);var winstonLevels={normal:0,success:1,failed:2,info:3,warn:4,error:5,fatal:6,uncaught:7};Winston.setLevels(winstonLevels),Winston.remove(Winston.transports.Console),Winston.add(Winston.transports.File,{level:"normal",filename:_logfile,json:!1});var chalk_id=Chalk.bgBlue,chalk_success=Chalk.green,chalk_warn=Chalk.yellow,chalk_error=Chalk.red,chalk_info=Chalk.cyan,levelToFormat={normal:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+r},success:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+chalk_success(r)},failed:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+chalk_error(r)},info:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+chalk_info(r)},warn:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+chalk_warn.inverse.bold("Warning:")+" "+chalk_warn(r)},error:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+chalk_error.inverse.bold("Error:")+" "+chalk_error(r)},fatal:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+chalk_error.inverse.bold("Fatal Error:")+" "+chalk_error(r)},uncaught:function(r){var e=chalk_id("["+process.pid+"]")+" ";return e+chalk_error.inverse.bold("Uncaught Exception:")+" "+chalk_error(r)}};Winston.add(Winston.transports.Console,{level:"normal",formatter:function(r){var e=(chalk_id("["+process.pid+"]")+" ","");void 0!==r.message&&(e+=r.message),r.meta&&Object.keys(r.meta).length&&(e+=" "+JSON.stringify(r.meta));var o=levelToFormat[r.level];return o?o(e):e}}),Commander.version(App.getVersion()).option("--dev","Run in development mode").option("--show-devtools","Open devtools automatically when main window loaded").option("--debug <port>","Open in browser context debug mode",parseInt).option("--debug-brk <port>","Open in browser context debug mode, and break at first.",parseInt),Editor.App.initCommander&&Editor.App.initCommander(Commander),Commander.parse(process.argv),Editor.isDev=Commander.dev,Editor.showDevtools=Commander.showDevtools,App.on("window-all-closed",function(){App.quit()}),App.on("will-finish-launching",function(){}),App.on("ready",function(){if(Winston.normal("Initializing protocol"),require("./src/editor-core/protocol-init"),Winston.normal("Initializing editor"),require("./src/editor-core/editor-init"),require("./src/editor-core/ipc-init"),Editor.registerProfilePath("global",Path.join(Editor.dataPath,"settings")),Editor.registerProfilePath("local",Path.join(Editor.dataPath,"settings")),!Editor.App.init)return Winston.error('Can not find function "init" in your App'),void App.terminate();try{Editor.App.init(Commander)}catch(r){return Winston.error(r.stack||r),void App.terminate()}if(Winston.success("Initial success!"),!Editor.App.run)return Winston.error('Can not find function "run" in your App'),void App.terminate();try{Editor.App.run()}catch(r){return Winston.error(r.stack||r),void App.terminate()}});