all files / WindowsUtilities/ WindowsUtilities.js

89.01% Statements 170/191
76.67% Branches 46/60
91.67% Functions 22/24
89.01% Lines 170/191
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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    16× 16× 16× 12×                               2527×         1557×   1557×   1557×   1557× 1557×       1557× 1557×           426×   426×   426×   426×   426×               16×           1477×                         1477×             114×                                   135×   135× 127×         127×       135×                                                     164× 164×     164×                     398× 398× 164× 164× 164×     234× 58×   58×     234× 234×                       164×   164× 36×   36× 21×   15×       164×                     15×                       19× 19×   19× 57×     19×                   268× 268×                       11× 11× 11×                                         32×         32×   32× 32×   32×   65× 65× 65× 20×   45×     65× 27×     38× 38× 23×   23×   23×           38× 33×         32× 32×      
/*
 * Windows Registry Settings Handler
 *
 * Copyright 2012 Raising the Floor - International
 * Copyright 2012 Antranig Basman
 * Copyright 2012 Astea Solutions AD
 *
 * 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 ffi = require("ffi");
var fluid = require("universal");
 
var gpii = fluid.registerNamespace("gpii");
var windows = fluid.registerNamespace("gpii.windows");
 
var ref = require("ref");
var Struct = require("ref-struct");
var arrayType = require("ref-array");
var NULL = ref.NULL;
 
var os = require("os");
var arch = os.arch();
 
/**
 * A map between Windows and C types.
 * https://msdn.microsoft.com/en-us/library/windows/desktop/aa383751%28v=vs.85%29.aspx
 */
windows.types = {
    "BOOL":   "int",
    "PBOOL":   "*int",
    "INT":    "int",
    "UINT":   "uint",
    "ULONG":  "ulong",
    "DWORD":  "ulong",
    "LPDWORD":  "*ulong",
    "HKL":    "void*",
    "ULONG_PTR": arch === "x64" ? "uint64" : "uint32",
    "LONG": "long",
    "HANDLE": arch === "x64" ? "uint64" : "uint32",
    "PVOID": ref.refType("void"),
    "WORD":   "uint16",
    // TODO: TCHAR should support Unicode and Windows code pages. We are just guessing
    // the system is using Unicode (wchar_t == uint16 type). The implementation should
    // support both modes.
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dd374131(v=vs.85).aspx
    "TCHAR": "uint16"
};
 
var t = windows.types;
 
