|
| 1 | +const CONNECTED_REGEX = /^(\S+) connected (?:(\d+)x(\d+))?/; |
| 2 | +const DISCONNECTED_REGEX = /^(\S+) disconnected/; |
| 3 | +const MODE_REGEX = /^\s+(\d+)x([0-9i]+)\s+((?:\d+\.)?\d+)([* ]?)([+ ]?)/; |
| 4 | + |
| 5 | +export default function xrandrParser(input) { |
| 6 | + let strInput = input; |
| 7 | + if (Buffer.isBuffer(input)) { |
| 8 | + strInput = input.toString(); |
| 9 | + } |
| 10 | + const lines = strInput.split('\n'); |
| 11 | + const result = {}; |
| 12 | + let mode = {}; |
| 13 | + let lastInterface; |
| 14 | + |
| 15 | + lines.forEach((line) => { |
| 16 | + let parts; |
| 17 | + if (CONNECTED_REGEX.test(line)) { |
| 18 | + parts = CONNECTED_REGEX.exec(line); |
| 19 | + result[parts[1]] = { |
| 20 | + connected: true, |
| 21 | + modes: [] |
| 22 | + }; |
| 23 | + if (parts[2] && parts[3]) { |
| 24 | + result[parts[1]].width = parseInt(parts[2], 10); |
| 25 | + result[parts[1]].height = parseInt(parts[3], 10); |
| 26 | + } |
| 27 | + lastInterface = parts[1]; |
| 28 | + } else if (DISCONNECTED_REGEX.test(line)) { |
| 29 | + parts = DISCONNECTED_REGEX.exec(line); |
| 30 | + result[parts[1]] = { |
| 31 | + connected: false, |
| 32 | + modes: [] |
| 33 | + }; |
| 34 | + lastInterface = parts[1]; |
| 35 | + } else if (lastInterface && MODE_REGEX.test(line)) { |
| 36 | + parts = MODE_REGEX.exec(line); |
| 37 | + mode = { |
| 38 | + width: parseInt(parts[1], 10), |
| 39 | + height: parseInt(parts[2], 10), |
| 40 | + rate: parseFloat(parts[3], 10) |
| 41 | + }; |
| 42 | + if (parts[4] === '+' || parts[5] === '+') mode.native = true; |
| 43 | + if (parts[4] === '*' || parts[5] === '*') mode.current = true; |
| 44 | + result[lastInterface].modes.push(mode); |
| 45 | + } else { |
| 46 | + lastInterface = null; |
| 47 | + } |
| 48 | + }); |
| 49 | + return result; |
| 50 | +} |
0 commit comments