all files / processHandling/ processHandling.js

91.03% Statements 71/78
73.08% Branches 19/26
90% Functions 9/10
91.03% Lines 71/78
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291                                                              15× 15× 15×                                   69× 69×         69× 69×   69×   69× 69×     69× 69× 4351× 4351×   4351× 50×   27×     23×       4328×       69× 69×       46×                 45×                                   23×           23×   23×                       23×                             18× 18×                                                                                             268× 268× 268×   268×                                                                                                
/*
 * Windows Process Handling.
 * A wrapper to integrate processHandlingCore into GPII.
 *
 * Copyright 2016 Raising the Floor - International
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The research leading to these results has received funding from the European Union's
 * Seventh Framework Programme (FP7/2007-2013)
 * under grant agreement no. 289016.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */
 
"use strict";
 
var fluid = require("universal");
var ref = require("ref");
 
var gpii = fluid.registerNamespace("gpii");
var windows = fluid.registerNamespace("gpii.windows");
 
require("../WindowsUtilities/WindowsUtilities.js");
 
var c = windows.API_constants;
 
/**
 * Kills any windows processes with a given application filename.
 * http://stackoverflow.com/questions/7956519/how-to-kill-processes-by-name-win32-api
 *
 * @param {String} The filename of the application. For example, the Windows on
 * screen keyboard is "osk.exe". Other examples include "Magnify.exe" and
 * "firefox.exe".
 */
gpii.windows.killProcessByName = function (filename) {
    var pids = gpii.windows.findProcessByName(filename, true);
    Eif (pids) {
        for (var n = 0, len = pids.length; n < len; n++) {
            var hProcess = windows.kernel32.OpenProcess(c.PROCESS_TERMINATE, 0, pids[n]);
            Eif (hProcess !== ref.NULL) {
                windows.kernel32.TerminateProcess(hProcess, 9);
                windows.kernel32.CloseHandle(hProcess);
            }
        }
    }
};
 
/**
 * Finds a running process with the given name.
 *
 * The CreateToolhelp32Snapshot Windows API call captures the running processes, and the Process32First/Next
 * functions are used to enumerate them.
 *
 * @param filename The exe file name to search for.
 * @param all {boolean?} Set to true to return an array containing all matching processes.
 * @returns {?number|number[]} The Process ID of the matching processes, otherwise null.
 */
gpii.windows.findProcessByName = function (filename, all) {
 
    // Get a snapshot of the processes.
    var hSnapShot = windows.kernel32.CreateToolhelp32Snapshot(windows.API_constants.TH32CS_SNAPPROCESS, null);
    Iif (hSnapShot === windows.API_constants.INVALID_HANDLE_VALUE) {
        console.error("CreateToolhelp32Snapshot failed. Win32 error: " + windows.GetLastError());
        return null;
    }
 
    var matches = [];
    var filenameLower = filename.toLowerCase();
 
    try {
        // Create the structure for the return parameter of Process32First/Next.
        var pEntry = new windows.PROCESSENTRY32();
        pEntry.dwSize = windows.PROCESSENTRY32.size;
 
        // Enumerate the processes.
        var hRes = windows.kernel32.Process32First(hSnapShot, pEntry.ref());
        while (hRes) {
            var buf = new Buffer(pEntry.szExeFile);
            var processName = ref.readCString(buf, 0);
 
            if (processName.toLowerCase() === filenameLower) {
                if (all) {
                    // Add it to the array of matches.
                    matches.push(pEntry.th32ProcessID);
                } else {
                    // Only want the first one - return it.
                    return pEntry.th32ProcessID;
                }
            }
 
            hRes = windows.kernel32.Process32Next(hSnapShot, pEntry.ref());
        }
    } finally {
        // Make sure the snapshot is closed.
        Eif (hSnapShot) {
            windows.kernel32.CloseHandle(hSnapShot);
        }
    }
 
    return all ? matches : null;
};
 
/**
 * Determines if a given process is running, returning true if it is.
 *
 * @param {string} filename The name of the executable.
 * @return {boolean} true if the process is running.
 */
gpii.windows.isProcessRunning = function (filename) {
    return gpii.windows.findProcessByName(filename) !== null;
};
 
 
/**
 * Waits for a process to either start or terminate, returning a promise which will resolve when the existence of a
 * process is in the desired state.
 *
 * The promise will reject if the process has yet to become in the desired state after the timeout.
 *
 * @param filename The executable.
 * @param options The options.
 * @param options.start The desired state: true to wait for the process to start, false to wait for the termination.
 * @param options.timeout Approximate milliseconds to wait, or null for infinite.
 * @param options.pollDelay How long to wait, in milliseconds, between checking for the process.
 * @return {promise} The promise will resolve when the process is in the desired state, or will reject if after the
 *   timeout the process is still in the same state.
 */