windows.kernel32 = ffi.Library("kernel32", {
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd319072(v=vs.85).aspx
    // UINT, DWORD, LPCSTR, INT, LPWSTR, INT
    "MultiByteToWideChar": [
        "int", ["uint", "uint32", "char*", "int", "void*", "int"]
    ],
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd374130(v=vs.85).aspx
    // UINT, DWORD, LPCWSTR, int, LPSTR, int, LPCSTR, LPBOOL
    "WideCharToMultiByte": [
        "int", ["uint", "uint32", "void*", "int", "char*", "int", "char*", "bool*"]
    ],
 
    "GetLastError": [
        "int32", []
    ],
    "SetLastError": [
        "void", [ "int32" ]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489(v=vs.85).aspx
    "CreateToolhelp32Snapshot": [
        t.HANDLE, [t.DWORD, t.DWORD]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684834%28v=vs.85%29.aspx
    "Process32First": [
        "bool", [t.DWORD, "pointer"]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320%28v=vs.85%29.aspx
    "OpenProcess": [
        t.HANDLE, [t.DWORD, t.BOOL, t.DWORD]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714%28v=vs.85%29.aspx
    "TerminateProcess": [
        t.BOOL, [t.HANDLE, t.UINT]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211%28v=vs.85%29.aspx
    "CloseHandle": [
        t.BOOL, [t.HANDLE]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684836%28v=vs.85%29.aspx
    "Process32Next": [
        t.BOOL, [t.HANDLE, "pointer"]
    ],
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684139.aspx
    "IsWow64Process": [
        t.BOOL,  [t.INT, t.PBOOL ]
    ]
});
 
windows.user32 = ffi.Library("user32", {
    // https://msdn.microsoft.com/library/ms633497
    "EnumWindows": [
        t.BOOL, ["void*", t.HANDLE]
    ],
    // https://msdn.microsoft.com/library/windows/desktop/ms633522
    "GetWindowThreadProcessId": [
        t.DWORD, [t.HANDLE, t.LPDWORD]
    ],
    // https://msdn.microsoft.com/library/windows/desktop/ms644944
    "PostMessageW": [
        t.BOOL, [t.HANDLE, t.UINT, t.UINT, t.HANDLE ]
    ]
});
 
/**
 * Gets a function pointer for an EnumWindowsProc callback for EnumWindows.
 *
 * See: https://msdn.microsoft.com/en-us/library/ms633498
 *
 * @param callback {function} The callback.
 * @return {*} Function pointer for the given callback, to be passed to EnumWindows
 */
windows.EnumWindowsProc = function (callback) {
    return ffi.Callback(t.BOOL, [t.HANDLE, t.HANDLE], callback);
};
 
// Windows API constants delved from the unfathomable deeps of windows.h
windows.API_constants = {
    HKEY_CLASSES_ROOT:   0x80000000,
    HKEY_CURRENT_USER:   0x80000001,
    HKEY_LOCAL_MACHINE:  0x80000002,
    HKEY_USERS:          0x80000003,
    HKEY_CURRENT_CONFIG: 0x80000005,
    CP_UTF8: 65001,
    KEY_QUERY_VALUE: 1,
    KEY_SET_VALUE: 2,
    returnCodesLookup: {
        0: "ERROR_SUCCESS",
        1: "ERROR_INVALID_FUNCTION",
        2: "FILE_NOT_FOUND",
        3: "PATH_NOT_FOUND",
        6: "ERROR_INVALID_HANDLE",
        259: "ERROR_NO_MORE_ITEMS"
    },
    returnCodes: {},
 
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880%28v=vs.85%29.aspx
    PROCESS_TERMINATE: 0x0001,
 
    // http://stackoverflow.com/questions/23452271/is-max-path-always-same-size-even-if-unicode-macro-is-defined
    MAX_PATH: 260,
    MAX_NAME: 32,
    ENUM_CURRENT_SETTINGS: 0xffffffff,   // ((DWORD)-1)
    DISP_CHANGE_SUCCESSFUL: 0,
    DISP_CHANGE_RESTART: 1,
    FALSE:  0,
    TRUE:   1,
    // https://msdn.microsoft.com/library/windows/desktop/ms632641
    WM_QUIT: 0x12,
 
    // The AccessibilityTemp values; https://msdn.microsoft.com/library/windows/desktop/bb879984.aspx
    disableAT: 2,
    enableAT: 3
};
 
fluid.each(windows.API_constants.returnCodesLookup, function (value, key) {
    windows.API_constants.returnCodes[value] = +key;
});
 
/*
 * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682489(v=vs.85).aspx
 * TH32CS_SNAPALL
 */
var TH32CS_SNAPHEAPLIST = 0x00000001;
var TH32CS_SNAPMODULE = 0x00000008;
var TH32CS_SNAPPROCESS = 0x00000002;
var TH32CS_SNAPTHREAD = 0x00000004;
 
var TH32CS_SNAPALL = TH32CS_SNAPHEAPLIST | TH32CS_SNAPMODULE |
    TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD;
 
windows.API_constants.TH32CS_SNAPALL = TH32CS_SNAPALL;
windows.API_constants.TH32CS_SNAPPROCESS = TH32CS_SNAPPROCESS;
 
var c = windows.API_constants;
 
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms684839%28v=vs.85%29.aspx
windows.PROCESSENTRY32 = new Struct([
    [t.DWORD, "dwSize"],
    [t.DWORD, "cntUsage"],
    [t.DWORD, "th32ProcessID"],
    [t.ULONG_PTR, "th32DefaultHeapID"],
    [t.DWORD, "th32ModuleID"],
    [t.DWORD, "cntThreads"],
    [t.DWORD, "th32ParentProcessID"],
    [t.LONG, "pcPriClassBase"],
    [t.DWORD, "dwFlags"],
    // TODO: This needs refactoring to adopt new type t.TCHAR instead of an array of
    // chars.
    [arrayType("char", c.MAX_PATH), "szExeFile"]
]);
 
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd318112(v=vs.85).aspx
windows.HighContrast = new Struct({
    "cbSize": "uint32",
    "dwFlags": "int32",
    "lpszDefaultScheme": "pointer"
});
windows.highContrastPointer = ref.refType(windows.HighContrast);
 
// http://msdn.microsoft.com/en-us/library/windows/desktop/dd145037(v=vs.85).aspx
windows.LogFont = new Struct([
    ["int32",  "lfHeight"],
    ["int32",  "lfWidth"],
    ["int32",  "lfEscapement"],
    ["int32",  "lfOrientation"],
    ["int32",  "lfWeight"],
    ["uchar",  "lfItalic"],
    ["uchar",  "lfUnderline"],
    ["uchar",  "lfStrikeOut"],
    ["uchar",  "lfCharSet"],
    ["uchar",  "lfOutPrecision"],
    ["uchar",  "lfClipPrecision"],
    ["uchar",  "lfQuality"],
    ["uchar",  "lfPitchAndFamily"],
    [arrayType(t.TCHAR, c.MAX_NAME), "lfFaceName"]
]);
windows.logFontPointer = ref.refType(windows.LogFont);
 
// http://msdn.microsoft.com/en-us/library/windows/desktop/ff729175(v=vs.85).aspx
windows.NonClientMetrics = new Struct([
    ["uint32",   "cbSize"],
    ["int32",    "iBorderWidth"],
    ["int32",    "iScrollWidth"],
    ["int32",    "iScrollHeight"],
    ["int32",    "iCaptionWidth"],
    ["int32",    "iCaptionHeight"],
    [windows.LogFont,  "lfCaptionFont"],
    ["int32",    "iSmCaptionWidth"],
    ["int32",    "iSmCaptionHeight"],
    [windows.LogFont,  "lfSmCaptionFont"],
    ["int32",    "iMenuWidth"],
    ["int32",    "iMenuHeight"],
    [windows.LogFont,  "lfMenuFont"],
    [windows.LogFont,  "lfStatusFont"],
    [windows.LogFont,  "lfMessageFont"],
    ["int32", "iPaddedBorderWidth"]
]);
windows.nonClientMetricsPointer = ref.refType(windows.NonClientMetrics);
 
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd373652(v=vs.85).aspx
windows.StickyKeys = new Struct([
    ["uint32",   "cbSize"],
    ["uint32",   "dwFlags"]
]);
windows.StickyKeysPointer = ref.refType(windows.StickyKeys);
 
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd318079(v=vs.85).aspx
windows.FilterKeys = new Struct([
    ["uint32",   "cbSize"],
    ["uint32",   "dwFlags"],
    ["uint32",   "iWaitMSec"],
    ["uint32",   "iDelayMSec"],
    ["uint32",   "iRepeatMSec"],
    ["uint32",   "iBounceMSec"]
]);
windows.FilterKeysPointer = ref.refType(windows.FilterKeys);
 
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd373593(v=vs.85).aspx
windows.MouseKeys = new Struct([
    ["uint32",   "cbSize"],
    ["uint32",   "dwFlags"],
    ["uint32",   "iMaxSpeed"],
    ["uint32",   "iTimeToMaxSpeed"],
    ["uint32",   "iCtrlSpeed"],
    ["uint32",   "dwReserved1"],
    ["uint32",   "dwReserved2"]
]);
windows.MouseKeysPointer = ref.refType(windows.MouseKeys);
 
// TODO Define additional structures used in calls to SystemParametersInfo here.
 
/**
 * Contains actions that can be used as the first argument of the SystemParametersInfo function.
 */
windows.actionConstants = {
    "SPI_GETHIGHCONTRAST":     0x0042,
    "SPI_SETHIGHCONTRAST":     0x0043,
    "SPI_GETNONCLIENTMETRICS": 0x0029,
    "SPI_SETNONCLIENTMETRICS": 0x002A,
    "SPI_GETICONTITLELOGFONT": 0x001F,
    "SPI_SETICONTITLELOGFONT": 0x0022,
    "SPI_GETSTICKYKEYS":       0x003A,
    "SPI_SETSTICKYKEYS":       0x003B,
    "SPI_GETFILTERKEYS":       0x0032,
    "SPI_SETFILTERKEYS":       0x0033,
    "SPI_GETMOUSE":            0x0003,
    "SPI_SETMOUSE":            0x0004,
    "SPI_GETMOUSEKEYS":        0x0036,
    "SPI_SETMOUSEKEYS":        0x0037,
    "SPI_GETMOUSECLICKLOCK":   0x101E,
    "SPI_SETMOUSECLICKLOCK":   0x101F,
 
    "SPI_GETMOUSETRAILS":      0x005E,
    "SPI_SETMOUSETRAILS":      0x005D
    // TODO Define additional actions used in calls to SystemParametersInfo here.
};
 
/**
 * Contains flags used in the "dwFlags" field of various structures
 * that are used in calls to the SystemParametersInfo function.
 */
windows.flagConstants = {
    // HIGHCONTRAST flags
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd318112(v=vs.85).aspx
    "HCF_AVAILABLE":       0x00000002,
    "HCF_CONFIRMHOTKEY":   0x00000008,
    "HCF_HIGHCONTRASTON":  0x00000001,
    "HCF_HOTKEYACTIVE":    0x00000004,
    "HCF_HOTKEYAVAILABLE": 0x00000040,
    "HCF_HOTKEYSOUND":     0x00000010,
    "HCF_INDICATOR":       0x00000020,
 
    // STICKYKEYS flags
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd373652%28v=vs.85%29.aspx
    "SKF_AUDIBLEFEEDBACK": 0x00000040,
    "SKF_AVAILABLE":       0x00000002,
    "SKF_HOTKEYACTIVE":    0x00000004,
    "SKF_STICKYKEYSON":    0x00000001,
 
    // FILTERKEYS flags
    // http://msdn.microsoft.com/en-us/library/windows/desktop/dd318079%28v=vs.85%29.aspx
    "FKF_AVAILABLE":       0x00000002,
    "FKF_CLICKON":         0x00000040,
    "FKF_CONFIRMHOTKEY":   0x00000008,
    "FKF_FILTERKEYSON":    0x00000001,
    "FKF_HOTKEYACTIVE":    0x00000004,
    "FKF_HOTKEYSOUND":     0x00000010,
    "FKF_INDICATOR":       0x00000020,
 
    // MOUSEKEYS flags
    // https://msdn.microsoft.com/en-us/library/windows/desktop/dd373593(v=vs.85).aspx
    "MKF_AVAILABLE":       0x00000002,
    "MKF_CONFIRMHOTKEY":   0x00000008,
    "MKF_HOTKEYACTIVE":    0x00000004,
    "MKF_HOTKEYSOUND":     0x00000010,
    "MKF_INDICATOR":       0x00000020,
    "MKF_LEFTBUTTONDOWN":  0x01000000,
    "MKF_LEFTBUTTONSEL":   0x10000000,
    "MKF_MODIFIERS":       0x00000040,
    "MKF_MOUSEKEYSON":     0x00000001,
    "MKF_MOUSEMODE":       0x80000000,
    "MKF_REPLACENUMBERS":  0x00000080,
    "MKF_RIGHTBUTTONDOWN": 0x02000000,
    "MKF_RIGHTBUTTONSEL":  0x20000000
 
    // TODO Define additional flags used across various structures here.
};
 
/**
 * Contains structures that are used in calls to the SystemParametersInfo function,
 * accessible by their names. Used to dynamically instantiate the appropriate structure.
 */
windows.structures = {
    "HIGHCONTRAST":     windows.HighContrast,
    "NONCLIENTMETRICS": windows.NonClientMetrics,
    "LOGFONT":          windows.LogFont,
    "STICKYKEYS":       windows.StickyKeys,
    "FILTERKEYS":       windows.FilterKeys,
    "MOUSEKEYS":        windows.MouseKeys
    // TODO Add additional structures that we need to instantiate here.
};
 
gpii.pointerToHex = function (pointer, count) {
    var togo = "";
    for (var i = 0; i < count; ++i) {
        var nbyte = pointer.readUInt8(i);
        togo += (nbyte < 16 ? "0" : "") + nbyte.toString(16);
        if (i !== count - 1) {
            togo += " ";
        }
    }
    return togo;
};
 
// Slow but short method to parse very forgiving hex streams - any non-hex characters will be ignored. Digits
// forming a single byte must be adjacent
gpii.hexToPointer = function (hexString) {
    var buffer = [];
    var i;
    for (i = 0; i < hexString.length; ++i) {
        var c = hexString.charAt(i);
        var digit = parseInt(c, 16);
        if (!isNaN(digit)) {
            buffer.push(digit);
        }
    }
    Iif ((buffer.length % 2) === 1) {
        fluid.fail("Odd number of hex digits in buffer " + hexString);
    }
 
    var togo = new Buffer(buffer.length / 2);
 
    for (i = 0; i < buffer.length; i += 2) {
        togo.writeUInt8(buffer[i] * 16 + buffer[i + 1], i / 2);
    }
    return {
        pointer: togo,
        length: buffer.length / 2
    };
};
 
windows.convertReturnCode = function (code) {
    return "Return code " + code + ": " + c.returnCodesLookup[code];
};
 
windows.checkReturnCode = function (code) {
    Iif (code !== 0) {
        fluid.fail(windows.convertReturnCode(code));
    }
};
 
windows.toWideChar = function (string) {
    var stringBuffer = new Buffer(string);
 
    var chars = windows.kernel32.MultiByteToWideChar(c.CP_UTF8, 0, stringBuffer, stringBuffer.length, NULL, 0);
 
    var buffer = new Buffer(chars * 2 + 2); // 2 extra bytes for the null character
 
    var chars2 = windows.kernel32.MultiByteToWideChar(c.CP_UTF8, 0, stringBuffer, stringBuffer.length, buffer, chars);
    Iif (chars2 !== chars) {
        fluid.fail("Expected to write " + chars + " characters, only wrote " + chars2);
    }
 
    buffer.writeInt16BE(0, chars * 2);  // add the null character at the end
    return {
        pointer: buffer,
        length: chars * 2
    };
};
 
windows.fromWideChar = function (buffer) {
    buffer = ref.reinterpretUntilZeros(buffer, 2, 0);
 
    var bytes = windows.kernel32.WideCharToMultiByte(c.CP_UTF8, 0, buffer, buffer.length / 2, NULL, 0, NULL, NULL);
 
    var convertBuffer = new Buffer(bytes);
 
    windows.kernel32.WideCharToMultiByte(c.CP_UTF8, 0, buffer, buffer.length / 2, convertBuffer, bytes, NULL, NULL);
 
    return convertBuffer.toString();
};
 
/**
 * Buffer-based conversions
 */
windows.stringToWideChar = function (string) {
    return new Buffer(string + "\u0000", "ucs2"); // add null at the end
};
 
windows.stringFromWideChar = function (buffer) {
    return ref.reinterpretUntilZeros(buffer, 2, 0).toString("ucs2");
};
 
/*
 * Unicode registry functions need the string pointers aligned on 16bit boundary.
 */
windows.ensureAlignment = function (buffer) {
    Iif (ref.address(buffer) & 1) { // not aligned
        var alignedBuffer = new Buffer(buffer.length + 1);
 
        if (ref.address(alignedBuffer) & 1) { // the new buffer is not aligned as well
            buffer.copy(alignedBuffer, 1);
            return alignedBuffer.slice(1);
 
        } else { // the new buffer is OK
            buffer.copy(alignedBuffer);
            return alignedBuffer.slice(0, alignedBuffer.length - 1);
        }
    }
 
    return buffer;
};
 
/**
 * If a structure is not already defined, creates it by using the structure template in the payload.
 * If such is not provided, throws an exception.
 */
windows.defineStruct = function (payload) {
    Iif (payload.options.pvParam.type === "struct" && !windows.structures[payload.options.pvParam.name]) {
        if (!payload.options.pvParam.template) {
            throw "Cannot create structure " + payload.options.pvParam.name + " - payload.options.pvParam.template not found!";
        }
 
        windows.structures[payload.options.pvParam.name] = new Struct(payload.options.pvParam.template);
    }
};
 
/**
 * Creates an empty structure with a given name. It should be registered in the
 * <code>windows.structures</code> map with that name. If the structure has a <code>cbSize</code>
 * member, the function sets that member to the size of the structure using <code>ffi.sizeof</code>.
 *
 * @param {String} structName The name of the structure to create. Should be registered in the
 *                 <code>windows.structures</code> map.
 * @return {Object} The newly created structure with its <code>cbSize</code> member initialized.
 */
windows.createEmptyStructure = function (structName) {
    var struct = new windows.structures[structName]();
 
    if (struct.cbSize !== undefined) {
        struct.cbSize = windows.structures[structName].size;
        // TODO: This needs to be dropped. It's duplicated in SpiSettingsHandler too,
        // creating a poison dependency. It should be in the struct definition or
        // let it pass because it only applies on Windows Server 2003 and
        // Windows XP/2000
        if (structName === "NONCLIENTMETRICS" && os.release() < "6") {
            struct.cbSize -= 4; // do not unclude NONCLIENTMETRICS.iPaddedBorderWidth
        }
    }
 
    return struct;
};
 
/**
 * Takes an array of flag names, applies binary OR among them and returns the result.
 * Used to supply the "dwFlags" argument of some structures.
 *
 * @param {Array} flagNamesArray An array of flag names.
 *                These should be predefined in windows.flagConstants.
 */
windows.combineFlags = function (flagNamesArray) {
    var combinedFlags = 0;
    if (!fluid.isArrayable(flagNamesArray)) {
        console.log("GPII Windows SpiSettingsHandler combineFlags: array expected!");
        return 0;
    }
    for (var index in flagNamesArray) {
        combinedFlags = combinedFlags | windows.flagConstants[flagNamesArray[index]];
    }
    return combinedFlags;
};
 
/**
 * Gets the value of a given flag name.
 *
 * @param {String} flagName The name of the flag whose value we need.
 * @return {Number} The value of the flag.
 */
windows.getFlagValue = function (flagName) {
    var flagValue = windows.flagConstants[flagName];
    Iif (flagValue === undefined) {
        fluid.fail("Unknown flag name " + flagName);
    }
    return flagValue;
};
 
/**
 * Accesses consecutive fields of an object.
 *
 * @param {Object} object The object to be accessed.
 * @param {String} path A string containing the consecutive field names, separated by '.'
 * @param {Object} setValue <optional> A new value to be stored in the field.
 * @return {Object} The value stored in the field.
 */
windows.resolvePath = function (object, path, setValue) {
    var flagsIndex = path.indexOf("dwFlags");
    if (flagsIndex !== -1) {
        var path1 = path.substr(0, flagsIndex - 1);
        var flagName = path.substr(path.lastIndexOf(".") + 1);
        return windows.accessFlag(fluid.get(object, path1), flagName, setValue);
 
    } else {
        if (setValue !== undefined) {
            if (typeof setValue === "string") {
                setValue = windows.stringToWideChar(setValue);
            }
            fluid.set(object, path, setValue);
        }
 
        var value = fluid.get(object, path);
        return Buffer.isBuffer(value) ? windows.stringFromWideChar(value) : value;
    }
};
 
/**
 * Accesses a single flag in a flags field of an object.
 *
 * @param {Object} object The object to be accessed.
 * @param {String} flagName A string containing the flag name according to the Windows API.
 * @param {Object} setValue <optional> A new value for the flag.
 * @return {Object} The value of the flag.
 */
windows.accessFlag = function (object, flagName, setValue) {
    var flagValue = windows.getFlagValue(flagName);
 
    if (setValue !== undefined) {
        setValue = Boolean(setValue);
        // The '>>>' operator is needed to convert the number back to an unsigned 32-bit int.
        if (setValue) {
            object.dwFlags = (object.dwFlags | flagValue) >>> 0;
        } else {
            object.dwFlags = (object.dwFlags & ~flagValue) >>> 0;
        }
    }
 
    return Boolean(object.dwFlags & flagValue);
};
 
/**
 * Converts an array to a buffer.
 *
 * @param {Array} array The array to be converted.
 * @param {String} type The type of the array according to the Windows API.
 * @return {Buffer} A buffer representing the raw memory allocated for the array.
 */
windows.arrayToBuffer = function (array, type) {
    var size = ref.coerceType(windows.types[type]).size;
    var buf = new Buffer(array.length * size);
 
    for (var i = 0; i < array.length; ++i) {
        ref.set(buf, i * size, array[i], windows.types[type]);
    }
 
    return buf;
};
 
/**
 * Converts a buffer to an array.
 *
 * @param {Buffer} buffer The buffer to be converted.
 * @param {String} type The type of the array according to the Windows API.
 * @return {Array} An array containing the values stored in the buffer.
 */
windows.bufferToArray = function (buffer, type) {
    var array = [];
    var size = ref.coerceType(windows.types[type]).size;
 
    for (var i = 0; i < buffer.length / size; ++i) {
        array[i] = ref.get(buffer, i * size, windows.types[type]);
    }
 
    return array;
};
 
/**
 * Enumerates all top-level windows on the desktop, invoking the callback for each one.
 *
 * @param callback Called for each Window.
 */
windows.enumerateWindows = function (callback) {
    // Suppress "no-unused-vars" - lparam argument is required for EnumWindowsProc.
    // eslint-disable-next-line no-unused-vars
    var proc = gpii.windows.EnumWindowsProc(function (hwnd, lparam) {
        callback(hwnd);
        return true;
    });
 
    gpii.windows.user32.EnumWindows(proc, 0);
};
 
/**
 * Determines whether this process is running under WoW64. That is, 32-bit node on 64-bit Windows.
 *
 * https://msdn.microsoft.com/en-us/library/windows/desktop/aa384249(v=vs.85).aspx
 *
 * @return {boolean} true if this process is 32-bit, and the OS is 64-bit otherwise false.
 */
windows.isWow64 = function () {
    var ptr = ref.alloc(windows.types.DWORD);
    gpii.windows.kernel32.IsWow64Process(-1, ptr);
    return !!ptr.deref();
};
 
/**
 * Waits for a condition, by polling a given function. A promise is returned, resolving when the condition is met or
 * rejecting upon timeout. If the condition is already met, then the returned promise will be resolved.
 *
 * The function is called repeatedly (with a delay) until it returns a truthful value, or a period of time has elapsed.
 *
 * @param {Function} func The function to call which checks the condition.
 * @param {Object} [options] Options
 * @param {Any} options.conditionValue The value that the function will return to indicate the condition is met.
 *  This is compared using '===', but the default is to match any truthy value.
 * @param {Number} options.argument An argument to pass to the function.
 * @param {Number} options.timeout How long to wait (ms) before timing out, or null (default) for no timeout.
 * @param {Number} options.pollDelay The delay (ms) between each poll. 500ms by default.
 * @param {Boolean} options.dontReject If true, then resolve the promise with "timeout" instead of rejecting.
 * @param {Object} options.error The error object used when rejecting.
 *
 * @todo A better place for this should be found/created, as it's not even specific to Windows.
 */
windows.waitForCondition = function (func, options) {
    var defaultOptions = {
        timeout: null,
        pollDelay: 500,
        dontReject: false
    };
    options = fluid.extend(defaultOptions, options);
 
    var promise = fluid.promise();
    var startTime = process.hrtime();
 
    var checkCondition = function () {
        // See if the condition has been met.
        var returnValue = func(options.argument);
        var conditionMet;
        if (options.conditionValue === undefined) {
            conditionMet = !!returnValue;
        } else {
            conditionMet = (returnValue === options.conditionValue);
        }
 
        if (conditionMet) {
            promise.resolve();
        } else {
            // Check the time.
            var timedout = false;
            if (typeof(options.timeout) === "number") {
                var hr = process.hrtime(startTime);
                // combine seconds + nanoseconds into milliseconds
                var timeTakenMs = (hr[0] * 1000) + (hr[1] / 1e6);
 
                if (timeTakenMs >= options.timeout) {
                    timedout = true;
                    if (options.dontReject) {
                        promise.resolve("timeout");
                    } else {
                        promise.reject(options.error);
                    }
                }
            }
 
            if (!timedout) {
                setTimeout(checkCondition, options.pollDelay);
            }
        }
    };
 
    checkCondition();
    return promise;
};
 
exports.windows = windows;