From 9020f645af347c2829b0bbdd79f2bbd1e2d5106f Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Thu, 7 Feb 2013 12:33:50 -0600 Subject: [PATCH] lazily set raw mode. --- lib/program.js | 70 +++++++++++++++++++++++++++----------------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/lib/program.js b/lib/program.js index e426848..0f7a03b 100644 --- a/lib/program.js +++ b/lib/program.js @@ -44,43 +44,42 @@ Program.prototype.term = function(is) { }; Program.prototype.listen = function() { - if (!this.input.isTTY || !this.output.isTTY) { - return; - } - var readline = require('readline') , self = this; - if (!this.input.isRaw) { - this.input.setRawMode(true); - - this.input.on('keypress', function(ch, key) { - key = key || 0; - if (key.ctrl && key.name === 'c') { - if (process.listeners('SIGINT').length) { - process.emit('SIGINT'); - } - if (self.listeners('SIGINT').length) { - self.emit('SIGINT'); - } - return; - } - self.emit('keypress', ch, key); - }); - - this.input.on('data', function(data) { - self.emit('data', data); - }); - - readline.emitKeypressEvents(this.input); - - this.input.resume(); + if (!this.input.isTTY || !this.output.isTTY) { + throw new Error('Not a terminal.'); } - this.output.on('resize', function() { - self.cols = self.output.columns; - self.rows = self.output.rows; - self.emit('resize'); + // Input + this.input.on('keypress', function(ch, key) { + key = key || 0; + if (key.ctrl && key.name === 'c') { + if (process.listeners('SIGINT').length) { + process.emit('SIGINT'); + } + if (self.listeners('SIGINT').length) { + self.emit('SIGINT'); + } + return; + } + self.emit('keypress', ch, key); + }); + + this.input.on('data', function(data) { + self.emit('data', data); + }); + + readline.emitKeypressEvents(this.input); + + this.on('newListener', function fn(type) { + if (type === 'keypress' || type === 'mouse') { + self.removeListener('newListener', fn); + if (!self.input.isRaw) { + self.input.setRawMode(true); + self.input.resume(); + } + } }); this.on('newListener', function fn(type) { @@ -92,6 +91,13 @@ Program.prototype.listen = function() { // self.bindMouse(); // self.bindResponse(); + + // Output + this.output.on('resize', function() { + self.cols = self.output.columns; + self.rows = self.output.rows; + self.emit('resize'); + }); }; // XTerm mouse events