gpii.windows.waitForProcessState = function (filename, options) {
    var defaultOptions = {
        pollDelay: 500,
        timeout: null,
        start: false
    };
 
    options = fluid.extend(true, defaultOptions, options);
 
    var waitOptions = {
        argument: filename,
        conditionValue: options.start,
        pollDelay: options.pollDelay,
        timeout: options.timeout,
        error: {
            isError: true,
            message: "Timed out waiting for process " + filename +
            " to " + (options.start ? "start" : "terminate") + " after " + options.timeout + "ms"
        }
    };
 
    return gpii.windows.waitForCondition(gpii.windows.isProcessRunning, waitOptions);
};
 
/**
 * Waits for a process to terminate, returning a promise which will resolve when there are no matching processes
 * running. If there are no processes running when the function is called, the promise will already be resolved.
 * The promise will reject if the process is still running after the timeout.
 *
 * @param filename The executable.
 * @param userOptions The options.
 * @param userOptions.timeout Approximate milliseconds to wait, or null for infinite.
 * @param userOptions.pollDelay How long to wait, in milliseconds, between checking for the process.
 * @return {promise} The promise will resolve when there are no matching processes running, or will reject if a matching
 *  process is still running after the timeout.
 */
gpii.windows.waitForProcessTermination = function (filename, userOptions) {
    var options = fluid.extend(true, {start: false}, userOptions);
    return gpii.windows.waitForProcessState(filename, options);
};
 
/**
 * Waits for a process to start, returning a promise which will resolve when there there is a matching process running.
 * If there are already processes running when the function is called, the promise will already be resolved.
 * The promise will reject if a matching process is still not running after the timeout.
 *
 * @param filename The executable.
 * @param userOptions The options.
 * @param userOptions.timeout Approximate milliseconds to wait, or null for infinite.
 * @param userOptions.pollDelay How long to wait, in milliseconds, between checking for the process.
 * @return {promise} The promise will resolve when there is a matching processes running, or will reject if a matching
 *  process is still not running after the timeout.
 */
gpii.windows.waitForProcessStart = function (filename, userOptions) {
    var options = fluid.extend(true, {start: true}, userOptions);
    return gpii.windows.waitForProcessState(filename, options);
};
 
/**
 * Terminates a process in a kind manner by sending WM_QUIT to the windows it owns. This should allow the process to
 * perform any clean up tasks.
 *
 * If options.gracefulOnly is false (default), and if the process has not shutdown after the timeout or the process
 * does not have any Windows, then the process will be terminated.
 *
 * The returned promise resolves when the process has ended, with a boolean indicating whether a clean shutdown was
 * possible.
 *
 * @param filename
 * @param options The options.
 * @param options.timeout How long to wait for the process to die, in milliseconds.
 * @param options.cleanOnly true to reject if the process can't be closed cleanly; false to force the termination.
 * @param options.exitCode {number} The exit code the application should return.
 * @return {promise}
 */
gpii.windows.closeProcessByName = function (filename, options) {
    var defaultOptions = {
        timeout: 15000,
        cleanOnly: false,
        exitCode: 0
    };
 
    options = fluid.extend(defaultOptions, options);
 
    var pids = gpii.windows.findProcessByName(filename, true);
    Iif (!pids) {
        // Process is not running.
        return fluid.toPromise(true);
    }
 
    var foundWindow = false;
 
    // Enumerate all the top-level windows on the desktop, to see which ones are owned by the process.
    gpii.windows.enumerateWindows(function (hwnd) {
        // Get the process ID that owns the Window.
        var ptr = ref.alloc(windows.types.DWORD);
        gpii.windows.user32.GetWindowThreadProcessId(hwnd, ptr);
        var windowPid = ptr.deref();
 
        if (pids.indexOf(windowPid) !== -1) {
            // Send WM_QUIT, which tells the thread to terminate.
            gpii.windows.user32.PostMessageW(hwnd, windows.API_constants.WM_QUIT, options.exitCode, 0);
            foundWindow = true;
        }
    });
 
    var promiseTogo = fluid.promise();
 
    if (foundWindow) {
        // Wait for the process to die.
        gpii.windows.waitForProcessTermination(filename, { timeout: options.timeout })
            .then(function () {
                promiseTogo.resolve(true);
            }, function (err) {
                // Taking too long to die.
                if (options.cleanOnly) {
                    promiseTogo.reject({
                        isError: true,
                        message: "Process " + filename + " will not close cleanly: " + err.message,
                        error: err
                    });
                } else {
                    // Force it to terminate
                    gpii.windows.killProcessByName(filename);
 
                    // This promise was rejected but the return promise should resolve as the process is terminated.
                    promiseTogo.resolve(false);
                }
            });
    } else {
        // The process does not have any windows so it can't be shutdown cleanly.
        if (options.cleanOnly) {
            promiseTogo.reject({
                isError: true,
                message: "Process " + filename + " will not close cleanly: No windows belong to the process"
            });
        } else {
            // Force it to terminate.
            gpii.windows.killProcessByName(filename);
            promiseTogo.resolve(false);
        }
    }
 
    return promiseTogo;
};
 
fluid.defaults("gpii.windows.killProcessByName", {
    gradeNames: "fluid.function",
    argumentMap: {
        filename: 0
    }
});
 
fluid.defaults("gpii.windows.closeProcessByName", {
    gradeNames: "fluid.function",
    argumentMap: {
        filename: 0,
        options: 1
    }
});