"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseConsole = exports.SERVER_TERMINAL_WIDGET_ID = void 0;
var inversify_1 = require("inversify");
var widget_1 = require("@theia/core/lib/browser/widgets/widget");
var terminal_theme_service_1 = require("@theia/terminal/lib/browser/terminal-theme-service");
var terminal_preferences_1 = require("@theia/terminal/lib/browser/terminal-preferences");
var color_1 = require("../utils/color");
var promise_util_1 = require("@theia/core/lib/common/promise-util");
var fixed_length_buffer_1 = require("../utils/fixed-length-buffer");
var core_1 = require("@theia/core");
var asIs = function (x) { return x; };
var asPx = function (x) { return x + "px"; };
var preferenceIdToCss = {
    'terminal.integrated.fontFamily': { id: '--fontFamily', transform: asIs },
    'terminal.integrated.fontSize': { id: '--fontSize', transform: asPx },
    'terminal.integrated.fontWeight': { id: '--fontWeight', transform: asIs },
    'terminal.integrated.letterSpacing': { id: '--letterSpacing', transform: asPx },
    'terminal.integrated.lineHeight': { id: '--lineHeight', transform: asIs },
};
exports.SERVER_TERMINAL_WIDGET_ID = 'fxdk-server-terminal';
var BaseConsole = /** @class */ (function (_super) {
    __extends(BaseConsole, _super);
    function BaseConsole() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.scrollNodeDeferred = new promise_util_1.Deferred();
        _this.removeNodeQueue = [];
        _this.appendNodeQueue = [];
        _this.nodesBuffer = new fixed_length_buffer_1.FixedLengthBuffer(500);
        _this.raf = null;
        _this.consoleInitialized = false;
        _this.needsResize = true;
        _this.scrollOverride = false;
        return _this;
    }
    BaseConsole.prototype.init = function () {
        var _this = this;
        this.setup();
        this.scrollOptions = {};
        this.addClass('fxdk-console-widget');
        this.logNode = document.createElement('div');
        this.outputNode = document.createElement('div');
        this.outputStructuredNode = document.createElement('div');
        this.inputNode = this.createInputNode();
        this.toDispose.push(this.preferences.onPreferenceChanged(function (change) {
            if (change.preferenceName.indexOf('terminal.intergrated.') === -1) {
                return;
            }
            _this.updateCssVar(change.preferenceName);
        }));
        this.toDispose.push(this.nodesBuffer);
        this.nodesBuffer.onRemove(function (removedNode) {
            _this.removeNodeQueue.push(removedNode);
            _this.performRafActions();
        });
        this.toDispose.push(core_1.Disposable.create(function () {
            if (_this.raf !== null) {
                cancelAnimationFrame(_this.raf);
            }
        }));
    };
    BaseConsole.prototype.receiveStructuredMessage = function (_a) {
        var channel = _a.channel, message = _a.message;
        var _b = __read(color_1.rgbForKey(channel), 3), r = _b[0], g = _b[1], b = _b[2];
        var node = document.createElement('div');
        this.nodesBuffer.push(node);
        node.classList.add('structured-message');
        // Yes, ImGUI uses BGR but who would have known, right
        node.innerHTML = "\n      <div class=\"channel\" style=\"--channel-color: rgb(" + b + ", " + g + ", " + r + ")\">" + channel + "</div>\n      <div class=\"message\">" + color_1.colorizeString(message) + "</div>\n    ";
        this.appendNodeQueue.push(node);
        this.performRafActions();
    };
    BaseConsole.prototype.performRafActions = function () {
        var _this = this;
        if (this.raf === null) {
            this.raf = requestAnimationFrame(function () {
                var _a;
                _this.raf = null;
                if (_this.appendNodeQueue.length) {
                    var appendNodes = _this.appendNodeQueue;
                    _this.appendNodeQueue = [];
                    (_a = _this.outputStructuredNode).append.apply(_a, __spread(appendNodes));
                }
                if (_this.removeNodeQueue.length) {
                    var removedNodes = _this.removeNodeQueue;
                    _this.removeNodeQueue = [];
                    removedNodes.forEach(function (removedNode) {
                        _this.outputStructuredNode.removeChild(removedNode);
                    });
                }
                _this.updateScroll();
            });
        }
    };
    BaseConsole.prototype.getScrollContainer = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.scrollNodeDeferred.promise];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, this.logNode];
                }
            });
        });
    };
    BaseConsole.prototype.createInputNode = function () {
        var _this = this;
        var node = document.createElement('input');
        node.addEventListener('keydown', function (event) {
            if (event.key === 'Enter') {
                var command = node.value.trim();
                if (command) {
                    node.value = '';
                    _this.handleCommand(command);
                }
            }
        });
        return node;
    };
    BaseConsole.prototype.updateCssVar = function (preferenceId) {
        var cfg = preferenceIdToCss[preferenceId];
        if (!cfg) {
            return;
        }
        this.node.style.setProperty(cfg.id, cfg.transform(this.preferences[preferenceId]));
    };
    BaseConsole.prototype.populateCssVars = function () {
        var _this = this;
        Object.entries(preferenceIdToCss).forEach(function (_a) {
            var _b = __read(_a, 2), preferenceId = _b[0], cfg = _b[1];
            _this.node.style.setProperty(cfg.id, cfg.transform(_this.preferences[preferenceId]));
        });
    };
    BaseConsole.prototype.setBufferedOutput = function (output) {
        var _this = this;
        requestAnimationFrame(function () {
            _this.outputNode.innerHTML = output.split('\n').join('\n<br/>\n');
            _this.updateScroll();
        });
    };
    BaseConsole.prototype.clear = function () {
        var _a;
        this.outputNode.innerHTML = '';
        this.outputStructuredNode.innerHTML = '';
        (_a = this.scrollBar) === null || _a === void 0 ? void 0 : _a.update();
    };
    BaseConsole.prototype.onActivateRequest = function (msg) {
        _super.prototype.onActivateRequest.call(this, msg);
        this.inputNode.focus();
    };
    BaseConsole.prototype.onAfterShow = function (msg) {
        _super.prototype.onAfterShow.call(this, msg);
        this.update();
    };
    BaseConsole.prototype.onAfterAttach = function (msg) {
        _super.prototype.onAfterAttach.call(this, msg);
        this.update();
    };
    BaseConsole.prototype.onBeforeDetach = function (msg) {
        _super.prototype.onBeforeDetach.call(this, msg);
    };
    BaseConsole.prototype.onResize = function (msg) {
        _super.prototype.onResize.call(this, msg);
        this.update();
        this.updateScroll();
    };
    BaseConsole.prototype.open = function () {
        if (this.consoleInitialized) {
            return;
        }
        this.consoleInitialized = true;
        this.populateCssVars();
        this.logNode.classList.add('log');
        this.logNode.prepend(this.outputNode, this.outputStructuredNode);
        this.node.prepend(this.logNode);
        var cmdInputNode = document.createElement('div');
        cmdInputNode.innerHTML = '<span>cmd:</span>';
        cmdInputNode.classList.add('cmd-input');
        cmdInputNode.appendChild(this.inputNode);
        this.node.prepend(cmdInputNode);
        console.log('Created console dom tree');
        this.scrollNodeDeferred.resolve();
        this.setupEventListeners();
        this.initilizeConsole();
    };
    BaseConsole.prototype.onUpdateRequest = function (msg) {
        _super.prototype.onUpdateRequest.call(this, msg);
        if (!this.isVisible || !this.isAttached) {
            return;
        }
        this.open();
        this.updateScroll();
    };
    BaseConsole.prototype.updateScroll = function () {
        var _a;
        (_a = this.scrollBar) === null || _a === void 0 ? void 0 : _a.update();
        if (!this.scrollOverride) {
            var node = this.logNode;
            node.scrollTop = node.scrollHeight - node.clientHeight;
        }
    };
    BaseConsole.prototype.setupEventListeners = function () {
        var _this = this;
        var mouseDownHandler = function (e) {
            // Handling right-click
            if (e.button === 2) {
                e.preventDefault();
                e.stopPropagation();
                var selection = window.getSelection();
                if (!selection) {
                    return;
                }
                var selectionString = selection.toString();
                if (!selectionString) {
                    return;
                }
                document.execCommand('copy');
                selection.empty();
            }
        };
        this.logNode.addEventListener('mousedown', mouseDownHandler);
        this.toDispose.push(core_1.Disposable.create(function () { return _this.logNode.removeEventListener('mousedown', mouseDownHandler); }));
        this.toDispose.push(this.onScrollUp(function () { return _this.scrollOverride = true; }));
        this.toDispose.push(this.onScrollYReachEnd(function () { return _this.scrollOverride = false; }));
    };
    __decorate([
        inversify_1.inject(terminal_theme_service_1.TerminalThemeService),
        __metadata("design:type", terminal_theme_service_1.TerminalThemeService)
    ], BaseConsole.prototype, "themeService", void 0);
    __decorate([
        inversify_1.inject(terminal_preferences_1.TerminalPreferences),
        __metadata("design:type", Object)
    ], BaseConsole.prototype, "preferences", void 0);
    __decorate([
        inversify_1.postConstruct(),
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], BaseConsole.prototype, "init", null);
    BaseConsole = __decorate([
        inversify_1.injectable()
    ], BaseConsole);
    return BaseConsole;
}(widget_1.BaseWidget));
exports.BaseConsole = BaseConsole;
//# sourceMappingURL=base-console.js.map