diff --git a/Makefile b/Makefile index e51d7e9..aac341a 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ OBJS = $(SRCS:.c=.o) TARGET = wterm BUILD_DIR=./build CROSS_COMPILE = -LIBS = -lpthread +LIBS = -lpthread # -lcrypto -lssl USE_SQLITE3 ?= 0 WERROR ?= 0 diff --git a/src/cJSON.c b/src/cJSON.c index ca824f0..52791b7 100644 --- a/src/cJSON.c +++ b/src/cJSON.c @@ -32,25 +32,25 @@ #pragma GCC visibility push(default) #endif #if defined(_MSC_VER) -#pragma warning (push) +#pragma warning(push) /* disable warning about single line comments in system headers */ -#pragma warning (disable : 4001) +#pragma warning(disable : 4001) #endif -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include #ifdef ENABLE_LOCALES #include #endif #if defined(_MSC_VER) -#pragma warning (pop) +#pragma warning(pop) #endif #ifdef __GNUC__ #pragma GCC visibility pop @@ -69,7 +69,8 @@ #endif #define false ((cJSON_bool)0) -/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has + * been defined in math.h */ #ifndef isinf #define isinf(d) (isnan((d - d)) && !isnan(d)) #endif @@ -81,98 +82,85 @@ #ifdef _WIN32 #define NAN sqrt(-1.0) #else -#define NAN 0.0/0.0 +#define NAN 0.0 / 0.0 #endif #endif typedef struct { - const unsigned char *json; - size_t position; + const unsigned char *json; + size_t position; } error; -static error global_error = { NULL, 0 }; +static error global_error = {NULL, 0}; -CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) -{ - return (const char*) (global_error.json + global_error.position); +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) { + return (const char *)(global_error.json + global_error.position); } -CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) -{ - if (!cJSON_IsString(item)) - { - return NULL; - } +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON *const item) { + if (!cJSON_IsString(item)) { + return NULL; + } - return item->valuestring; + return item->valuestring; } -CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) -{ - if (!cJSON_IsNumber(item)) - { - return (double) NAN; - } +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON *const item) { + if (!cJSON_IsNumber(item)) { + return (double)NAN; + } - return item->valuedouble; + return item->valuedouble; } -/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ -#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 18) - #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +/* This is a safeguard to prevent copy-pasters from using incompatible C and + * header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || \ + (CJSON_VERSION_PATCH != 18) +#error cJSON.h and cJSON.c have different versions. Make sure that both have the same. #endif -CJSON_PUBLIC(const char*) cJSON_Version(void) -{ - static char version[15]; - sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); +CJSON_PUBLIC(const char *) cJSON_Version(void) { + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, + CJSON_VERSION_PATCH); - return version; + return version; } -/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ -static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) -{ - if ((string1 == NULL) || (string2 == NULL)) - { - return 1; - } +/* Case insensitive string comparison, doesn't consider two NULL pointers equal + * though */ +static int case_insensitive_strcmp(const unsigned char *string1, + const unsigned char *string2) { + if ((string1 == NULL) || (string2 == NULL)) { + return 1; + } - if (string1 == string2) - { - return 0; - } + if (string1 == string2) { + return 0; + } - for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) - { - if (*string1 == '\0') - { - return 0; - } + for (; tolower(*string1) == tolower(*string2); (void)string1++, string2++) { + if (*string1 == '\0') { + return 0; } + } - return tolower(*string1) - tolower(*string2); + return tolower(*string1) - tolower(*string2); } -typedef struct internal_hooks -{ - void *(CJSON_CDECL *allocate)(size_t size); - void (CJSON_CDECL *deallocate)(void *pointer); - void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +typedef struct internal_hooks { + void *(CJSON_CDECL *allocate)(size_t size); + void(CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); } internal_hooks; #if defined(_MSC_VER) -/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ -static void * CJSON_CDECL internal_malloc(size_t size) -{ - return malloc(size); -} -static void CJSON_CDECL internal_free(void *pointer) -{ - free(pointer); -} -static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) -{ - return realloc(pointer, size); +/* work around MSVC error C2322: '...' address of dllimport '...' is not static + */ +static void *CJSON_CDECL internal_malloc(size_t size) { return malloc(size); } +static void CJSON_CDECL internal_free(void *pointer) { free(pointer); } +static void *CJSON_CDECL internal_realloc(void *pointer, size_t size) { + return realloc(pointer, size); } #else #define internal_malloc malloc @@ -183,3009 +171,2695 @@ static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) /* strlen of character literals resolved at compile time */ #define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) -static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; +static internal_hooks global_hooks = {internal_malloc, internal_free, + internal_realloc}; -static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) -{ - size_t length = 0; - unsigned char *copy = NULL; +static unsigned char *cJSON_strdup(const unsigned char *string, + const internal_hooks *const hooks) { + size_t length = 0; + unsigned char *copy = NULL; - if (string == NULL) - { - return NULL; - } + if (string == NULL) { + return NULL; + } - length = strlen((const char*)string) + sizeof(""); - copy = (unsigned char*)hooks->allocate(length); - if (copy == NULL) - { - return NULL; - } - memcpy(copy, string, length); + length = strlen((const char *)string) + sizeof(""); + copy = (unsigned char *)hooks->allocate(length); + if (copy == NULL) { + return NULL; + } + memcpy(copy, string, length); - return copy; + return copy; } -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) -{ - if (hooks == NULL) - { - /* Reset hooks */ - global_hooks.allocate = malloc; - global_hooks.deallocate = free; - global_hooks.reallocate = realloc; - return; - } - +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks) { + if (hooks == NULL) { + /* Reset hooks */ global_hooks.allocate = malloc; - if (hooks->malloc_fn != NULL) - { - global_hooks.allocate = hooks->malloc_fn; - } - global_hooks.deallocate = free; - if (hooks->free_fn != NULL) - { - global_hooks.deallocate = hooks->free_fn; - } + global_hooks.reallocate = realloc; + return; + } - /* use realloc only if both free and malloc are used */ - global_hooks.reallocate = NULL; - if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) - { - global_hooks.reallocate = realloc; - } + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) { + global_hooks.reallocate = realloc; + } } /* Internal constructor. */ -static cJSON *cJSON_New_Item(const internal_hooks * const hooks) -{ - cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); - if (node) - { - memset(node, '\0', sizeof(cJSON)); - } +static cJSON *cJSON_New_Item(const internal_hooks *const hooks) { + cJSON *node = (cJSON *)hooks->allocate(sizeof(cJSON)); + if (node) { + memset(node, '\0', sizeof(cJSON)); + } - return node; + return node; } /* Delete a cJSON structure. */ -CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) -{ - cJSON *next = NULL; - while (item != NULL) - { - next = item->next; - if (!(item->type & cJSON_IsReference) && (item->child != NULL)) - { - cJSON_Delete(item->child); - } - if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) - { - global_hooks.deallocate(item->valuestring); - item->valuestring = NULL; - } - if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) - { - global_hooks.deallocate(item->string); - item->string = NULL; - } - global_hooks.deallocate(item); - item = next; +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) { + cJSON *next = NULL; + while (item != NULL) { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) { + cJSON_Delete(item->child); } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) { + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { + global_hooks.deallocate(item->string); + item->string = NULL; + } + global_hooks.deallocate(item); + item = next; + } } /* get the decimal point character of the current locale */ -static unsigned char get_decimal_point(void) -{ +static unsigned char get_decimal_point(void) { #ifdef ENABLE_LOCALES - struct lconv *lconv = localeconv(); - return (unsigned char) lconv->decimal_point[0]; + struct lconv *lconv = localeconv(); + return (unsigned char)lconv->decimal_point[0]; #else - return '.'; + return '.'; #endif } -typedef struct -{ - const unsigned char *content; - size_t length; - size_t offset; - size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ - internal_hooks hooks; +typedef struct { + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the + current offset. */ + internal_hooks hooks; } parse_buffer; -/* check if the given size is left to read in a given parse buffer (starting with 1) */ -#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the given size is left to read in a given parse buffer (starting + * with 1) */ +#define can_read(buffer, size) \ + ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) /* check if the buffer can be accessed at the given index (starting with 0) */ -#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) -#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +#define can_access_at_index(buffer, index) \ + ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) \ + (!can_access_at_index(buffer, index)) /* get a pointer to the buffer at the position */ #define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) -/* Parse the input text to generate a number, and populate the result into item. */ -static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) -{ - double number = 0; - unsigned char *after_end = NULL; - unsigned char *number_c_string; - unsigned char decimal_point = get_decimal_point(); - size_t i = 0; - size_t number_string_length = 0; - cJSON_bool has_decimal_point = false; +/* Parse the input text to generate a number, and populate the result into item. + */ +static cJSON_bool parse_number(cJSON *const item, + parse_buffer *const input_buffer) { + double number = 0; + unsigned char *after_end = NULL; + unsigned char *number_c_string; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + size_t number_string_length = 0; + cJSON_bool has_decimal_point = false; - if ((input_buffer == NULL) || (input_buffer->content == NULL)) - { - return false; - } + if ((input_buffer == NULL) || (input_buffer->content == NULL)) { + return false; + } - /* copy the number into a temporary buffer and replace '.' with the decimal point - * of the current locale (for strtod) - * This also takes care of '\0' not necessarily being available for marking the end of the input */ - for (i = 0; can_access_at_index(input_buffer, i); i++) - { - switch (buffer_at_offset(input_buffer)[i]) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case '+': - case '-': - case 'e': - case 'E': - number_string_length++; - break; + /* copy the number into a temporary buffer and replace '.' with the decimal + * point of the current locale (for strtod) This also takes care of '\0' not + * necessarily being available for marking the end of the input */ + for (i = 0; can_access_at_index(input_buffer, i); i++) { + switch (buffer_at_offset(input_buffer)[i]) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_string_length++; + break; - case '.': - number_string_length++; - has_decimal_point = true; - break; + case '.': + number_string_length++; + has_decimal_point = true; + break; - default: - goto loop_end; - } + default: + goto loop_end; } + } loop_end: - /* malloc for temporary buffer, add 1 for '\0' */ - number_c_string = (unsigned char *) input_buffer->hooks.allocate(number_string_length + 1); - if (number_c_string == NULL) - { - return false; /* allocation failure */ + /* malloc for temporary buffer, add 1 for '\0' */ + number_c_string = + (unsigned char *)input_buffer->hooks.allocate(number_string_length + 1); + if (number_c_string == NULL) { + return false; /* allocation failure */ + } + + memcpy(number_c_string, buffer_at_offset(input_buffer), number_string_length); + number_c_string[number_string_length] = '\0'; + + if (has_decimal_point) { + for (i = 0; i < number_string_length; i++) { + if (number_c_string[i] == '.') { + /* replace '.' with the decimal point of the current locale (for strtod) + */ + number_c_string[i] = decimal_point; + } } + } - memcpy(number_c_string, buffer_at_offset(input_buffer), number_string_length); - number_c_string[number_string_length] = '\0'; - - if (has_decimal_point) - { - for (i = 0; i < number_string_length; i++) - { - if (number_c_string[i] == '.') - { - /* replace '.' with the decimal point of the current locale (for strtod) */ - number_c_string[i] = decimal_point; - } - } - } - - number = strtod((const char*)number_c_string, (char**)&after_end); - if (number_c_string == after_end) - { - /* free the temporary buffer */ - input_buffer->hooks.deallocate(number_c_string); - return false; /* parse_error */ - } - - item->valuedouble = number; - - /* use saturation in case of overflow */ - if (number >= INT_MAX) - { - item->valueint = INT_MAX; - } - else if (number <= (double)INT_MIN) - { - item->valueint = INT_MIN; - } - else - { - item->valueint = (int)number; - } - - item->type = cJSON_Number; - - input_buffer->offset += (size_t)(after_end - number_c_string); + number = strtod((const char *)number_c_string, (char **)&after_end); + if (number_c_string == after_end) { /* free the temporary buffer */ input_buffer->hooks.deallocate(number_c_string); - return true; + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) { + item->valueint = INT_MAX; + } else if (number <= (double)INT_MIN) { + item->valueint = INT_MIN; + } else { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return true; } -/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ -CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) -{ - if (number >= INT_MAX) - { - object->valueint = INT_MAX; - } - else if (number <= (double)INT_MIN) - { - object->valueint = INT_MIN; - } - else - { - object->valueint = (int)number; - } +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or + * double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) { + if (number >= INT_MAX) { + object->valueint = INT_MAX; + } else if (number <= (double)INT_MIN) { + object->valueint = INT_MIN; + } else { + object->valueint = (int)number; + } - return object->valuedouble = number; + return object->valuedouble = number; } -/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */ -CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) -{ - char *copy = NULL; - size_t v1_len; - size_t v2_len; - /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ - if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) - { - return NULL; - } - /* return NULL if the object is corrupted or valuestring is NULL */ - if (object->valuestring == NULL || valuestring == NULL) - { - return NULL; - } +/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an + * error and return NULL */ +CJSON_PUBLIC(char *) +cJSON_SetValuestring(cJSON *object, const char *valuestring) { + char *copy = NULL; + size_t v1_len; + size_t v2_len; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not + * set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || + (object->type & cJSON_IsReference)) { + return NULL; + } + /* return NULL if the object is corrupted or valuestring is NULL */ + if (object->valuestring == NULL || valuestring == NULL) { + return NULL; + } - v1_len = strlen(valuestring); - v2_len = strlen(object->valuestring); + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); - if (v1_len <= v2_len) - { - /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ - if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) - { - return NULL; - } - strcpy(object->valuestring, valuestring); - return object->valuestring; + if (v1_len <= v2_len) { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 + * or Y2 < X1 */ + if (!(valuestring + v1_len < object->valuestring || + object->valuestring + v2_len < valuestring)) { + return NULL; } - copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); - if (copy == NULL) - { - return NULL; - } - if (object->valuestring != NULL) - { - cJSON_free(object->valuestring); - } - object->valuestring = copy; + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = + (char *)cJSON_strdup((const unsigned char *)valuestring, &global_hooks); + if (copy == NULL) { + return NULL; + } + if (object->valuestring != NULL) { + cJSON_free(object->valuestring); + } + object->valuestring = copy; - return copy; + return copy; } -typedef struct -{ - unsigned char *buffer; - size_t length; - size_t offset; - size_t depth; /* current nesting depth (for formatted printing) */ - cJSON_bool noalloc; - cJSON_bool format; /* is this print a formatted print */ - internal_hooks hooks; +typedef struct { + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; } printbuffer; /* realloc printbuffer if necessary to have at least "needed" bytes more */ -static unsigned char* ensure(printbuffer * const p, size_t needed) -{ - unsigned char *newbuffer = NULL; - size_t newsize = 0; +static unsigned char *ensure(printbuffer *const p, size_t needed) { + unsigned char *newbuffer = NULL; + size_t newsize = 0; - if ((p == NULL) || (p->buffer == NULL)) - { - return NULL; + if ((p == NULL) || (p->buffer == NULL)) { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) { + newsize = INT_MAX; + } else { + return NULL; + } + } else { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) { + /* reallocate with realloc if available */ + newbuffer = (unsigned char *)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } else { + /* otherwise reallocate manually */ + newbuffer = (unsigned char *)p->hooks.allocate(newsize); + if (!newbuffer) { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; } - if ((p->length > 0) && (p->offset >= p->length)) - { - /* make sure that offset is valid */ - return NULL; - } + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; - if (needed > INT_MAX) - { - /* sizes bigger than INT_MAX are currently not supported */ - return NULL; - } - - needed += p->offset + 1; - if (needed <= p->length) - { - return p->buffer + p->offset; - } - - if (p->noalloc) { - return NULL; - } - - /* calculate new buffer size */ - if (needed > (INT_MAX / 2)) - { - /* overflow of int, use INT_MAX if possible */ - if (needed <= INT_MAX) - { - newsize = INT_MAX; - } - else - { - return NULL; - } - } - else - { - newsize = needed * 2; - } - - if (p->hooks.reallocate != NULL) - { - /* reallocate with realloc if available */ - newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); - if (newbuffer == NULL) - { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - } - else - { - /* otherwise reallocate manually */ - newbuffer = (unsigned char*)p->hooks.allocate(newsize); - if (!newbuffer) - { - p->hooks.deallocate(p->buffer); - p->length = 0; - p->buffer = NULL; - - return NULL; - } - - memcpy(newbuffer, p->buffer, p->offset + 1); - p->hooks.deallocate(p->buffer); - } - p->length = newsize; - p->buffer = newbuffer; - - return newbuffer + p->offset; + return newbuffer + p->offset; } -/* calculate the new length of the string in a printbuffer and update the offset */ -static void update_offset(printbuffer * const buffer) -{ - const unsigned char *buffer_pointer = NULL; - if ((buffer == NULL) || (buffer->buffer == NULL)) - { - return; - } - buffer_pointer = buffer->buffer + buffer->offset; +/* calculate the new length of the string in a printbuffer and update the offset + */ +static void update_offset(printbuffer *const buffer) { + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; - buffer->offset += strlen((const char*)buffer_pointer); + buffer->offset += strlen((const char *)buffer_pointer); } /* securely comparison of floating-point variables */ -static cJSON_bool compare_double(double a, double b) -{ - double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); - return (fabs(a - b) <= maxVal * DBL_EPSILON); +static cJSON_bool compare_double(double a, double b) { + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); } /* Render the number nicely from the given item into a string. */ -static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output_pointer = NULL; - double d = item->valuedouble; - int length = 0; - size_t i = 0; - unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ - unsigned char decimal_point = get_decimal_point(); - double test = 0.0; +static cJSON_bool print_number(const cJSON *const item, + printbuffer *const output_buffer) { + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = { + 0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; - if (output_buffer == NULL) - { - return false; + if (output_buffer == NULL) { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) { + length = sprintf((char *)number_buffer, "null"); + } else if (d == (double)item->valueint) { + length = sprintf((char *)number_buffer, "%d", item->valueint); + } else { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits + */ + length = sprintf((char *)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char *)number_buffer, "%lg", &test) != 1) || + !compare_double((double)test, d)) { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char *)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) { + if (number_buffer[i] == decimal_point) { + output_pointer[i] = '.'; + continue; } - /* This checks for NaN and Infinity */ - if (isnan(d) || isinf(d)) - { - length = sprintf((char*)number_buffer, "null"); - } - else if(d == (double)item->valueint) - { - length = sprintf((char*)number_buffer, "%d", item->valueint); - } - else - { - /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ - length = sprintf((char*)number_buffer, "%1.15g", d); + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; - /* Check whether the original double can be recovered */ - if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) - { - /* If not, print with 17 decimal places of precision */ - length = sprintf((char*)number_buffer, "%1.17g", d); - } - } + output_buffer->offset += (size_t)length; - /* sprintf failed or buffer overrun occurred */ - if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) - { - return false; - } - - /* reserve appropriate space in the output */ - output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); - if (output_pointer == NULL) - { - return false; - } - - /* copy the printed number to the output and replace locale - * dependent decimal point with '.' */ - for (i = 0; i < ((size_t)length); i++) - { - if (number_buffer[i] == decimal_point) - { - output_pointer[i] = '.'; - continue; - } - - output_pointer[i] = number_buffer[i]; - } - output_pointer[i] = '\0'; - - output_buffer->offset += (size_t)length; - - return true; + return true; } /* parse 4 digit hexadecimal number */ -static unsigned parse_hex4(const unsigned char * const input) -{ - unsigned int h = 0; - size_t i = 0; +static unsigned parse_hex4(const unsigned char *const input) { + unsigned int h = 0; + size_t i = 0; - for (i = 0; i < 4; i++) + for (i = 0; i < 4; i++) { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) { + h += (unsigned int)input[i] - '0'; + } else if ((input[i] >= 'A') && (input[i] <= 'F')) { + h += (unsigned int)10 + input[i] - 'A'; + } else if ((input[i] >= 'a') && (input[i] <= 'f')) { + h += (unsigned int)10 + input[i] - 'a'; + } else /* invalid */ { - /* parse digit */ - if ((input[i] >= '0') && (input[i] <= '9')) - { - h += (unsigned int) input[i] - '0'; - } - else if ((input[i] >= 'A') && (input[i] <= 'F')) - { - h += (unsigned int) 10 + input[i] - 'A'; - } - else if ((input[i] >= 'a') && (input[i] <= 'f')) - { - h += (unsigned int) 10 + input[i] - 'a'; - } - else /* invalid */ - { - return 0; - } - - if (i < 3) - { - /* shift left to make place for the next nibble */ - h = h << 4; - } + return 0; } - return h; + if (i < 3) { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; } /* converts a UTF-16 literal to UTF-8 * A literal can be one or two sequences of the form \uXXXX */ -static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) -{ - long unsigned int codepoint = 0; - unsigned int first_code = 0; - const unsigned char *first_sequence = input_pointer; - unsigned char utf8_length = 0; - unsigned char utf8_position = 0; - unsigned char sequence_length = 0; - unsigned char first_byte_mark = 0; +static unsigned char +utf16_literal_to_utf8(const unsigned char *const input_pointer, + const unsigned char *const input_end, + unsigned char **output_pointer) { + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; - if ((input_end - first_sequence) < 6) - { - /* input ends unexpectedly */ - goto fail; + if ((input_end - first_sequence) < 6) { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) { + /* input ends unexpectedly */ + goto fail; } - /* get the first utf16 sequence */ - first_code = parse_hex4(first_sequence + 2); + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) { + /* missing second half of the surrogate pair */ + goto fail; + } + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); /* check that the code is valid */ - if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) - { - goto fail; + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) { + /* invalid second half of the surrogate pair */ + goto fail; } - /* UTF16 surrogate pair */ - if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) - { - const unsigned char *second_sequence = first_sequence + 6; - unsigned int second_code = 0; - sequence_length = 12; /* \uXXXX\uXXXX */ + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = + 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } else { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } - if ((input_end - second_sequence) < 6) - { - /* input ends unexpectedly */ - goto fail; - } + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } else if (codepoint < 0x800) { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } else if (codepoint < 0x10000) { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } else if (codepoint <= 0x10FFFF) { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } else { + /* invalid unicode codepoint */ + goto fail; + } - if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) - { - /* missing second half of the surrogate pair */ - goto fail; - } + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; + utf8_position--) { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = + (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) { + (*output_pointer)[0] = + (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } else { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } - /* get the second utf16 sequence */ - second_code = parse_hex4(second_sequence + 2); - /* check that the code is valid */ - if ((second_code < 0xDC00) || (second_code > 0xDFFF)) - { - /* invalid second half of the surrogate pair */ - goto fail; - } + *output_pointer += utf8_length; - - /* calculate the unicode codepoint from the surrogate pair */ - codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); - } - else - { - sequence_length = 6; /* \uXXXX */ - codepoint = first_code; - } - - /* encode as UTF-8 - * takes at maximum 4 bytes to encode: - * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ - if (codepoint < 0x80) - { - /* normal ascii, encoding 0xxxxxxx */ - utf8_length = 1; - } - else if (codepoint < 0x800) - { - /* two bytes, encoding 110xxxxx 10xxxxxx */ - utf8_length = 2; - first_byte_mark = 0xC0; /* 11000000 */ - } - else if (codepoint < 0x10000) - { - /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ - utf8_length = 3; - first_byte_mark = 0xE0; /* 11100000 */ - } - else if (codepoint <= 0x10FFFF) - { - /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ - utf8_length = 4; - first_byte_mark = 0xF0; /* 11110000 */ - } - else - { - /* invalid unicode codepoint */ - goto fail; - } - - /* encode as utf8 */ - for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) - { - /* 10xxxxxx */ - (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); - codepoint >>= 6; - } - /* encode first byte */ - if (utf8_length > 1) - { - (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); - } - else - { - (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); - } - - *output_pointer += utf8_length; - - return sequence_length; + return sequence_length; fail: - return 0; + return 0; } /* Parse the input text into an unescaped cinput, and populate item. */ -static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) -{ - const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; - const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; - unsigned char *output_pointer = NULL; - unsigned char *output = NULL; +static cJSON_bool parse_string(cJSON *const item, + parse_buffer *const input_buffer) { + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; - /* not a string */ - if (buffer_at_offset(input_buffer)[0] != '\"') - { + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while ( + ((size_t)(input_end - input_buffer->content) < input_buffer->length) && + (*input_end != '\"')) { + /* is escape sequence */ + if (input_end[0] == '\\') { + if ((size_t)(input_end + 1 - input_buffer->content) >= + input_buffer->length) { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || + (*input_end != '\"')) { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = + (size_t)(input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char *)input_buffer->hooks.allocate(allocation_length + + sizeof("")); + if (output == NULL) { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) { + if (*input_pointer != '\\') { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) { goto fail; + } + + switch (input_pointer[1]) { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = + utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; } + } - { - /* calculate approximate size of the output (overestimate) */ - size_t allocation_length = 0; - size_t skipped_bytes = 0; - while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) - { - /* is escape sequence */ - if (input_end[0] == '\\') - { - if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) - { - /* prevent buffer overflow when last input character is a backslash */ - goto fail; - } - skipped_bytes++; - input_end++; - } - input_end++; - } - if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) - { - goto fail; /* string ended unexpectedly */ - } + /* zero terminate the output */ + *output_pointer = '\0'; - /* This is at most how much we need for the output */ - allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; - output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); - if (output == NULL) - { - goto fail; /* allocation failure */ - } - } + item->type = cJSON_String; + item->valuestring = (char *)output; - output_pointer = output; - /* loop through the string literal */ - while (input_pointer < input_end) - { - if (*input_pointer != '\\') - { - *output_pointer++ = *input_pointer++; - } - /* escape sequence */ - else - { - unsigned char sequence_length = 2; - if ((input_end - input_pointer) < 1) - { - goto fail; - } + input_buffer->offset = (size_t)(input_end - input_buffer->content); + input_buffer->offset++; - switch (input_pointer[1]) - { - case 'b': - *output_pointer++ = '\b'; - break; - case 'f': - *output_pointer++ = '\f'; - break; - case 'n': - *output_pointer++ = '\n'; - break; - case 'r': - *output_pointer++ = '\r'; - break; - case 't': - *output_pointer++ = '\t'; - break; - case '\"': - case '\\': - case '/': - *output_pointer++ = input_pointer[1]; - break; - - /* UTF-16 literal */ - case 'u': - sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); - if (sequence_length == 0) - { - /* failed to convert UTF16-literal to UTF-8 */ - goto fail; - } - break; - - default: - goto fail; - } - input_pointer += sequence_length; - } - } - - /* zero terminate the output */ - *output_pointer = '\0'; - - item->type = cJSON_String; - item->valuestring = (char*)output; - - input_buffer->offset = (size_t) (input_end - input_buffer->content); - input_buffer->offset++; - - return true; + return true; fail: - if (output != NULL) - { - input_buffer->hooks.deallocate(output); - output = NULL; - } + if (output != NULL) { + input_buffer->hooks.deallocate(output); + output = NULL; + } - if (input_pointer != NULL) - { - input_buffer->offset = (size_t)(input_pointer - input_buffer->content); - } + if (input_pointer != NULL) { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } - return false; + return false; } /* Render the cstring provided to an escaped version that can be printed. */ -static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) -{ - const unsigned char *input_pointer = NULL; - unsigned char *output = NULL; - unsigned char *output_pointer = NULL; - size_t output_length = 0; - /* numbers of additional characters needed for escaping */ - size_t escape_characters = 0; +static cJSON_bool print_string_ptr(const unsigned char *const input, + printbuffer *const output_buffer) { + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; - if (output_buffer == NULL) - { - return false; + if (output_buffer == NULL) { + return false; + } + + /* empty string */ + if (input == NULL) { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) { + return false; } + strcpy((char *)output, "\"\""); - /* empty string */ - if (input == NULL) - { - output = ensure(output_buffer, sizeof("\"\"")); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "\"\""); + return true; + } - return true; + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) { + switch (*input_pointer) { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; } + } + output_length = (size_t)(input_pointer - input) + escape_characters; - /* set "flag" to 1 if something needs to be escaped */ - for (input_pointer = input; *input_pointer; input_pointer++) - { - switch (*input_pointer) - { - case '\"': - case '\\': - case '\b': - case '\f': - case '\n': - case '\r': - case '\t': - /* one character escape sequence */ - escape_characters++; - break; - default: - if (*input_pointer < 32) - { - /* UTF-16 escape sequence uXXXX */ - escape_characters += 5; - } - break; - } - } - output_length = (size_t)(input_pointer - input) + escape_characters; - - output = ensure(output_buffer, output_length + sizeof("\"\"")); - if (output == NULL) - { - return false; - } - - /* no characters have to be escaped */ - if (escape_characters == 0) - { - output[0] = '\"'; - memcpy(output + 1, input, output_length); - output[output_length + 1] = '\"'; - output[output_length + 2] = '\0'; - - return true; - } + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) { + return false; + } + /* no characters have to be escaped */ + if (escape_characters == 0) { output[0] = '\"'; - output_pointer = output + 1; - /* copy the string */ - for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) - { - if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) - { - /* normal character, copy */ - *output_pointer = *input_pointer; - } - else - { - /* character needs to be escaped */ - *output_pointer++ = '\\'; - switch (*input_pointer) - { - case '\\': - *output_pointer = '\\'; - break; - case '\"': - *output_pointer = '\"'; - break; - case '\b': - *output_pointer = 'b'; - break; - case '\f': - *output_pointer = 'f'; - break; - case '\n': - *output_pointer = 'n'; - break; - case '\r': - *output_pointer = 'r'; - break; - case '\t': - *output_pointer = 't'; - break; - default: - /* escape and print as unicode codepoint */ - sprintf((char*)output_pointer, "u%04x", *input_pointer); - output_pointer += 4; - break; - } - } - } + memcpy(output + 1, input, output_length); output[output_length + 1] = '\"'; output[output_length + 2] = '\0'; return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; + (void)input_pointer++, output_pointer++) { + if ((*input_pointer > 31) && (*input_pointer != '\"') && + (*input_pointer != '\\')) { + /* normal character, copy */ + *output_pointer = *input_pointer; + } else { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char *)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; } /* Invoke print_string_ptr (which is useful) on an item. */ -static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) -{ - return print_string_ptr((unsigned char*)item->valuestring, p); +static cJSON_bool print_string(const cJSON *const item, printbuffer *const p) { + return print_string_ptr((unsigned char *)item->valuestring, p); } /* Predeclare these prototypes. */ -static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); -static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); -static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); -static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); -static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); -static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_value(cJSON *const item, + parse_buffer *const input_buffer); +static cJSON_bool print_value(const cJSON *const item, + printbuffer *const output_buffer); +static cJSON_bool parse_array(cJSON *const item, + parse_buffer *const input_buffer); +static cJSON_bool print_array(const cJSON *const item, + printbuffer *const output_buffer); +static cJSON_bool parse_object(cJSON *const item, + parse_buffer *const input_buffer); +static cJSON_bool print_object(const cJSON *const item, + printbuffer *const output_buffer); /* Utility to jump whitespace and cr/lf */ -static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) -{ - if ((buffer == NULL) || (buffer->content == NULL)) - { - return NULL; - } - - if (cannot_access_at_index(buffer, 0)) - { - return buffer; - } - - while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) - { - buffer->offset++; - } - - if (buffer->offset == buffer->length) - { - buffer->offset--; - } +static parse_buffer *buffer_skip_whitespace(parse_buffer *const buffer) { + if ((buffer == NULL) || (buffer->content == NULL)) { + return NULL; + } + if (cannot_access_at_index(buffer, 0)) { return buffer; + } + + while (can_access_at_index(buffer, 0) && + (buffer_at_offset(buffer)[0] <= 32)) { + buffer->offset++; + } + + if (buffer->offset == buffer->length) { + buffer->offset--; + } + + return buffer; } /* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ -static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) -{ - if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) - { - return NULL; - } +static parse_buffer *skip_utf8_bom(parse_buffer *const buffer) { + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) { + return NULL; + } - if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) - { - buffer->offset += 3; - } + if (can_access_at_index(buffer, 4) && + (strncmp((const char *)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == + 0)) { + buffer->offset += 3; + } - return buffer; + return buffer; } -CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) -{ - size_t buffer_length; +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithOpts(const char *value, const char **return_parse_end, + cJSON_bool require_null_terminated) { + size_t buffer_length; - if (NULL == value) - { - return NULL; - } + if (NULL == value) { + return NULL; + } - /* Adding null character size due to require_null_terminated. */ - buffer_length = strlen(value) + sizeof(""); + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); - return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, + require_null_terminated); } /* Parse an object - create a new root, and populate. */ -CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) -{ - parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; - cJSON *item = NULL; +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, + const char **return_parse_end, + cJSON_bool require_null_terminated) { + parse_buffer buffer = {0, 0, 0, 0, {0, 0, 0}}; + cJSON *item = NULL; - /* reset error position */ - global_error.json = NULL; - global_error.position = 0; + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; - if (value == NULL || 0 == buffer_length) - { - goto fail; + if (value == NULL || 0 == buffer_length) { + goto fail; + } + + buffer.content = (const unsigned char *)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then + * check for a null terminator */ + if (require_null_terminated) { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || + buffer_at_offset(&buffer)[0] != '\0') { + goto fail; } + } + if (return_parse_end) { + *return_parse_end = (const char *)buffer_at_offset(&buffer); + } - buffer.content = (const unsigned char*)value; - buffer.length = buffer_length; - buffer.offset = 0; - buffer.hooks = global_hooks; - - item = cJSON_New_Item(&global_hooks); - if (item == NULL) /* memory fail */ - { - goto fail; - } - - if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) - { - /* parse failure. ep is set. */ - goto fail; - } - - /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ - if (require_null_terminated) - { - buffer_skip_whitespace(&buffer); - if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') - { - goto fail; - } - } - if (return_parse_end) - { - *return_parse_end = (const char*)buffer_at_offset(&buffer); - } - - return item; + return item; fail: - if (item != NULL) - { - cJSON_Delete(item); + if (item != NULL) { + cJSON_Delete(item); + } + + if (value != NULL) { + error local_error; + local_error.json = (const unsigned char *)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) { + local_error.position = buffer.offset; + } else if (buffer.length > 0) { + local_error.position = buffer.length - 1; } - if (value != NULL) - { - error local_error; - local_error.json = (const unsigned char*)value; - local_error.position = 0; - - if (buffer.offset < buffer.length) - { - local_error.position = buffer.offset; - } - else if (buffer.length > 0) - { - local_error.position = buffer.length - 1; - } - - if (return_parse_end != NULL) - { - *return_parse_end = (const char*)local_error.json + local_error.position; - } - - global_error = local_error; + if (return_parse_end != NULL) { + *return_parse_end = (const char *)local_error.json + local_error.position; } - return NULL; + global_error = local_error; + } + + return NULL; } /* Default options for cJSON_Parse */ -CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) -{ - return cJSON_ParseWithOpts(value, 0, 0); +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) { + return cJSON_ParseWithOpts(value, 0, 0); } -CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) -{ - return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithLength(const char *value, size_t buffer_length) { + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); } #define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) -static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) -{ - static const size_t default_buffer_size = 256; - printbuffer buffer[1]; - unsigned char *printed = NULL; +static unsigned char *print(const cJSON *const item, cJSON_bool format, + const internal_hooks *const hooks) { + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; - memset(buffer, 0, sizeof(buffer)); + memset(buffer, 0, sizeof(buffer)); - /* create buffer */ - buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); - buffer->length = default_buffer_size; - buffer->format = format; - buffer->hooks = *hooks; - if (buffer->buffer == NULL) - { - goto fail; + /* create buffer */ + buffer->buffer = (unsigned char *)hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) { + printed = + (unsigned char *)hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; } - - /* print the value */ - if (!print_value(item, buffer)) - { - goto fail; + buffer->buffer = NULL; + } else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char *)hooks->allocate(buffer->offset + 1); + if (printed == NULL) { + goto fail; } - update_offset(buffer); + memcpy(printed, buffer->buffer, + cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ - /* check if reallocate is available */ - if (hooks->reallocate != NULL) - { - printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); - if (printed == NULL) { - goto fail; - } - buffer->buffer = NULL; - } - else /* otherwise copy the JSON over to a new buffer */ - { - printed = (unsigned char*) hooks->allocate(buffer->offset + 1); - if (printed == NULL) - { - goto fail; - } - memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); - printed[buffer->offset] = '\0'; /* just to be sure */ + /* free the buffer */ + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } - /* free the buffer */ - hooks->deallocate(buffer->buffer); - buffer->buffer = NULL; - } - - return printed; + return printed; fail: - if (buffer->buffer != NULL) - { - hooks->deallocate(buffer->buffer); - buffer->buffer = NULL; - } + if (buffer->buffer != NULL) { + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } - if (printed != NULL) - { - hooks->deallocate(printed); - printed = NULL; - } + if (printed != NULL) { + hooks->deallocate(printed); + printed = NULL; + } - return NULL; + return NULL; } /* Render a cJSON item/entity/structure to text. */ -CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) -{ - return (char*)print(item, true, &global_hooks); +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) { + return (char *)print(item, true, &global_hooks); } -CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) -{ - return (char*)print(item, false, &global_hooks); +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) { + return (char *)print(item, false, &global_hooks); } -CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) -{ - printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; +CJSON_PUBLIC(char *) +cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) { + printbuffer p = {0, 0, 0, 0, 0, 0, {0, 0, 0}}; - if (prebuffer < 0) - { - return NULL; - } + if (prebuffer < 0) { + return NULL; + } - p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); - if (!p.buffer) - { - return NULL; - } + p.buffer = (unsigned char *)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) { + return NULL; + } - p.length = (size_t)prebuffer; - p.offset = 0; - p.noalloc = false; - p.format = fmt; - p.hooks = global_hooks; + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; - if (!print_value(item, &p)) - { - global_hooks.deallocate(p.buffer); - p.buffer = NULL; - return NULL; - } + if (!print_value(item, &p)) { + global_hooks.deallocate(p.buffer); + p.buffer = NULL; + return NULL; + } - return (char*)p.buffer; + return (char *)p.buffer; } -CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) -{ - printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; +CJSON_PUBLIC(cJSON_bool) +cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, + const cJSON_bool format) { + printbuffer p = {0, 0, 0, 0, 0, 0, {0, 0, 0}}; - if ((length < 0) || (buffer == NULL)) - { - return false; - } + if ((length < 0) || (buffer == NULL)) { + return false; + } - p.buffer = (unsigned char*)buffer; - p.length = (size_t)length; - p.offset = 0; - p.noalloc = true; - p.format = format; - p.hooks = global_hooks; + p.buffer = (unsigned char *)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; - return print_value(item, &p); + return print_value(item, &p); } /* Parser core - when encountering text, process appropriately. */ -static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) -{ - if ((input_buffer == NULL) || (input_buffer->content == NULL)) - { - return false; /* no input */ - } +static cJSON_bool parse_value(cJSON *const item, + parse_buffer *const input_buffer) { + if ((input_buffer == NULL) || (input_buffer->content == NULL)) { + return false; /* no input */ + } - /* parse the different types of values */ - /* null */ - if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) - { - item->type = cJSON_NULL; - input_buffer->offset += 4; - return true; - } - /* false */ - if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) - { - item->type = cJSON_False; - input_buffer->offset += 5; - return true; - } - /* true */ - if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) - { - item->type = cJSON_True; - item->valueint = 1; - input_buffer->offset += 4; - return true; - } - /* string */ - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) - { - return parse_string(item, input_buffer); - } - /* number */ - if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) - { - return parse_number(item, input_buffer); - } - /* array */ - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) - { - return parse_array(item, input_buffer); - } - /* object */ - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) - { - return parse_object(item, input_buffer); - } + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && + (strncmp((const char *)buffer_at_offset(input_buffer), "null", 4) == 0)) { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && + (strncmp((const char *)buffer_at_offset(input_buffer), "false", 5) == + 0)) { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && + (strncmp((const char *)buffer_at_offset(input_buffer), "true", 4) == 0)) { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && + (buffer_at_offset(input_buffer)[0] == '\"')) { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && + ((buffer_at_offset(input_buffer)[0] == '-') || + ((buffer_at_offset(input_buffer)[0] >= '0') && + (buffer_at_offset(input_buffer)[0] <= '9')))) { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && + (buffer_at_offset(input_buffer)[0] == '[')) { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && + (buffer_at_offset(input_buffer)[0] == '{')) { + return parse_object(item, input_buffer); + } - return false; + return false; } /* Render a value to text. */ -static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output = NULL; +static cJSON_bool print_value(const cJSON *const item, + printbuffer *const output_buffer) { + unsigned char *output = NULL; - if ((item == NULL) || (output_buffer == NULL)) - { - return false; + if ((item == NULL) || (output_buffer == NULL)) { + return false; + } + + switch ((item->type) & 0xFF) { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) { + return false; + } + strcpy((char *)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) { + return false; + } + strcpy((char *)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) { + return false; + } + strcpy((char *)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: { + size_t raw_length = 0; + if (item->valuestring == NULL) { + return false; } - switch ((item->type) & 0xFF) - { - case cJSON_NULL: - output = ensure(output_buffer, 5); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "null"); - return true; - - case cJSON_False: - output = ensure(output_buffer, 6); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "false"); - return true; - - case cJSON_True: - output = ensure(output_buffer, 5); - if (output == NULL) - { - return false; - } - strcpy((char*)output, "true"); - return true; - - case cJSON_Number: - return print_number(item, output_buffer); - - case cJSON_Raw: - { - size_t raw_length = 0; - if (item->valuestring == NULL) - { - return false; - } - - raw_length = strlen(item->valuestring) + sizeof(""); - output = ensure(output_buffer, raw_length); - if (output == NULL) - { - return false; - } - memcpy(output, item->valuestring, raw_length); - return true; - } - - case cJSON_String: - return print_string(item, output_buffer); - - case cJSON_Array: - return print_array(item, output_buffer); - - case cJSON_Object: - return print_object(item, output_buffer); - - default: - return false; + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) { + return false; } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } } /* Build an array from input text. */ -static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) -{ - cJSON *head = NULL; /* head of the linked list */ - cJSON *current_item = NULL; +static cJSON_bool parse_array(cJSON *const item, + parse_buffer *const input_buffer) { + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; - if (input_buffer->depth >= CJSON_NESTING_LIMIT) - { - return false; /* to deeply nested */ - } - input_buffer->depth++; + if (input_buffer->depth >= CJSON_NESTING_LIMIT) { + return false; /* to deeply nested */ + } + input_buffer->depth++; - if (buffer_at_offset(input_buffer)[0] != '[') - { - /* not an array */ - goto fail; + if (buffer_at_offset(input_buffer)[0] != '[') { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && + (buffer_at_offset(input_buffer)[0] == ']')) { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) { + goto fail; /* allocation failure */ } + /* attach next item to list */ + if (head == NULL) { + /* start the linked list */ + current_item = head = new_item; + } else { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) - { - /* empty array */ - goto success; + if (!parse_value(current_item, input_buffer)) { + goto fail; /* failed to parse value */ } + buffer_skip_whitespace(input_buffer); + } while (can_access_at_index(input_buffer, 0) && + (buffer_at_offset(input_buffer)[0] == ',')); - /* check if we skipped to the end of the buffer */ - if (cannot_access_at_index(input_buffer, 0)) - { - input_buffer->offset--; - goto fail; - } - - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do - { - /* allocate next item */ - cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); - if (new_item == NULL) - { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if (head == NULL) - { - /* start the linked list */ - current_item = head = new_item; - } - else - { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - /* parse next value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_value(current_item, input_buffer)) - { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } - while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); - - if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') - { - goto fail; /* expected end of array */ - } + if (cannot_access_at_index(input_buffer, 0) || + buffer_at_offset(input_buffer)[0] != ']') { + goto fail; /* expected end of array */ + } success: - input_buffer->depth--; + input_buffer->depth--; - if (head != NULL) { - head->prev = current_item; - } + if (head != NULL) { + head->prev = current_item; + } - item->type = cJSON_Array; - item->child = head; + item->type = cJSON_Array; + item->child = head; - input_buffer->offset++; + input_buffer->offset++; - return true; + return true; fail: - if (head != NULL) - { - cJSON_Delete(head); - } + if (head != NULL) { + cJSON_Delete(head); + } - return false; + return false; } /* Render an array to text */ -static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output_pointer = NULL; - size_t length = 0; - cJSON *current_element = item->child; +static cJSON_bool print_array(const cJSON *const item, + printbuffer *const output_buffer) { + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; - if (output_buffer == NULL) - { + if (output_buffer == NULL) { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) { + if (!print_value(current_element, output_buffer)) { + return false; + } + update_offset(output_buffer); + if (current_element->next) { + length = (size_t)(output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) { return false; + } + *output_pointer++ = ','; + if (output_buffer->format) { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; } + current_element = current_element->next; + } - /* Compose the output array. */ - /* opening square bracket */ - output_pointer = ensure(output_buffer, 1); - if (output_pointer == NULL) - { - return false; - } + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; - *output_pointer = '['; - output_buffer->offset++; - output_buffer->depth++; - - while (current_element != NULL) - { - if (!print_value(current_element, output_buffer)) - { - return false; - } - update_offset(output_buffer); - if (current_element->next) - { - length = (size_t) (output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) - { - return false; - } - *output_pointer++ = ','; - if(output_buffer->format) - { - *output_pointer++ = ' '; - } - *output_pointer = '\0'; - output_buffer->offset += length; - } - current_element = current_element->next; - } - - output_pointer = ensure(output_buffer, 2); - if (output_pointer == NULL) - { - return false; - } - *output_pointer++ = ']'; - *output_pointer = '\0'; - output_buffer->depth--; - - return true; + return true; } /* Build an object from the text. */ -static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) -{ - cJSON *head = NULL; /* linked list head */ - cJSON *current_item = NULL; +static cJSON_bool parse_object(cJSON *const item, + parse_buffer *const input_buffer) { + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; - if (input_buffer->depth >= CJSON_NESTING_LIMIT) - { - return false; /* to deeply nested */ - } - input_buffer->depth++; + if (input_buffer->depth >= CJSON_NESTING_LIMIT) { + return false; /* to deeply nested */ + } + input_buffer->depth++; - if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) - { - goto fail; /* not an object */ + if (cannot_access_at_index(input_buffer, 0) || + (buffer_at_offset(input_buffer)[0] != '{')) { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && + (buffer_at_offset(input_buffer)[0] == '}')) { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) { + goto fail; /* allocation failure */ } + /* attach next item to list */ + if (head == NULL) { + /* start the linked list */ + current_item = head = new_item; + } else { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + if (cannot_access_at_index(input_buffer, 1)) { + goto fail; /* nothing comes after the comma */ + } + + /* parse the name of the child */ input_buffer->offset++; buffer_skip_whitespace(input_buffer); - if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) - { - goto success; /* empty object */ + if (!parse_string(current_item, input_buffer)) { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || + (buffer_at_offset(input_buffer)[0] != ':')) { + goto fail; /* invalid object */ } - /* check if we skipped to the end of the buffer */ - if (cannot_access_at_index(input_buffer, 0)) - { - input_buffer->offset--; - goto fail; + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) { + goto fail; /* failed to parse value */ } + buffer_skip_whitespace(input_buffer); + } while (can_access_at_index(input_buffer, 0) && + (buffer_at_offset(input_buffer)[0] == ',')); - /* step back to character in front of the first element */ - input_buffer->offset--; - /* loop through the comma separated array elements */ - do - { - /* allocate next item */ - cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); - if (new_item == NULL) - { - goto fail; /* allocation failure */ - } - - /* attach next item to list */ - if (head == NULL) - { - /* start the linked list */ - current_item = head = new_item; - } - else - { - /* add to the end and advance */ - current_item->next = new_item; - new_item->prev = current_item; - current_item = new_item; - } - - if (cannot_access_at_index(input_buffer, 1)) - { - goto fail; /* nothing comes after the comma */ - } - - /* parse the name of the child */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_string(current_item, input_buffer)) - { - goto fail; /* failed to parse name */ - } - buffer_skip_whitespace(input_buffer); - - /* swap valuestring and string, because we parsed the name */ - current_item->string = current_item->valuestring; - current_item->valuestring = NULL; - - if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) - { - goto fail; /* invalid object */ - } - - /* parse the value */ - input_buffer->offset++; - buffer_skip_whitespace(input_buffer); - if (!parse_value(current_item, input_buffer)) - { - goto fail; /* failed to parse value */ - } - buffer_skip_whitespace(input_buffer); - } - while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); - - if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) - { - goto fail; /* expected end of object */ - } + if (cannot_access_at_index(input_buffer, 0) || + (buffer_at_offset(input_buffer)[0] != '}')) { + goto fail; /* expected end of object */ + } success: - input_buffer->depth--; + input_buffer->depth--; - if (head != NULL) { - head->prev = current_item; - } + if (head != NULL) { + head->prev = current_item; + } - item->type = cJSON_Object; - item->child = head; + item->type = cJSON_Object; + item->child = head; - input_buffer->offset++; - return true; + input_buffer->offset++; + return true; fail: - if (head != NULL) - { - cJSON_Delete(head); - } + if (head != NULL) { + cJSON_Delete(head); + } - return false; + return false; } /* Render an object to text. */ -static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) -{ - unsigned char *output_pointer = NULL; - size_t length = 0; - cJSON *current_item = item->child; +static cJSON_bool print_object(const cJSON *const item, + printbuffer *const output_buffer) { + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; - if (output_buffer == NULL) - { + if (output_buffer == NULL) { + return false; + } + + /* Compose the output: */ + length = (size_t)(output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) { + if (output_buffer->format) { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) { return false; + } + for (i = 0; i < output_buffer->depth; i++) { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; } - /* Compose the output: */ - length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) - { - return false; + /* print key */ + if (!print_string_ptr((unsigned char *)current_item->string, + output_buffer)) { + return false; } + update_offset(output_buffer); - *output_pointer++ = '{'; - output_buffer->depth++; - if (output_buffer->format) - { - *output_pointer++ = '\n'; + length = (size_t)(output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) { + *output_pointer++ = '\t'; } output_buffer->offset += length; - while (current_item) - { - if (output_buffer->format) - { - size_t i; - output_pointer = ensure(output_buffer, output_buffer->depth); - if (output_pointer == NULL) - { - return false; - } - for (i = 0; i < output_buffer->depth; i++) - { - *output_pointer++ = '\t'; - } - output_buffer->offset += output_buffer->depth; - } + /* print value */ + if (!print_value(current_item, output_buffer)) { + return false; + } + update_offset(output_buffer); - /* print key */ - if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) - { - return false; - } - update_offset(output_buffer); - - length = (size_t) (output_buffer->format ? 2 : 1); - output_pointer = ensure(output_buffer, length); - if (output_pointer == NULL) - { - return false; - } - *output_pointer++ = ':'; - if (output_buffer->format) - { - *output_pointer++ = '\t'; - } - output_buffer->offset += length; - - /* print value */ - if (!print_value(current_item, output_buffer)) - { - return false; - } - update_offset(output_buffer); - - /* print comma if not last */ - length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); - output_pointer = ensure(output_buffer, length + 1); - if (output_pointer == NULL) - { - return false; - } - if (current_item->next) - { - *output_pointer++ = ','; - } - - if (output_buffer->format) - { - *output_pointer++ = '\n'; - } - *output_pointer = '\0'; - output_buffer->offset += length; - - current_item = current_item->next; + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) { + return false; + } + if (current_item->next) { + *output_pointer++ = ','; } - output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); - if (output_pointer == NULL) - { - return false; + if (output_buffer->format) { + *output_pointer++ = '\n'; } - if (output_buffer->format) - { - size_t i; - for (i = 0; i < (output_buffer->depth - 1); i++) - { - *output_pointer++ = '\t'; - } - } - *output_pointer++ = '}'; *output_pointer = '\0'; - output_buffer->depth--; + output_buffer->offset += length; - return true; + current_item = current_item->next; + } + + output_pointer = ensure( + output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) { + return false; + } + if (output_buffer->format) { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; } /* Get Array size/item / object item. */ -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) -{ - cJSON *child = NULL; - size_t size = 0; +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) { + cJSON *child = NULL; + size_t size = 0; - if (array == NULL) - { - return 0; - } + if (array == NULL) { + return 0; + } - child = array->child; + child = array->child; - while(child != NULL) - { - size++; - child = child->next; - } + while (child != NULL) { + size++; + child = child->next; + } - /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ - return (int)size; + return (int)size; } -static cJSON* get_array_item(const cJSON *array, size_t index) -{ - cJSON *current_child = NULL; +static cJSON *get_array_item(const cJSON *array, size_t index) { + cJSON *current_child = NULL; - if (array == NULL) - { - return NULL; - } + if (array == NULL) { + return NULL; + } - current_child = array->child; - while ((current_child != NULL) && (index > 0)) - { - index--; - current_child = current_child->next; - } + current_child = array->child; + while ((current_child != NULL) && (index > 0)) { + index--; + current_child = current_child->next; + } - return current_child; + return current_child; } -CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) -{ - if (index < 0) - { - return NULL; - } +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) { + if (index < 0) { + return NULL; + } - return get_array_item(array, (size_t)index); + return get_array_item(array, (size_t)index); } -static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) -{ - cJSON *current_element = NULL; +static cJSON *get_object_item(const cJSON *const object, const char *const name, + const cJSON_bool case_sensitive) { + cJSON *current_element = NULL; - if ((object == NULL) || (name == NULL)) - { - return NULL; - } + if ((object == NULL) || (name == NULL)) { + return NULL; + } - current_element = object->child; - if (case_sensitive) - { - while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) - { - current_element = current_element->next; - } + current_element = object->child; + if (case_sensitive) { + while ((current_element != NULL) && (current_element->string != NULL) && + (strcmp(name, current_element->string) != 0)) { + current_element = current_element->next; } - else - { - while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) - { - current_element = current_element->next; - } + } else { + while ((current_element != NULL) && + (case_insensitive_strcmp( + (const unsigned char *)name, + (const unsigned char *)(current_element->string)) != 0)) { + current_element = current_element->next; } + } - if ((current_element == NULL) || (current_element->string == NULL)) { - return NULL; - } + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } - return current_element; + return current_element; } -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) -{ - return get_object_item(object, string, false); +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItem(const cJSON *const object, const char *const string) { + return get_object_item(object, string, false); } -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) -{ - return get_object_item(object, string, true); +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItemCaseSensitive(const cJSON *const object, + const char *const string) { + return get_object_item(object, string, true); } -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) -{ - return cJSON_GetObjectItem(object, string) ? 1 : 0; +CJSON_PUBLIC(cJSON_bool) +cJSON_HasObjectItem(const cJSON *object, const char *string) { + return cJSON_GetObjectItem(object, string) ? 1 : 0; } /* Utility for array list handling. */ -static void suffix_object(cJSON *prev, cJSON *item) -{ - prev->next = item; - item->prev = prev; +static void suffix_object(cJSON *prev, cJSON *item) { + prev->next = item; + item->prev = prev; } /* Utility for handling references. */ -static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) -{ - cJSON *reference = NULL; - if (item == NULL) - { - return NULL; - } +static cJSON *create_reference(const cJSON *item, + const internal_hooks *const hooks) { + cJSON *reference = NULL; + if (item == NULL) { + return NULL; + } - reference = cJSON_New_Item(hooks); - if (reference == NULL) - { - return NULL; - } + reference = cJSON_New_Item(hooks); + if (reference == NULL) { + return NULL; + } - memcpy(reference, item, sizeof(cJSON)); - reference->string = NULL; - reference->type |= cJSON_IsReference; - reference->next = reference->prev = NULL; - return reference; + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; } -static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) -{ - cJSON *child = NULL; +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) { + cJSON *child = NULL; - if ((item == NULL) || (array == NULL) || (array == item)) - { - return false; - } + if ((item == NULL) || (array == NULL) || (array == item)) { + return false; + } - child = array->child; - /* - * To find the last item in array quickly, we use prev in array - */ - if (child == NULL) - { - /* list is empty, start new one */ - array->child = item; - item->prev = item; - item->next = NULL; - } - else - { - /* append to the end */ - if (child->prev) - { - suffix_object(child->prev, item); - array->child->prev = item; - } + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } else { + /* append to the end */ + if (child->prev) { + suffix_object(child->prev, item); + array->child->prev = item; } + } - return true; + return true; } /* Add item to array/object. */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) -{ - return add_item_to_array(array, item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) { + return add_item_to_array(array, item); } -#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) - #pragma GCC diagnostic push +#if defined(__clang__) || \ + (defined(__GNUC__) && \ + ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) +#pragma GCC diagnostic push #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wcast-qual" #endif /* helper function to cast away const */ -static void* cast_away_const(const void* string) -{ - return (void*)string; -} -#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) - #pragma GCC diagnostic pop +static void *cast_away_const(const void *string) { return (void *)string; } +#if defined(__clang__) || \ + (defined(__GNUC__) && \ + ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) +#pragma GCC diagnostic pop #endif +static cJSON_bool add_item_to_object(cJSON *const object, + const char *const string, + cJSON *const item, + const internal_hooks *const hooks, + const cJSON_bool constant_key) { + char *new_key = NULL; + int new_type = cJSON_Invalid; -static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) -{ - char *new_key = NULL; - int new_type = cJSON_Invalid; + if ((object == NULL) || (string == NULL) || (item == NULL) || + (object == item)) { + return false; + } - if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) - { - return false; + if (constant_key) { + new_key = (char *)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } else { + new_key = (char *)cJSON_strdup((const unsigned char *)string, hooks); + if (new_key == NULL) { + return false; } - if (constant_key) - { - new_key = (char*)cast_away_const(string); - new_type = item->type | cJSON_StringIsConst; - } - else - { - new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); - if (new_key == NULL) - { - return false; - } + new_type = item->type & ~cJSON_StringIsConst; + } - new_type = item->type & ~cJSON_StringIsConst; - } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) { + hooks->deallocate(item->string); + } - if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) - { - hooks->deallocate(item->string); - } + item->string = new_key; + item->type = new_type; - item->string = new_key; - item->type = new_type; - - return add_item_to_array(object, item); + return add_item_to_array(object, item); } -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) -{ - return add_item_to_object(object, string, item, &global_hooks, false); +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) { + return add_item_to_object(object, string, item, &global_hooks, false); } /* Add an item to an object with constant string as key */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) -{ - return add_item_to_object(object, string, item, &global_hooks, true); +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) { + return add_item_to_object(object, string, item, &global_hooks, true); } -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) -{ - if (array == NULL) - { - return false; - } +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) { + if (array == NULL) { + return false; + } - return add_item_to_array(array, create_reference(item, &global_hooks)); + return add_item_to_array(array, create_reference(item, &global_hooks)); } -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) -{ - if ((object == NULL) || (string == NULL)) - { - return false; - } +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) { + if ((object == NULL) || (string == NULL)) { + return false; + } - return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); + return add_item_to_object(object, string, + create_reference(item, &global_hooks), + &global_hooks, false); } -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) -{ - cJSON *null = cJSON_CreateNull(); - if (add_item_to_object(object, name, null, &global_hooks, false)) - { - return null; - } +CJSON_PUBLIC(cJSON *) +cJSON_AddNullToObject(cJSON *const object, const char *const name) { + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) { + return null; + } - cJSON_Delete(null); + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddTrueToObject(cJSON *const object, const char *const name) { + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddFalseToObject(cJSON *const object, const char *const name) { + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddBoolToObject(cJSON *const object, const char *const name, + const cJSON_bool boolean) { + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddNumberToObject(cJSON *const object, const char *const name, + const double number) { + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddStringToObject(cJSON *const object, const char *const name, + const char *const string) { + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddRawToObject(cJSON *const object, const char *const name, + const char *const raw) { + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddObjectToObject(cJSON *const object, const char *const name) { + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_AddArrayToObject(cJSON *const object, const char *const name) { + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item) { + if ((parent == NULL) || (item == NULL) || + (item != parent->child && item->prev == NULL)) { return NULL; + } + + if (item != parent->child) { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) { + /* first element */ + parent->child = item->next; + } else if (item->next == NULL) { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; } -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) -{ - cJSON *true_item = cJSON_CreateTrue(); - if (add_item_to_object(object, name, true_item, &global_hooks, false)) - { - return true_item; - } - - cJSON_Delete(true_item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) { + if (which < 0) { return NULL; + } + + return cJSON_DetachItemViaPointer(array, + get_array_item(array, (size_t)which)); } -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) -{ - cJSON *false_item = cJSON_CreateFalse(); - if (add_item_to_object(object, name, false_item, &global_hooks, false)) - { - return false_item; - } - - cJSON_Delete(false_item); - return NULL; +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) { + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); } -CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) -{ - cJSON *bool_item = cJSON_CreateBool(boolean); - if (add_item_to_object(object, name, bool_item, &global_hooks, false)) - { - return bool_item; - } +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObject(cJSON *object, const char *string) { + cJSON *to_detach = cJSON_GetObjectItem(object, string); - cJSON_Delete(bool_item); - return NULL; + return cJSON_DetachItemViaPointer(object, to_detach); } -CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) -{ - cJSON *number_item = cJSON_CreateNumber(number); - if (add_item_to_object(object, name, number_item, &global_hooks, false)) - { - return number_item; - } +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) { + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); - cJSON_Delete(number_item); - return NULL; + return cJSON_DetachItemViaPointer(object, to_detach); } -CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) -{ - cJSON *string_item = cJSON_CreateString(string); - if (add_item_to_object(object, name, string_item, &global_hooks, false)) - { - return string_item; - } - - cJSON_Delete(string_item); - return NULL; +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObject(cJSON *object, const char *string) { + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); } -CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) -{ - cJSON *raw_item = cJSON_CreateRaw(raw); - if (add_item_to_object(object, name, raw_item, &global_hooks, false)) - { - return raw_item; - } - - cJSON_Delete(raw_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) -{ - cJSON *object_item = cJSON_CreateObject(); - if (add_item_to_object(object, name, object_item, &global_hooks, false)) - { - return object_item; - } - - cJSON_Delete(object_item); - return NULL; -} - -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) -{ - cJSON *array = cJSON_CreateArray(); - if (add_item_to_object(object, name, array, &global_hooks, false)) - { - return array; - } - - cJSON_Delete(array); - return NULL; -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) -{ - if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL)) - { - return NULL; - } - - if (item != parent->child) - { - /* not the first element */ - item->prev->next = item->next; - } - if (item->next != NULL) - { - /* not the last element */ - item->next->prev = item->prev; - } - - if (item == parent->child) - { - /* first element */ - parent->child = item->next; - } - else if (item->next == NULL) - { - /* last element */ - parent->child->prev = item->prev; - } - - /* make sure the detached item doesn't point anywhere anymore */ - item->prev = NULL; - item->next = NULL; - - return item; -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) -{ - if (which < 0) - { - return NULL; - } - - return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) -{ - cJSON_Delete(cJSON_DetachItemFromArray(array, which)); -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) -{ - cJSON *to_detach = cJSON_GetObjectItem(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) -{ - cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); - - return cJSON_DetachItemViaPointer(object, to_detach); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) -{ - cJSON_Delete(cJSON_DetachItemFromObject(object, string)); -} - -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) -{ - cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) { + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); } /* Replace array/object items with new ones. */ -CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) -{ - cJSON *after_inserted = NULL; +CJSON_PUBLIC(cJSON_bool) +cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) { + cJSON *after_inserted = NULL; - if (which < 0 || newitem == NULL) - { - return false; - } + if (which < 0 || newitem == NULL) { + return false; + } - after_inserted = get_array_item(array, (size_t)which); - if (after_inserted == NULL) - { - return add_item_to_array(array, newitem); - } + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) { + return add_item_to_array(array, newitem); + } - if (after_inserted != array->child && after_inserted->prev == NULL) { - /* return false if after_inserted is a corrupted array item */ - return false; - } + if (after_inserted != array->child && after_inserted->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } - newitem->next = after_inserted; - newitem->prev = after_inserted->prev; - after_inserted->prev = newitem; - if (after_inserted == array->child) - { - array->child = newitem; - } - else - { - newitem->prev->next = newitem; - } + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) { + array->child = newitem; + } else { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, + cJSON *replacement) { + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || + (item == NULL)) { + return false; + } + + if (replacement == item) { return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) { + replacement->next->prev = replacement; + } + if (parent->child == item) { + if (parent->child->prev == parent->child) { + replacement->prev = replacement; + } + parent->child = replacement; + } else { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was + * the parent's child + */ + if (replacement->prev != NULL) { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; } -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) -{ - if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) - { - return false; - } +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) { + if (which < 0) { + return false; + } - if (replacement == item) - { - return true; - } - - replacement->next = item->next; - replacement->prev = item->prev; - - if (replacement->next != NULL) - { - replacement->next->prev = replacement; - } - if (parent->child == item) - { - if (parent->child->prev == parent->child) - { - replacement->prev = replacement; - } - parent->child = replacement; - } - else - { /* - * To find the last item in array quickly, we use prev in array. - * We can't modify the last item's next pointer where this item was the parent's child - */ - if (replacement->prev != NULL) - { - replacement->prev->next = replacement; - } - if (replacement->next == NULL) - { - parent->child->prev = replacement; - } - } - - item->next = NULL; - item->prev = NULL; - cJSON_Delete(item); - - return true; + return cJSON_ReplaceItemViaPointer( + array, get_array_item(array, (size_t)which), newitem); } -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) -{ - if (which < 0) - { - return false; - } +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, + cJSON *replacement, + cJSON_bool case_sensitive) { + if ((replacement == NULL) || (string == NULL)) { + return false; + } - return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && + (replacement->string != NULL)) { + cJSON_free(replacement->string); + } + replacement->string = + (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); + if (replacement->string == NULL) { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer( + object, get_object_item(object, string, case_sensitive), replacement); } -static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) -{ - if ((replacement == NULL) || (string == NULL)) - { - return false; - } - - /* replace the name in the replacement */ - if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) - { - cJSON_free(replacement->string); - } - replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - if (replacement->string == NULL) - { - return false; - } - - replacement->type &= ~cJSON_StringIsConst; - - return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) { + return replace_item_in_object(object, string, newitem, false); } -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) -{ - return replace_item_in_object(object, string, newitem, false); -} - -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) -{ - return replace_item_in_object(object, string, newitem, true); +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, + cJSON *newitem) { + return replace_item_in_object(object, string, newitem, true); } /* Create basic types: */ -CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_NULL; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_NULL; + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_True; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_True; + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_False; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_False; + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = boolean ? cJSON_True : cJSON_False; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = boolean ? cJSON_True : cJSON_False; + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_Number; - item->valuedouble = num; +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Number; + item->valuedouble = num; - /* use saturation in case of overflow */ - if (num >= INT_MAX) - { - item->valueint = INT_MAX; - } - else if (num <= (double)INT_MIN) - { - item->valueint = INT_MIN; - } - else - { - item->valueint = (int)num; - } + /* use saturation in case of overflow */ + if (num >= INT_MAX) { + item->valueint = INT_MAX; + } else if (num <= (double)INT_MIN) { + item->valueint = INT_MIN; + } else { + item->valueint = (int)num; } + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_String; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); - if(!item->valuestring) - { - cJSON_Delete(item); - return NULL; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_String; + item->valuestring = + (char *)cJSON_strdup((const unsigned char *)string, &global_hooks); + if (!item->valuestring) { + cJSON_Delete(item); + return NULL; } + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) - { - item->type = cJSON_String | cJSON_IsReference; - item->valuestring = (char*)cast_away_const(string); - } +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char *)cast_away_const(string); + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) { - item->type = cJSON_Object | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); - } +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON *)cast_away_const(child); + } - return item; + return item; } CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { - cJSON *item = cJSON_New_Item(&global_hooks); - if (item != NULL) { - item->type = cJSON_Array | cJSON_IsReference; - item->child = (cJSON*)cast_away_const(child); - } + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON *)cast_away_const(child); + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type = cJSON_Raw; - item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); - if(!item->valuestring) - { - cJSON_Delete(item); - return NULL; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Raw; + item->valuestring = + (char *)cJSON_strdup((const unsigned char *)raw, &global_hooks); + if (!item->valuestring) { + cJSON_Delete(item); + return NULL; } + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if(item) - { - item->type=cJSON_Array; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Array; + } - return item; + return item; } -CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) -{ - cJSON *item = cJSON_New_Item(&global_hooks); - if (item) - { - item->type = cJSON_Object; - } +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) { + item->type = cJSON_Object; + } - return item; + return item; } /* Create Arrays: */ -CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) { + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; - if ((count < 0) || (numbers == NULL)) - { - return NULL; + if ((count < 0) || (numbers == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateNumber(numbers[i]); + if (!n) { + cJSON_Delete(a); + return NULL; } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) - { - n = cJSON_CreateNumber(numbers[i]); - if (!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p, n); - } - p = n; + if (!i) { + a->child = n; + } else { + suffix_object(p, n); } + p = n; + } - if (a && a->child) { - a->child->prev = n; - } + if (a && a->child) { + a->child->prev = n; + } - return a; + return a; } -CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) { + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; - if ((count < 0) || (numbers == NULL)) - { - return NULL; + if ((count < 0) || (numbers == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateNumber((double)numbers[i]); + if (!n) { + cJSON_Delete(a); + return NULL; } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) - { - n = cJSON_CreateNumber((double)numbers[i]); - if(!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p, n); - } - p = n; + if (!i) { + a->child = n; + } else { + suffix_object(p, n); } + p = n; + } - if (a && a->child) { - a->child->prev = n; - } + if (a && a->child) { + a->child->prev = n; + } - return a; + return a; } -CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; +CJSON_PUBLIC(cJSON *) +cJSON_CreateDoubleArray(const double *numbers, int count) { + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; - if ((count < 0) || (numbers == NULL)) - { - return NULL; + if ((count < 0) || (numbers == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateNumber(numbers[i]); + if (!n) { + cJSON_Delete(a); + return NULL; } - - a = cJSON_CreateArray(); - - for(i = 0; a && (i < (size_t)count); i++) - { - n = cJSON_CreateNumber(numbers[i]); - if(!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p, n); - } - p = n; + if (!i) { + a->child = n; + } else { + suffix_object(p, n); } + p = n; + } - if (a && a->child) { - a->child->prev = n; - } + if (a && a->child) { + a->child->prev = n; + } - return a; + return a; } -CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) -{ - size_t i = 0; - cJSON *n = NULL; - cJSON *p = NULL; - cJSON *a = NULL; +CJSON_PUBLIC(cJSON *) +cJSON_CreateStringArray(const char *const *strings, int count) { + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; - if ((count < 0) || (strings == NULL)) - { - return NULL; + if ((count < 0) || (strings == NULL)) { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) { + n = cJSON_CreateString(strings[i]); + if (!n) { + cJSON_Delete(a); + return NULL; } - - a = cJSON_CreateArray(); - - for (i = 0; a && (i < (size_t)count); i++) - { - n = cJSON_CreateString(strings[i]); - if(!n) - { - cJSON_Delete(a); - return NULL; - } - if(!i) - { - a->child = n; - } - else - { - suffix_object(p,n); - } - p = n; + if (!i) { + a->child = n; + } else { + suffix_object(p, n); } + p = n; + } - if (a && a->child) { - a->child->prev = n; - } + if (a && a->child) { + a->child->prev = n; + } - return a; + return a; } /* Duplication */ -cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); +cJSON *cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); -CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) -{ - return cJSON_Duplicate_rec(item, 0, recurse ); +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) { + return cJSON_Duplicate_rec(item, 0, recurse); } -cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse) -{ - cJSON *newitem = NULL; - cJSON *child = NULL; - cJSON *next = NULL; - cJSON *newchild = NULL; +cJSON *cJSON_Duplicate_rec(const cJSON *item, size_t depth, + cJSON_bool recurse) { + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; - /* Bail on bad ptr */ - if (!item) - { - goto fail; + /* Bail on bad ptr */ + if (!item) { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) { + newitem->valuestring = + (char *)cJSON_strdup((unsigned char *)item->valuestring, &global_hooks); + if (!newitem->valuestring) { + goto fail; } - /* Create new item */ - newitem = cJSON_New_Item(&global_hooks); - if (!newitem) - { - goto fail; + } + if (item->string) { + newitem->string = (item->type & cJSON_StringIsConst) + ? item->string + : (char *)cJSON_strdup((unsigned char *)item->string, + &global_hooks); + if (!newitem->string) { + goto fail; } - /* Copy over all vars */ - newitem->type = item->type & (~cJSON_IsReference); - newitem->valueint = item->valueint; - newitem->valuedouble = item->valuedouble; - if (item->valuestring) - { - newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); - if (!newitem->valuestring) - { - goto fail; - } - } - if (item->string) - { - newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); - if (!newitem->string) - { - goto fail; - } - } - /* If non-recursive, then we're done! */ - if (!recurse) - { - return newitem; - } - /* Walk the ->next chain for the child. */ - child = item->child; - while (child != NULL) - { - if(depth >= CJSON_CIRCULAR_LIMIT) { - goto fail; - } - newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */ - if (!newchild) - { - goto fail; - } - if (next != NULL) - { - /* If newitem->child already set, then crosswire ->prev and ->next and move on */ - next->next = newchild; - newchild->prev = next; - next = newchild; - } - else - { - /* Set newitem->child and move to it */ - newitem->child = newchild; - next = newchild; - } - child = child->next; - } - if (newitem && newitem->child) - { - newitem->child->prev = newchild; - } - + } + /* If non-recursive, then we're done! */ + if (!recurse) { return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) { + if (depth >= CJSON_CIRCULAR_LIMIT) { + goto fail; + } + newchild = cJSON_Duplicate_rec( + child, depth + 1, + true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) { + goto fail; + } + if (next != NULL) { + /* If newitem->child already set, then crosswire ->prev and ->next and + * move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } else { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) { + newitem->child->prev = newchild; + } + + return newitem; fail: - if (newitem != NULL) - { - cJSON_Delete(newitem); - } + if (newitem != NULL) { + cJSON_Delete(newitem); + } - return NULL; + return NULL; } -static void skip_oneline_comment(char **input) -{ - *input += static_strlen("//"); +static void skip_oneline_comment(char **input) { + *input += static_strlen("//"); - for (; (*input)[0] != '\0'; ++(*input)) - { - if ((*input)[0] == '\n') { - *input += static_strlen("\n"); - return; - } + for (; (*input)[0] != '\0'; ++(*input)) { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; } + } } -static void skip_multiline_comment(char **input) -{ - *input += static_strlen("/*"); +static void skip_multiline_comment(char **input) { + *input += static_strlen("/*"); - for (; (*input)[0] != '\0'; ++(*input)) - { - if (((*input)[0] == '*') && ((*input)[1] == '/')) - { - *input += static_strlen("*/"); - return; - } + for (; (*input)[0] != '\0'; ++(*input)) { + if (((*input)[0] == '*') && ((*input)[1] == '/')) { + *input += static_strlen("*/"); + return; } + } } static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { (*output)[0] = (*input)[0]; - *input += static_strlen("\""); - *output += static_strlen("\""); - - for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { - (*output)[0] = (*input)[0]; - - if ((*input)[0] == '\"') { - (*output)[0] = '\"'; - *input += static_strlen("\""); - *output += static_strlen("\""); - return; - } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { - (*output)[1] = (*input)[1]; - *input += static_strlen("\""); - *output += static_strlen("\""); - } + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); } + } } -CJSON_PUBLIC(void) cJSON_Minify(char *json) -{ - char *into = json; +CJSON_PUBLIC(void) cJSON_Minify(char *json) { + char *into = json; - if (json == NULL) - { - return; + if (json == NULL) { + return; + } + + while (json[0] != '\0') { + switch (json[0]) { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') { + skip_oneline_comment(&json); + } else if (json[1] == '*') { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char **)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; } + } - while (json[0] != '\0') - { - switch (json[0]) - { - case ' ': - case '\t': - case '\r': - case '\n': - json++; - break; - - case '/': - if (json[1] == '/') - { - skip_oneline_comment(&json); - } - else if (json[1] == '*') - { - skip_multiline_comment(&json); - } else { - json++; - } - break; - - case '\"': - minify_string(&json, (char**)&into); - break; - - default: - into[0] = json[0]; - json++; - into++; - } - } - - /* and null-terminate. */ - *into = '\0'; + /* and null-terminate. */ + *into = '\0'; } -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) -{ - if (item == NULL) - { +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item) { + if (item == NULL) { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) +cJSON_Compare(const cJSON *const a, const cJSON *const b, + const cJSON_bool case_sensitive) { + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) { + return true; + } + + switch (a->type & 0xFF) { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) { + return true; + } + + return false; + + case cJSON_Array: { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) { return false; + } + + a_element = a_element->next; + b_element = b_element->next; } - return (item->type & 0xFF) == cJSON_Invalid; -} + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) -{ - if (item == NULL) - { + return true; + } + + case cJSON_Object: { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) { return false; - } + } - return (item->type & 0xFF) == cJSON_False; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) -{ - if (item == NULL) - { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) { return false; + } } - return (item->type & 0xff) == cJSON_True; -} - - -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) -{ - if (item == NULL) - { + /* doing this twice, once on a and b to prevent true comparison if a subset + * of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) { return false; - } + } - return (item->type & (cJSON_True | cJSON_False)) != 0; -} -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) -{ - if (item == NULL) - { + if (!cJSON_Compare(b_element, a_element, case_sensitive)) { return false; + } } - return (item->type & 0xFF) == cJSON_NULL; + return true; + } + + default: + return false; + } } -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Number; +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) { + return global_hooks.allocate(size); } -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_String; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Array; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Object; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) -{ - if (item == NULL) - { - return false; - } - - return (item->type & 0xFF) == cJSON_Raw; -} - -CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) -{ - if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) - { - return false; - } - - /* check if type is valid */ - switch (a->type & 0xFF) - { - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - case cJSON_Number: - case cJSON_String: - case cJSON_Raw: - case cJSON_Array: - case cJSON_Object: - break; - - default: - return false; - } - - /* identical objects are equal */ - if (a == b) - { - return true; - } - - switch (a->type & 0xFF) - { - /* in these cases and equal type is enough */ - case cJSON_False: - case cJSON_True: - case cJSON_NULL: - return true; - - case cJSON_Number: - if (compare_double(a->valuedouble, b->valuedouble)) - { - return true; - } - return false; - - case cJSON_String: - case cJSON_Raw: - if ((a->valuestring == NULL) || (b->valuestring == NULL)) - { - return false; - } - if (strcmp(a->valuestring, b->valuestring) == 0) - { - return true; - } - - return false; - - case cJSON_Array: - { - cJSON *a_element = a->child; - cJSON *b_element = b->child; - - for (; (a_element != NULL) && (b_element != NULL);) - { - if (!cJSON_Compare(a_element, b_element, case_sensitive)) - { - return false; - } - - a_element = a_element->next; - b_element = b_element->next; - } - - /* one of the arrays is longer than the other */ - if (a_element != b_element) { - return false; - } - - return true; - } - - case cJSON_Object: - { - cJSON *a_element = NULL; - cJSON *b_element = NULL; - cJSON_ArrayForEach(a_element, a) - { - /* TODO This has O(n^2) runtime, which is horrible! */ - b_element = get_object_item(b, a_element->string, case_sensitive); - if (b_element == NULL) - { - return false; - } - - if (!cJSON_Compare(a_element, b_element, case_sensitive)) - { - return false; - } - } - - /* doing this twice, once on a and b to prevent true comparison if a subset of b - * TODO: Do this the proper way, this is just a fix for now */ - cJSON_ArrayForEach(b_element, b) - { - a_element = get_object_item(a, b_element->string, case_sensitive); - if (a_element == NULL) - { - return false; - } - - if (!cJSON_Compare(b_element, a_element, case_sensitive)) - { - return false; - } - } - - return true; - } - - default: - return false; - } -} - -CJSON_PUBLIC(void *) cJSON_malloc(size_t size) -{ - return global_hooks.allocate(size); -} - -CJSON_PUBLIC(void) cJSON_free(void *object) -{ - global_hooks.deallocate(object); - object = NULL; +CJSON_PUBLIC(void) cJSON_free(void *object) { + global_hooks.deallocate(object); + object = NULL; } diff --git a/src/cJSON.h b/src/cJSON.h index 37520bb..120272a 100644 --- a/src/cJSON.h +++ b/src/cJSON.h @@ -24,23 +24,27 @@ #define cJSON__h #ifdef __cplusplus -extern "C" -{ +extern "C" { #endif -#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#if !defined(__WINDOWS__) && \ + (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) #define __WINDOWS__ #endif #ifdef __WINDOWS__ -/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: +/* When compiling for windows, we specify a specific calling convention to avoid +issues where we are being called from a project with a different default calling +convention. For windows you have 3 define options: -CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols -CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) -CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever +dllexport symbols CJSON_EXPORT_SYMBOLS - Define this on library build when you +want to dllexport symbols (default) CJSON_IMPORT_SYMBOLS - Define this if you +want to dllimport symbol -For *nix builds that support visibility attribute, you can define similar behavior by +For *nix builds that support visibility attribute, you can define similar +behavior by setting default visibility to hidden by adding -fvisibility=hidden (for gcc) @@ -48,31 +52,35 @@ or -xldscope=hidden (for sun cc) to CFLAGS -then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way +CJSON_EXPORT_SYMBOLS does */ #define CJSON_CDECL __cdecl #define CJSON_STDCALL __stdcall -/* export symbols by default, this is necessary for copy pasting the C and header file */ -#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +/* export symbols by default, this is necessary for copy pasting the C and + * header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && \ + !defined(CJSON_EXPORT_SYMBOLS) #define CJSON_EXPORT_SYMBOLS #endif #if defined(CJSON_HIDE_SYMBOLS) -#define CJSON_PUBLIC(type) type CJSON_STDCALL +#define CJSON_PUBLIC(type) type CJSON_STDCALL #elif defined(CJSON_EXPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL #elif defined(CJSON_IMPORT_SYMBOLS) -#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL #endif #else /* !__WINDOWS__ */ #define CJSON_CDECL #define CJSON_STDCALL -#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) -#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__SUNPRO_C)) && \ + defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type #else #define CJSON_PUBLIC(type) type #endif @@ -87,115 +95,146 @@ then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJ /* cJSON Types: */ #define cJSON_Invalid (0) -#define cJSON_False (1 << 0) -#define cJSON_True (1 << 1) -#define cJSON_NULL (1 << 2) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) #define cJSON_Number (1 << 3) #define cJSON_String (1 << 4) -#define cJSON_Array (1 << 5) +#define cJSON_Array (1 << 5) #define cJSON_Object (1 << 6) -#define cJSON_Raw (1 << 7) /* raw json */ +#define cJSON_Raw (1 << 7) /* raw json */ #define cJSON_IsReference 256 #define cJSON_StringIsConst 512 /* The cJSON structure: */ -typedef struct cJSON -{ - /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ - struct cJSON *next; - struct cJSON *prev; - /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ - struct cJSON *child; +typedef struct cJSON { + /* next/prev allow you to walk array/object chains. Alternatively, use + * GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of + * the items in the array/object. */ + struct cJSON *child; - /* The type of the item, as above. */ - int type; + /* The type of the item, as above. */ + int type; - /* The item's string, if type==cJSON_String and type == cJSON_Raw */ - char *valuestring; - /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ - int valueint; - /* The item's number, if type==cJSON_Number */ - double valuedouble; + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; - /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ - char *string; + /* The item's name string, if this item is the child of, or is in the list of + * subitems of an object. */ + char *string; } cJSON; -typedef struct cJSON_Hooks -{ - /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ - void *(CJSON_CDECL *malloc_fn)(size_t sz); - void (CJSON_CDECL *free_fn)(void *ptr); +typedef struct cJSON_Hooks { + /* malloc/free are CDECL on Windows regardless of the default calling + * convention of the compiler, so ensure the hooks allow passing those + * functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void(CJSON_CDECL *free_fn)(void *ptr); } cJSON_Hooks; typedef int cJSON_bool; -/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. - * This is to prevent stack overflows. */ +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse + * them. This is to prevent stack overflows. */ #ifndef CJSON_NESTING_LIMIT #define CJSON_NESTING_LIMIT 1000 #endif -/* Limits the length of circular references can be before cJSON rejects to parse them. - * This is to prevent stack overflows. */ +/* Limits the length of circular references can be before cJSON rejects to parse + * them. This is to prevent stack overflows. */ #ifndef CJSON_CIRCULAR_LIMIT #define CJSON_CIRCULAR_LIMIT 10000 #endif /* returns the version of cJSON as a string */ -CJSON_PUBLIC(const char*) cJSON_Version(void); +CJSON_PUBLIC(const char *) cJSON_Version(void); /* Supply malloc, realloc and free functions to cJSON */ -CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks *hooks); -/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ -/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +/* Memory Management: the caller is always responsible to free the results from + * all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib + * free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is + * cJSON_PrintPreallocated, where the caller has full responsibility of the + * buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. + */ CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); -CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); -/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ -/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ -CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); -CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null + * terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then + * return_parse_end will contain a pointer to the error so will match + * cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithOpts(const char *value, const char **return_parse_end, + cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) +cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, + const char **return_parse_end, + cJSON_bool require_null_terminated); /* Render a cJSON entity to text for transfer/storage. */ CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); /* Render a cJSON entity to text for transfer/storage without any formatting. */ CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); -/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ -CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); -/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ -/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ -CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess + * at the final size. guessing well reduces reallocation. fmt=0 gives + * unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) +cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with + * given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will + * use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) +cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, + const cJSON_bool format); /* Delete a cJSON entity and all subentities. */ CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); /* Returns the number of items in an array (or object). */ CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); -/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +/* Retrieve item number "index" from array "array". Returns NULL if + * unsuccessful. */ CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); /* Get item "string" from object. Case insensitive. */ -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); -CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); -/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItem(const cJSON *const object, const char *const string); +CJSON_PUBLIC(cJSON *) +cJSON_GetObjectItemCaseSensitive(const cJSON *const object, + const char *const string); +CJSON_PUBLIC(cJSON_bool) +cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. + * You'll probably need to look a few chars back to make sense of it. Defined + * when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); /* Check item type and return its value */ -CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); -CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON *const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON *const item); /* These functions check the type of an item */ -CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); -CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON *const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON *const item); /* These calls create a cJSON item of the appropriate type. */ CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); @@ -218,84 +257,134 @@ CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); /* These utilities create an Array of count items. - * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ + * The parameter count cannot be greater than the number of elements in the + * number array, otherwise array access will be out of bounds.*/ CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); -CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); +CJSON_PUBLIC(cJSON *) +cJSON_CreateStringArray(const char *const *strings, int count); /* Append item to the specified array/object. */ CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); -/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. - * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before - * writing to `item->string` */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); -/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and + * will definitely survive the cJSON object. WARNING: When this function was + * used, make sure to always check that (item->type & cJSON_StringIsConst) is + * zero before writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you + * want to add an existing cJSON to a new cJSON, but don't want to corrupt your + * existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) +cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); /* Remove/Detach items from Arrays/Objects. */ -CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemViaPointer(cJSON *parent, cJSON *const item); CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); -CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) +cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) +cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); /* Update array items. */ -CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); -CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) +cJSON_InsertItemInArray( + cJSON *array, int which, + cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemViaPointer(cJSON *const parent, cJSON *const item, + cJSON *replacement); +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) +cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, + cJSON *newitem); /* Duplicate a cJSON item */ CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); -/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will - * need to be released. With recurse!=0, it will duplicate any children connected to the item. - * The item->next and ->prev pointers are always zero on return from Duplicate. */ -/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. - * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ -CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new + * memory that will need to be released. With recurse!=0, it will duplicate any + * children connected to the item. The item->next and ->prev pointers are always + * zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or + * invalid, they will be considered unequal. case_sensitive determines if object + * keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) +cJSON_Compare(const cJSON *const a, const cJSON *const b, + const cJSON_bool case_sensitive); -/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. - * The input pointer json cannot point to a read-only address area, such as a string constant, - * but should point to a readable and writable address area. */ +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from + * strings. The input pointer json cannot point to a read-only address area, + * such as a string constant, but should point to a readable and writable + * address area. */ CJSON_PUBLIC(void) cJSON_Minify(char *json); /* Helper functions for creating and adding items to an object at the same time. * They return the added item or NULL on failure. */ -CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); -CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); -CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); -CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); -CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); -CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddNullToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddTrueToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddFalseToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddBoolToObject(cJSON *const object, const char *const name, + const cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) +cJSON_AddNumberToObject(cJSON *const object, const char *const name, + const double number); +CJSON_PUBLIC(cJSON *) +cJSON_AddStringToObject(cJSON *const object, const char *const name, + const char *const string); +CJSON_PUBLIC(cJSON *) +cJSON_AddRawToObject(cJSON *const object, const char *const name, + const char *const raw); +CJSON_PUBLIC(cJSON *) +cJSON_AddObjectToObject(cJSON *const object, const char *const name); +CJSON_PUBLIC(cJSON *) +cJSON_AddArrayToObject(cJSON *const object, const char *const name); -/* When assigning an integer value, it needs to be propagated to valuedouble too. */ -#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* When assigning an integer value, it needs to be propagated to valuedouble + * too. */ +#define cJSON_SetIntValue(object, number) \ + ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) /* helper for the cJSON_SetNumberValue macro */ CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); -#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) -/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ -CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); +#define cJSON_SetNumberValue(object, number) \ + ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type + * of object is cJSON_String */ +CJSON_PUBLIC(char *) +cJSON_SetValuestring(cJSON *object, const char *valuestring); -/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ -#define cJSON_SetBoolValue(object, boolValue) ( \ - (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ - (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ - cJSON_Invalid\ -) +/* If the object is not a boolean type this does nothing and returns + * cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) \ + ((object != NULL && ((object)->type & (cJSON_False | cJSON_True))) \ + ? (object)->type = ((object)->type & (~(cJSON_False | cJSON_True))) | \ + ((boolValue) ? cJSON_True : cJSON_False) \ + : cJSON_Invalid) /* Macro for iterating over an array or object */ -#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) +#define cJSON_ArrayForEach(element, array) \ + for (element = (array != NULL) ? (array)->child : NULL; element != NULL; \ + element = element->next) -/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +/* malloc/free objects using the malloc/free functions that have been set with + * cJSON_InitHooks */ CJSON_PUBLIC(void *) cJSON_malloc(size_t size); CJSON_PUBLIC(void) cJSON_free(void *object); diff --git a/src/main.c b/src/main.c index 8b80064..5889ebc 100644 --- a/src/main.c +++ b/src/main.c @@ -1,13 +1,13 @@ +#include "terminal.h" +#include +#include +#include +#include #include #include #include -#include -#include #include -#include -#include -#include -#include "terminal.h" +#include #define HTTP_PORT "8888" #define STATIC_DIR "./static/" @@ -16,284 +16,301 @@ static const char *s_http_addr = "http://0.0.0.0:8888"; static struct mg_mgr mgr; struct client_data { - struct terminal_session term; - bool terminal_ready; + struct terminal_session term; + bool terminal_ready; }; // Функция для логирования запросов static void log_request(struct mg_connection *c, struct mg_http_message *hm) { - printf("HTTP Request: %.*s %.*s\n", (int)hm->method.len, hm->method.buf, - (int)hm->uri.len, hm->uri.buf); + printf("HTTP Request: %.*s %.*s\n", (int)hm->method.len, hm->method.buf, + (int)hm->uri.len, hm->uri.buf); } // Проверяем, жив ли дочерний процесс static bool is_process_alive(pid_t pid) { - if (pid <= 0) return false; - - int status; - pid_t result = waitpid(pid, &status, WNOHANG); - if (result == 0) { - // Процесс все еще работает - return true; - } else if (result == -1) { - // Ошибка - if (errno == ECHILD) { - // Процесс не существует - return false; - } - perror("waitpid"); - return false; - } else { - // Процесс завершился - return false; + if (pid <= 0) + return false; + + int status; + pid_t result = waitpid(pid, &status, WNOHANG); + if (result == 0) { + // Процесс все еще работает + return true; + } else if (result == -1) { + // Ошибка + if (errno == ECHILD) { + // Процесс не существует + return false; } + perror("waitpid"); + return false; + } else { + // Процесс завершился + return false; + } } // Перезапускаем терминальную сессию -static void restart_terminal_session(struct mg_connection *c, struct client_data *cd) { - if (!cd) return; - - printf("Restarting terminal session...\n"); - - // Уничтожаем старую сессию - if (cd->terminal_ready) { - destroy_terminal_session(&cd->term); - } - - // Создаем новую сессию - const char *shell = getenv("SHELL"); - if (!shell) shell = "/bin/bash"; - - if (create_terminal_session(&cd->term, shell) == 0) { - cd->terminal_ready = true; - mg_ws_send(c, "\r\n*** Terminal restarted ***\r\n", 29, WEBSOCKET_OP_TEXT); - } else { - mg_ws_send(c, "\r\n*** Failed to restart terminal ***\r\n", 37, WEBSOCKET_OP_TEXT); - cd->terminal_ready = false; - } +static void restart_terminal_session(struct mg_connection *c, + struct client_data *cd) { + if (!cd) + return; + + printf("Restarting terminal session...\n"); + + // Уничтожаем старую сессию + if (cd->terminal_ready) { + destroy_terminal_session(&cd->term); + } + + // Создаем новую сессию + const char *shell = getenv("SHELL"); + if (!shell) + shell = "/bin/bash"; + + if (create_terminal_session(&cd->term, shell) == 0) { + cd->terminal_ready = true; + mg_ws_send(c, "\r\n*** Terminal restarted ***\r\n", 29, WEBSOCKET_OP_TEXT); + } else { + mg_ws_send(c, "\r\n*** Failed to restart terminal ***\r\n", 37, + WEBSOCKET_OP_TEXT); + cd->terminal_ready = false; + } } // Обработчик WebSocket сообщений -static void handle_websocket_message(struct mg_connection *c, struct mg_ws_message *wm, struct client_data *cd) { - if (!cd) return; - - if (wm->data.len == 0) { - return; +static void handle_websocket_message(struct mg_connection *c, + struct mg_ws_message *wm, + struct client_data *cd) { + if (!cd) + return; + + if (wm->data.len == 0) { + return; + } + + // Парсим JSON для проверки resize сообщения + cJSON *json = cJSON_ParseWithLength(wm->data.buf, wm->data.len); + if (json != NULL) { + cJSON *cols = cJSON_GetObjectItemCaseSensitive(json, "cols"); + cJSON *rows = cJSON_GetObjectItemCaseSensitive(json, "rows"); + + if (cJSON_IsNumber(cols) && cJSON_IsNumber(rows)) { + printf("Resizing terminal to %dx%d\n", rows->valueint, cols->valueint); + resize_terminal(&cd->term, rows->valueint, cols->valueint); + cJSON_Delete(json); + return; } - - // Парсим JSON для проверки resize сообщения - cJSON *json = cJSON_ParseWithLength(wm->data.buf, wm->data.len); - if (json != NULL) { - cJSON *cols = cJSON_GetObjectItemCaseSensitive(json, "cols"); - cJSON *rows = cJSON_GetObjectItemCaseSensitive(json, "rows"); - - if (cJSON_IsNumber(cols) && cJSON_IsNumber(rows)) { - printf("Resizing terminal to %dx%d\n", rows->valueint, cols->valueint); - resize_terminal(&cd->term, rows->valueint, cols->valueint); - cJSON_Delete(json); - return; - } - cJSON_Delete(json); - } - - // Проверяем, не команда ли это exit - if (wm->data.len >= 4 && strncmp(wm->data.buf, "exit", 4) == 0) { - printf("Exit command detected, restarting terminal session\n"); - write_to_terminal(&cd->term, wm->data.buf, wm->data.len); - // Даем команде выполниться, затем перезапускаем - usleep(100); - restart_terminal_session(c, cd); - return; - } - - // Обычный ввод от пользователя + cJSON_Delete(json); + } + + // Проверяем, не команда ли это exit + if (wm->data.len >= 4 && strncmp(wm->data.buf, "exit", 4) == 0) { + printf("Exit command detected, restarting terminal session\n"); write_to_terminal(&cd->term, wm->data.buf, wm->data.len); + // Даем команде выполниться, затем перезапускаем + usleep(100); + restart_terminal_session(c, cd); + return; + } + + // Обычный ввод от пользователя + write_to_terminal(&cd->term, wm->data.buf, wm->data.len); } // Обработчик HTTP запросов static void fn(struct mg_connection *c, int ev, void *ev_data) { - if (ev == MG_EV_HTTP_MSG) { - struct mg_http_message *hm = (struct mg_http_message *)ev_data; - log_request(c, hm); - - if (mg_match(hm->uri, mg_str("/ws"), nullptr)) { - // Проверяем, нет ли уже активного соединения - if (c->fn_data != NULL) { - printf("WebSocket connection already exists for this connection, cleaning up...\n"); - struct client_data *old_cd = (struct client_data *)c->fn_data; - destroy_terminal_session(&old_cd->term); - free(old_cd); - c->fn_data = NULL; - } - - // Upgrade до WebSocket - struct client_data *cd = calloc(1, sizeof(struct client_data)); - if (!cd) { - mg_http_reply(c, 500, "Content-Type: text/plain\r\n", "Memory allocation failed"); - return; - } - - // Создаем терминальную сессию - const char *shell = getenv("SHELL"); - if (!shell) shell = "/bin/bash"; - - printf("Creating new terminal session with shell: %s\n", shell); - if (create_terminal_session(&cd->term, shell) != 0) { - mg_http_reply(c, 500, "Content-Type: text/plain\r\n", "Failed to create terminal session"); - free(cd); - return; - } - - cd->terminal_ready = true; - c->fn_data = cd; - - // Upgrade to WebSocket - struct mg_str *ws_proto = mg_http_get_header(hm, "Sec-WebSocket-Protocol"); - if (ws_proto != NULL) { - mg_ws_upgrade(c, hm, ws_proto->buf); - } else { - mg_ws_upgrade(c, hm, NULL); - } - - printf("WebSocket upgrade completed\n"); - - } else if (mg_match(hm->uri, mg_str("/"), nullptr)) { - // Главная страница - struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; - mg_http_serve_file(c, hm, "./static/index.html", &opts); - - } else if (mg_match(hm->uri, mg_str("/xterm.js"), nullptr)) { - // xterm.js - struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; - mg_http_serve_file(c, hm, "./static/xterm.js", &opts); - - } else if (mg_match(hm->uri, mg_str("/xterm.css"), nullptr)) { - // xterm.css - struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; - mg_http_serve_file(c, hm, "./static/xterm.css", &opts); - - } else if (mg_match(hm->uri, mg_str("/xterm-addon-fit.js"), nullptr)) { - // xterm-addon-fit.js - struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; - mg_http_serve_file(c, hm, "./static/xterm-addon-fit.js", &opts); - - } else { - mg_http_reply(c, 404, "Content-Type: text/plain\r\n", "Not Found"); - } - } else if (ev == MG_EV_WS_OPEN) { - // WebSocket соединение установлено - printf("WebSocket connection opened\n"); - struct client_data *cd = (struct client_data *)c->fn_data; - if (cd) { - mg_ws_send(c, "Terminal ready - type 'exit' to restart session\r\n", 49, WEBSOCKET_OP_TEXT); - } - } else if (ev == MG_EV_WS_MSG) { - // Сообщение от WebSocket клиента - struct mg_ws_message *wm = (struct mg_ws_message *)ev_data; - struct client_data *cd = (struct client_data *)c->fn_data; - handle_websocket_message(c, wm, cd); - } else if (ev == MG_EV_CLOSE) { - // Закрытие соединения - struct client_data *cd = (struct client_data *)c->fn_data; - if (cd) { - printf("WebSocket connection closed, cleaning up...\n"); - destroy_terminal_session(&cd->term); - free(cd); - c->fn_data = NULL; - } - } else if (ev == MG_EV_POLL) { - // Проверяем данные от терминала и отправляем через WebSocket - struct mg_connection *conn; - for (conn = mgr.conns; conn != NULL; conn = conn->next) { - if (!conn->is_websocket) continue; - - struct client_data *cd = (struct client_data *)conn->fn_data; - if (cd && cd->terminal_ready) { - // Проверяем, не завершился ли процесс - if (!is_process_alive(cd->term.child_pid)) { - printf("Terminal process died, restarting...\n"); - restart_terminal_session(conn, cd); - continue; - } - - // Читаем данные из терминала - char buffer[1024]; - ssize_t bytes_read = read_from_terminal(&cd->term, buffer, sizeof(buffer)); - if (bytes_read > 0) { - mg_ws_send(conn, buffer, bytes_read, WEBSOCKET_OP_BINARY); - } else if (bytes_read == 0) { - // EOF - процесс завершился - printf("EOF from terminal, restarting...\n"); - restart_terminal_session(conn, cd); - } else if (bytes_read < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { - // Ошибка чтения - printf("Error reading from terminal: %s\n", strerror(errno)); - restart_terminal_session(conn, cd); - } - } - } + if (ev == MG_EV_HTTP_MSG) { + struct mg_http_message *hm = (struct mg_http_message *)ev_data; + log_request(c, hm); + + if (mg_match(hm->uri, mg_str("/ws"), nullptr)) { + // Проверяем, нет ли уже активного соединения + if (c->fn_data != NULL) { + printf("WebSocket connection already exists for this connection, " + "cleaning up...\n"); + struct client_data *old_cd = (struct client_data *)c->fn_data; + destroy_terminal_session(&old_cd->term); + free(old_cd); + c->fn_data = NULL; + } + + // Upgrade до WebSocket + struct client_data *cd = calloc(1, sizeof(struct client_data)); + if (!cd) { + mg_http_reply(c, 500, "Content-Type: text/plain\r\n", + "Memory allocation failed"); + return; + } + + // Создаем терминальную сессию + const char *shell = getenv("SHELL"); + if (!shell) + shell = "/bin/bash"; + + printf("Creating new terminal session with shell: %s\n", shell); + if (create_terminal_session(&cd->term, shell) != 0) { + mg_http_reply(c, 500, "Content-Type: text/plain\r\n", + "Failed to create terminal session"); + free(cd); + return; + } + + cd->terminal_ready = true; + c->fn_data = cd; + + // Upgrade to WebSocket + struct mg_str *ws_proto = + mg_http_get_header(hm, "Sec-WebSocket-Protocol"); + if (ws_proto != NULL) { + mg_ws_upgrade(c, hm, ws_proto->buf); + } else { + mg_ws_upgrade(c, hm, NULL); + } + + printf("WebSocket upgrade completed\n"); + + } else if (mg_match(hm->uri, mg_str("/"), nullptr)) { + // Главная страница + struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR}; + mg_http_serve_file(c, hm, "./static/index.html", &opts); + + } else if (mg_match(hm->uri, mg_str("/xterm.js"), nullptr)) { + // xterm.js + struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR}; + mg_http_serve_file(c, hm, "./static/xterm.js", &opts); + + } else if (mg_match(hm->uri, mg_str("/xterm.css"), nullptr)) { + // xterm.css + struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR}; + mg_http_serve_file(c, hm, "./static/xterm.css", &opts); + + } else if (mg_match(hm->uri, mg_str("/xterm-addon-fit.js"), nullptr)) { + // xterm-addon-fit.js + struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR}; + mg_http_serve_file(c, hm, "./static/xterm-addon-fit.js", &opts); + + } else { + mg_http_reply(c, 404, "Content-Type: text/plain\r\n", "Not Found"); } + } else if (ev == MG_EV_WS_OPEN) { + // WebSocket соединение установлено + printf("WebSocket connection opened\n"); + struct client_data *cd = (struct client_data *)c->fn_data; + if (cd) { + mg_ws_send(c, "Terminal ready - type 'exit' to restart session\r\n", 49, + WEBSOCKET_OP_TEXT); + } + } else if (ev == MG_EV_WS_MSG) { + // Сообщение от WebSocket клиента + struct mg_ws_message *wm = (struct mg_ws_message *)ev_data; + struct client_data *cd = (struct client_data *)c->fn_data; + handle_websocket_message(c, wm, cd); + } else if (ev == MG_EV_CLOSE) { + // Закрытие соединения + struct client_data *cd = (struct client_data *)c->fn_data; + if (cd) { + printf("WebSocket connection closed, cleaning up...\n"); + destroy_terminal_session(&cd->term); + free(cd); + c->fn_data = NULL; + } + } else if (ev == MG_EV_POLL) { + // Проверяем данные от терминала и отправляем через WebSocket + struct mg_connection *conn; + for (conn = mgr.conns; conn != NULL; conn = conn->next) { + if (!conn->is_websocket) + continue; + + struct client_data *cd = (struct client_data *)conn->fn_data; + if (cd && cd->terminal_ready) { + // Проверяем, не завершился ли процесс + if (!is_process_alive(cd->term.child_pid)) { + printf("Terminal process died, restarting...\n"); + restart_terminal_session(conn, cd); + continue; + } + + // Читаем данные из терминала + char buffer[1024]; + ssize_t bytes_read = + read_from_terminal(&cd->term, buffer, sizeof(buffer)); + if (bytes_read > 0) { + mg_ws_send(conn, buffer, bytes_read, WEBSOCKET_OP_BINARY); + } else if (bytes_read == 0) { + // EOF - процесс завершился + printf("EOF from terminal, restarting...\n"); + restart_terminal_session(conn, cd); + } else if (bytes_read < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { + // Ошибка чтения + printf("Error reading from terminal: %s\n", strerror(errno)); + restart_terminal_session(conn, cd); + } + } + } + } } // Обработчик сигналов для graceful shutdown static void signal_handler(int sig) { - printf("\nShutting down server...\n"); - - // Очищаем все соединения - struct mg_connection *conn; - for (conn = mgr.conns; conn != NULL; conn = conn->next) { - if (conn->fn_data) { - struct client_data *cd = (struct client_data *)conn->fn_data; - destroy_terminal_session(&cd->term); - free(cd); - conn->fn_data = NULL; - } + printf("\nShutting down server...\n"); + + // Очищаем все соединения + struct mg_connection *conn; + for (conn = mgr.conns; conn != NULL; conn = conn->next) { + if (conn->fn_data) { + struct client_data *cd = (struct client_data *)conn->fn_data; + destroy_terminal_session(&cd->term); + free(cd); + conn->fn_data = NULL; } - - mg_mgr_free(&mgr); - exit(0); + } + + mg_mgr_free(&mgr); + exit(0); } // Проверяем существование директории static bool directory_exists(const char *path) { - struct stat st; - return stat(path, &st) == 0 && S_ISDIR(st.st_mode); + struct stat st; + return stat(path, &st) == 0 && S_ISDIR(st.st_mode); } int main(void) { - // Устанавливаем обработчики сигналов - signal(SIGINT, signal_handler); - signal(SIGTERM, signal_handler); - - // Инициализируем менеджер соединений - mg_mgr_init(&mgr); - printf("Mongoose version: %s\n", MG_VERSION); - - // Проверяем существование статической директории - if (!directory_exists(STATIC_DIR)) { - fprintf(stderr, "Static directory '%s' not found! Creating it...\n", STATIC_DIR); - if (mkdir(STATIC_DIR, 0755) != 0) { - fprintf(stderr, "Failed to create static directory\n"); - return 1; - } + // Устанавливаем обработчики сигналов + signal(SIGINT, signal_handler); + signal(SIGTERM, signal_handler); + + // Инициализируем менеджер соединений + mg_mgr_init(&mgr); + printf("Mongoose version: %s\n", MG_VERSION); + + // Проверяем существование статической директории + if (!directory_exists(STATIC_DIR)) { + fprintf(stderr, "Static directory '%s' not found! Creating it...\n", + STATIC_DIR); + if (mkdir(STATIC_DIR, 0755) != 0) { + fprintf(stderr, "Failed to create static directory\n"); + return 1; } - - // Создаем HTTP сервер - struct mg_connection *c = mg_http_listen(&mgr, s_http_addr, fn, NULL); - if (c == NULL) { - fprintf(stderr, "Failed to start server on %s\n", s_http_addr); - return 1; - } - - printf("Starting web terminal server on %s\n", s_http_addr); - printf("Static files directory: %s\n", STATIC_DIR); - printf("Server is ready. Open http://localhost:8000 in your browser\n"); - - // Основной цикл - while (true) { - mg_mgr_poll(&mgr, 50); // 50ms timeout - } - - mg_mgr_free(&mgr); - return 0; + } + + // Создаем HTTP сервер + struct mg_connection *c = mg_http_listen(&mgr, s_http_addr, fn, NULL); + if (c == NULL) { + fprintf(stderr, "Failed to start server on %s\n", s_http_addr); + return 1; + } + + printf("Starting web terminal server on %s\n", s_http_addr); + printf("Static files directory: %s\n", STATIC_DIR); + printf("Server is ready. Open http://localhost:8000 in your browser\n"); + + // Основной цикл + while (true) { + mg_mgr_poll(&mgr, 50); // 50ms timeout + } + + mg_mgr_free(&mgr); + return 0; } diff --git a/src/mongoose.c b/src/mongoose.c index 7b61650..6d169f5 100644 --- a/src/mongoose.c +++ b/src/mongoose.c @@ -16361,7 +16361,7 @@ int mg_rsa_mod_pow(const uint8_t *mod, size_t modsz, const uint8_t *exp, size_t #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro)) #endif -// +// #if (MG_UECC_WORD_SIZE == 1) #if MG_UECC_SUPPORTS_secp160r1 @@ -20899,7 +20899,7 @@ static bool cyw_wifi_connect(char *ssid, char *pass) { uint32_t data[64/4 + 1]; // max pass length: 64 for WPA, 128 for WPA3 SAE uint16_t *da = (uint16_t *) data; unsigned int len; - uint32_t val; + uint32_t val; val = 4; // security type: 0 for none, 2 for WPA, 4 for WPA2/WPA3, 6 for mixed WPA/WPA2 // sup_wpa[1] = 0 if not using security if (!(cyw_ioctl_set(134 /* SET_WSEC */, (uint8_t *)&val, sizeof(val)) @@ -20941,7 +20941,7 @@ static bool cyw_wifi_ap_start(char *ssid, char *pass, unsigned int channel) { uint32_t data[64/4 + 2]; // max pass length: 64 for WPA, 128 for WPA3 SAE uint16_t *da = (uint16_t *) data; unsigned int len; - uint32_t val; + uint32_t val; // CHIP DEPENDENCY // RPi set the AMPDU parameter for AP (window size = 2) ***************** // val = 2 ; cyw_ioctl_iovar_set_(0, "ampdu_ba_wsize", (uint8_t *)&val, sizeof(val)); @@ -20970,10 +20970,10 @@ static bool cyw_wifi_ap_start(char *ssid, char *pass, unsigned int channel) { da[1] = 1; // indicates wireless security key, skip for WPA3 SAE memcpy((uint8_t *)data + 2 * sizeof(uint16_t), pass, len); // skip for WPA3 SAE if (!cyw_ioctl_set_(1, 268 /* SET_WSEC_PMK */, data, sizeof(data))) return false; // skip for WPA3 SAE, sizeof/2 if supporting SAE but using WPA - /* for WPA3 SAE: + /* for WPA3 SAE: memcpy((uint8_t *)data + sizeof(uint16_t), pass, len); cyw_ioctl_iovar_set_(1, "sae_password", data, sizeof(data)); */ - /* for WPA3 or mixed WPA2/WPA3: + /* for WPA3 or mixed WPA2/WPA3: val = 5 ; cyw_ioctl_iovar_set_(1, "sae_max_pwe_loop", (uint8_t *)&val, sizeof(val)); // Some chipsets do not support this */ // resume if not using auth @@ -21119,7 +21119,7 @@ static void cyw_handle_scan_result(uint32_t status, struct scan_result *data, si bss.band = band & CYW_BSS_BAND2G ? MG_WIFI_BAND_2G : MG_WIFI_BAND_5G; bss.security = (sbss->capability & MG_BIT(4) /* CAP_PRIVACY */) ? MG_WIFI_SECURITY_WEP : MG_WIFI_SECURITY_OPEN; { // travel IEs (Information Elements) in search of security definitions - const uint8_t wot1[4] = {0x00, 0x50, 0xf2, 0x01}; // WPA_OUI_TYPE1 + const uint8_t wot1[4] = {0x00, 0x50, 0xf2, 0x01}; // WPA_OUI_TYPE1 uint8_t *ie = (uint8_t *)sbss + sbss->ie_offset; int bytes = (int) sbss->ie_length; while (bytes > 0 && ie[1] + 2 < bytes) { // ie[0] -> type, ie[1] -> bytes from ie[2] @@ -21130,11 +21130,11 @@ static void cyw_handle_scan_result(uint32_t status, struct scan_result *data, si bytes -= ie[1] + 2; } } - MG_VERBOSE(("BSS: %.*s (%u) (%M) %d dBm %u", bss.SSID.len, bss.SSID.buf, bss.channel, mg_print_mac, bss.BSSID, (int) bss.RSSI, bss.security)); + MG_VERBOSE(("BSS: %.*s (%u) (%M) %d dBm %u", bss.SSID.len, bss.SSID.buf, bss.channel, mg_print_mac, bss.BSSID, (int) bss.RSSI, bss.security)); mg_tcpip_call(s_ifp, MG_TCPIP_EV_WIFI_SCAN_RESULT, &bss); } else { MG_ERROR(("scan error")); - } + } } // clang-format on @@ -21326,7 +21326,7 @@ static bool cyw_init(uint8_t *mac) { // CHIP DEPENDENCY val = 8 ; cyw_ioctl_iovar_set("ampdu_ba_wsize", (uint8_t *)&val, sizeof(val)); val = 4 ; cyw_ioctl_iovar_set("ampdu_mpdu", (uint8_t *)&val, sizeof(val)); - val = 0 /* 8K */; cyw_ioctl_iovar_set("ampdu_rx_factor", (uint8_t *)&val, sizeof(val)); + val = 0 /* 8K */; cyw_ioctl_iovar_set("ampdu_rx_factor", (uint8_t *)&val, sizeof(val)); // { struct cyw_country c; @@ -21544,7 +21544,7 @@ static bool cyw_load_fwll(void *fwdata, size_t fwlen, void *nvramdata, size_t nv cyw_load_data(CYW_CHIP_ATCMRAM_BASE, fwdata, fwlen); mg_delayms(5); // TODO(scaprile): CHECK IF THIS IS ACTUALLY NEEDED // Load NVRAM and place 'length ~length' at the end; end of chip RAM - { + { const uint32_t start = CYW_CHIP_RAM_SIZE - 4 - nvramlen; cyw_load_data(start, nvramdata, nvramlen); // nvramlen must be a multiple of 4 // RAM_SIZE is a multiple of WINSZ, so the place for len ~len will be at the end of the window @@ -21835,7 +21835,7 @@ static bool cyw_sdio_init() { struct mg_tcpip_sdio *s = (struct mg_tcpip_sdio *) d->bus; uint32_t val = 0; if (!mg_sdio_init(s)) return false; - // no block transfers on F0. if (!mg_sdio_set_blksz(s, CYW_SDIO_FUNC_BUS, 32)) return false; + // no block transfers on F0. if (!mg_sdio_set_blksz(s, CYW_SDIO_FUNC_BUS, 32)) return false; if (!mg_sdio_set_blksz(s, CYW_SDIO_FUNC_CHIP, 64)) return false; if (!mg_sdio_set_blksz(s, CYW_SDIO_FUNC_WLAN, 64)) return false; // TODO(scaprile): we don't handle SDIO interrupts, study CCCR INTEN and SDIO support (SDIO 6.3, 8) @@ -22052,7 +22052,7 @@ static bool mg_tcpip_driver_imxrt_init(struct mg_tcpip_if *ifp) { int cr = (d == NULL || d->mdc_cr < 0) ? 24 : d->mdc_cr; ENET->MSCR = (1 << 8) | ((cr & 0x3f) << 1); // HOLDTIME 2 clks struct mg_phy phy = {enet_read_phy, enet_write_phy}; - mg_phy_init(&phy, d->phy_addr, MG_PHY_LEDS_ACTIVE_HIGH); // MAC clocks PHY + mg_phy_init(&phy, d->phy_addr, MG_PHY_LEDS_ACTIVE_HIGH); // MAC clocks PHY // Select RMII mode, 100M, keep CRC, set max rx length, disable loop ENET->RCR = (1518 << 16) | MG_BIT(8) | MG_BIT(2); // ENET->RCR |= MG_BIT(3); // Receive all @@ -24551,13 +24551,13 @@ struct tms570_mdio { #define ETH_PKT_SIZE 1540 // Max frame size #define ETH_DESC_CNT 4 // Descriptors count #define ETH_DS 4 // Descriptor size (words) -static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS] +static uint32_t s_txdesc[ETH_DESC_CNT][ETH_DS] __attribute__((section(".ETH_CPPI"), aligned(4))); // TX descriptors -static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS] +static uint32_t s_rxdesc[ETH_DESC_CNT][ETH_DS] __attribute__((section(".ETH_CPPI"), aligned(4))); // RX descriptors -static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] +static uint8_t s_rxbuf[ETH_DESC_CNT][ETH_PKT_SIZE] __attribute__((aligned(4))); // RX ethernet buffers -static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] +static uint8_t s_txbuf[ETH_DESC_CNT][ETH_PKT_SIZE] __attribute__((aligned(4))); // TX ethernet buffers static struct mg_tcpip_if *s_ifp; // MIP interface static uint16_t emac_read_phy(uint8_t addr, uint8_t reg) { @@ -24638,7 +24638,7 @@ static bool mg_tcpip_driver_tms570_init(struct mg_tcpip_if *ifp) { } s_txdesc[ETH_DESC_CNT - 1][0] = 0; s_rxdesc[ETH_DESC_CNT - 1][0] = 0; - + EMAC->MACCONTROL = MG_BIT(5) | MG_BIT(0); // Enable MII, Full-duplex //EMAC->TXINTMASKSET = 1; // Enable TX interrupt EMAC->RXINTMASKSET = 1; // Enable RX interrupt @@ -24665,7 +24665,7 @@ static size_t mg_tcpip_driver_tms570_tx(const void *buf, size_t len, s_txdesc[s_txno][2] = SWAP32((uint32_t) len); // Set data len s_txdesc[s_txno][3] = SWAP32(MG_BIT(31) | MG_BIT(30) | MG_BIT(29) | len); // SOP, EOP, OWN, length - + while(EMAC->TXHDP[0] != 0) (void) 0; EMAC->TXHDP[0] = (uint32_t) &s_txdesc[s_txno][0]; if(++s_txno == ETH_DESC_CNT) { diff --git a/src/mongoose.h b/src/mongoose.h index 6148b9e..8a6be32 100644 --- a/src/mongoose.h +++ b/src/mongoose.h @@ -26,26 +26,25 @@ extern "C" { #endif +#define MG_ARCH_CUSTOM 0 // User creates its own mongoose_config.h +#define MG_ARCH_UNIX 1 // Linux, BSD, Mac, ... +#define MG_ARCH_WIN32 2 // Windows +#define MG_ARCH_ESP32 3 // ESP32 +#define MG_ARCH_ESP8266 4 // ESP8266 +#define MG_ARCH_FREERTOS 5 // FreeRTOS +#define MG_ARCH_THREADX 6 // Eclipse ThreadX (former MS Azure RTOS) +#define MG_ARCH_ZEPHYR 7 // Zephyr RTOS +#define MG_ARCH_ARMGCC 8 // Plain ARM GCC +#define MG_ARCH_CMSIS_RTOS1 9 // CMSIS-RTOS API v1 (Keil RTX) +#define MG_ARCH_TIRTOS 10 // Texas Semi TI-RTOS +#define MG_ARCH_PICOSDK 11 // Raspberry Pi Pico-SDK (RP2040, RP2350) +#define MG_ARCH_ARMCC 12 // Keil MDK-Core with Configuration Wizard +#define MG_ARCH_CMSIS_RTOS2 13 // CMSIS-RTOS API v2 (Keil RTX5, FreeRTOS) +#define MG_ARCH_RTTHREAD 14 // RT-Thread RTOS +#define MG_ARCH_ARMCGT 15 // Texas Semi ARM-CGT +#define MG_ARCH_CUBE 16 // STM32Cube environment -#define MG_ARCH_CUSTOM 0 // User creates its own mongoose_config.h -#define MG_ARCH_UNIX 1 // Linux, BSD, Mac, ... -#define MG_ARCH_WIN32 2 // Windows -#define MG_ARCH_ESP32 3 // ESP32 -#define MG_ARCH_ESP8266 4 // ESP8266 -#define MG_ARCH_FREERTOS 5 // FreeRTOS -#define MG_ARCH_THREADX 6 // Eclipse ThreadX (former MS Azure RTOS) -#define MG_ARCH_ZEPHYR 7 // Zephyr RTOS -#define MG_ARCH_ARMGCC 8 // Plain ARM GCC -#define MG_ARCH_CMSIS_RTOS1 9 // CMSIS-RTOS API v1 (Keil RTX) -#define MG_ARCH_TIRTOS 10 // Texas Semi TI-RTOS -#define MG_ARCH_PICOSDK 11 // Raspberry Pi Pico-SDK (RP2040, RP2350) -#define MG_ARCH_ARMCC 12 // Keil MDK-Core with Configuration Wizard -#define MG_ARCH_CMSIS_RTOS2 13 // CMSIS-RTOS API v2 (Keil RTX5, FreeRTOS) -#define MG_ARCH_RTTHREAD 14 // RT-Thread RTOS -#define MG_ARCH_ARMCGT 15 // Texas Semi ARM-CGT -#define MG_ARCH_CUBE 16 // STM32Cube environment - -#define MG_ARCH_NEWLIB MG_ARCH_ARMGCC // Alias, deprecate in 2025 +#define MG_ARCH_NEWLIB MG_ARCH_ARMGCC // Alias, deprecate in 2025 #if !defined(MG_ARCH) #if defined(__unix__) || defined(__APPLE__) @@ -53,34 +52,19 @@ extern "C" { #elif defined(_WIN32) #define MG_ARCH MG_ARCH_WIN32 #endif -#endif // !defined(MG_ARCH) +#endif // !defined(MG_ARCH) #if !defined(MG_ARCH) || (MG_ARCH == MG_ARCH_CUSTOM) -#include "mongoose_config.h" // keep this include +#include "mongoose_config.h" // keep this include #endif #if !defined(MG_ARCH) -#error "MG_ARCH is not specified and we couldn't guess it. Define MG_ARCH=... in mongoose_config.h" +#error \ + "MG_ARCH is not specified and we couldn't guess it. Define MG_ARCH=... in mongoose_config.h" #endif // http://esr.ibiblio.org/?p=5095 -#define MG_BIG_ENDIAN (*(uint16_t *) "\0\xff" < 0x100) - - - - - - - - - - - - - - - - +#define MG_BIG_ENDIAN (*(uint16_t *)"\0\xff" < 0x100) #if MG_ARCH == MG_ARCH_ARMCGT @@ -100,7 +84,6 @@ extern "C" { #endif - #if MG_ARCH == MG_ARCH_ARMGCC #define _POSIX_TIMERS @@ -123,7 +106,6 @@ extern "C" { #endif - #if MG_ARCH == MG_ARCH_CUBE #include @@ -156,10 +138,11 @@ extern "C" { #endif #ifndef MG_ENABLE_TCPIP -#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack +#define MG_ENABLE_TCPIP 1 // Enable built-in TCP/IP stack #endif -#if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_STM32F) && !defined(MG_ENABLE_DRIVER_STM32H) +#if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_STM32F) && \ + !defined(MG_ENABLE_DRIVER_STM32H) #if defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || defined(STM32F7) #define MG_ENABLE_DRIVER_STM32F 1 #elif defined(STM32H5) || defined(STM32H7) @@ -173,7 +156,8 @@ extern "C" { #define MG_TLS MG_TLS_BUILTIN #endif -#if !defined(MG_OTA) && defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || defined(STM32F7) +#if !defined(MG_OTA) && defined(STM32F1) || defined(STM32F2) || \ + defined(STM32F4) || defined(STM32F7) #define MG_OTA MG_OTA_STM32F #elif !defined(MG_OTA) && defined(STM32H5) #define MG_OTA MG_OTA_STM32H5 @@ -185,30 +169,31 @@ extern "C" { #ifndef HAL_ICACHE_MODULE_ENABLED #define HAL_ICACHE_IsEnabled() 0 -#define HAL_ICACHE_Enable() (void) 0 -#define HAL_ICACHE_Disable() (void) 0 +#define HAL_ICACHE_Enable() (void)0 +#define HAL_ICACHE_Disable() (void)0 #endif #ifndef MG_SET_MAC_ADDRESS // Construct MAC address from UUID -#define MGUID ((uint32_t *) UID_BASE) // Unique 96-bit chip ID -#define MG_SET_MAC_ADDRESS(mac) \ - do { \ - int icache_enabled_ = HAL_ICACHE_IsEnabled(); \ - if (icache_enabled_) HAL_ICACHE_Disable(); \ - mac[0] = 42; \ - mac[1] = ((MGUID[0] >> 0) & 255) ^ ((MGUID[2] >> 19) & 255); \ - mac[2] = ((MGUID[0] >> 10) & 255) ^ ((MGUID[1] >> 10) & 255); \ - mac[3] = (MGUID[0] >> 19) & 255; \ - mac[4] = ((MGUID[1] >> 0) & 255) ^ ((MGUID[2] >> 10) & 255); \ - mac[5] = ((MGUID[2] >> 0) & 255) ^ ((MGUID[1] >> 19) & 255); \ - if (icache_enabled_) HAL_ICACHE_Enable(); \ +#define MGUID ((uint32_t *)UID_BASE) // Unique 96-bit chip ID +#define MG_SET_MAC_ADDRESS(mac) \ + do { \ + int icache_enabled_ = HAL_ICACHE_IsEnabled(); \ + if (icache_enabled_) \ + HAL_ICACHE_Disable(); \ + mac[0] = 42; \ + mac[1] = ((MGUID[0] >> 0) & 255) ^ ((MGUID[2] >> 19) & 255); \ + mac[2] = ((MGUID[0] >> 10) & 255) ^ ((MGUID[1] >> 10) & 255); \ + mac[3] = (MGUID[0] >> 19) & 255; \ + mac[4] = ((MGUID[1] >> 0) & 255) ^ ((MGUID[2] >> 10) & 255); \ + mac[5] = ((MGUID[2] >> 0) & 255) ^ ((MGUID[1] >> 19) & 255); \ + if (icache_enabled_) \ + HAL_ICACHE_Enable(); \ } while (0) #endif #endif - #if MG_ARCH == MG_ARCH_ESP32 #include @@ -226,8 +211,8 @@ extern "C" { #include #include -#include // Use angle brackets to avoid -#include // amalgamation ditching them +#include // Use angle brackets to avoid +#include // amalgamation ditching them #define MG_PATH_MAX 128 @@ -241,7 +226,6 @@ extern "C" { #endif - #if MG_ARCH == MG_ARCH_ESP8266 #include @@ -267,7 +251,6 @@ extern "C" { #endif - #if MG_ARCH == MG_ARCH_FREERTOS #include @@ -279,7 +262,7 @@ extern "C" { #include #include #include -#include // rand(), strtol(), atoi() +#include // rand(), strtol(), atoi() #include #if defined(__ARMCC_VERSION) #define mode_t size_t @@ -295,14 +278,13 @@ extern "C" { #define MG_ENABLE_CUSTOM_CALLOC 1 -static inline void mg_free(void *ptr) { - vPortFree(ptr); -} +static inline void mg_free(void *ptr) { vPortFree(ptr); } // Re-route calloc/free to the FreeRTOS's functions, don't use stdlib static inline void *mg_calloc(size_t cnt, size_t size) { void *p = pvPortMalloc(cnt * size); - if (p != NULL) memset(p, 0, size * cnt); + if (p != NULL) + memset(p, 0, size * cnt); return p; } @@ -310,13 +292,12 @@ static inline void *mg_calloc(size_t cnt, size_t size) { #else #define mkdir(a, b) mg_mkdir(a, b) static inline int mg_mkdir(const char *path, mode_t mode) { - (void) path, (void) mode; + (void)path, (void)mode; return -1; } #endif -#endif // MG_ARCH == MG_ARCH_FREERTOS - +#endif // MG_ARCH == MG_ARCH_FREERTOS #if MG_ARCH == MG_ARCH_PICOSDK #if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP @@ -330,8 +311,8 @@ static inline int mg_mkdir(const char *path, mode_t mode) { #include #include -#include #include +#include int mkdir(const char *, mode_t); #if MG_OTA == MG_OTA_PICOSDK @@ -341,21 +322,20 @@ int mkdir(const char *, mode_t); #endif - #if MG_ARCH == MG_ARCH_RTTHREAD -#include #include #include #include -#include -#include +#include #include #include #include #include #include #include +#include +#include #include #include @@ -365,10 +345,10 @@ int mkdir(const char *, mode_t); #endif // MG_ARCH == MG_ARCH_RTTHREAD - -#if MG_ARCH == MG_ARCH_ARMCC || MG_ARCH == MG_ARCH_CMSIS_RTOS1 || \ +#if MG_ARCH == MG_ARCH_ARMCC || MG_ARCH == MG_ARCH_CMSIS_RTOS1 || \ MG_ARCH == MG_ARCH_CMSIS_RTOS2 +#include #include #include #include @@ -377,30 +357,29 @@ int mkdir(const char *, mode_t); #include #include #include -#include #include #include #if MG_ARCH == MG_ARCH_CMSIS_RTOS1 -#include "cmsis_os.h" // keep this include +#include "cmsis_os.h" // keep this include // https://developer.arm.com/documentation/ka003821/latest extern uint32_t rt_time_get(void); #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2 -#include "cmsis_os2.h" // keep this include +#include "cmsis_os2.h" // keep this include #endif -#define strdup(s) ((char *) mg_strdup(mg_str(s)).buf) +#define strdup(s) ((char *)mg_strdup(mg_str(s)).buf) #if defined(__ARMCC_VERSION) #define mode_t size_t #define mkdir(a, b) mg_mkdir(a, b) static inline int mg_mkdir(const char *path, mode_t mode) { - (void) path, (void) mode; + (void)path, (void)mode; return -1; } #endif -#if (MG_ARCH == MG_ARCH_CMSIS_RTOS1 || MG_ARCH == MG_ARCH_CMSIS_RTOS2) && \ - !defined MG_ENABLE_RL && (!defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP) && \ +#if (MG_ARCH == MG_ARCH_CMSIS_RTOS1 || MG_ARCH == MG_ARCH_CMSIS_RTOS2) && \ + !defined MG_ENABLE_RL && (!defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP) && \ (!defined(MG_ENABLE_TCPIP) || !MG_ENABLE_TCPIP) #define MG_ENABLE_RL 1 #ifndef MG_SOCK_LISTEN_BACKLOG_SIZE @@ -410,7 +389,6 @@ static inline int mg_mkdir(const char *path, mode_t mode) { #endif - #if MG_ARCH == MG_ARCH_THREADX #include @@ -453,15 +431,14 @@ static inline int mg_mkdir(const char *path, mode_t mode) { #endif - #if MG_ARCH == MG_ARCH_TIRTOS -#include #include #include #include #include #include +#include #include #include @@ -472,10 +449,9 @@ static inline int mg_mkdir(const char *path, mode_t mode) { #endif - #if MG_ARCH == MG_ARCH_UNIX -#define _DARWIN_UNLIMITED_SELECT 1 // No limit on file descriptors +#define _DARWIN_UNLIMITED_SELECT 1 // No limit on file descriptors #if defined(__APPLE__) #include @@ -539,14 +515,13 @@ static inline int mg_mkdir(const char *path, mode_t mode) { #endif - #if MG_ARCH == MG_ARCH_WIN32 // Avoid name clashing; (macro expansion producing 'defined' has undefined // behaviour). See config.h for user options #ifndef MG_ENABLE_WINSOCK -#if (!defined(MG_ENABLE_TCPIP) || !MG_ENABLE_TCPIP) && \ - (!defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP) && \ +#if (!defined(MG_ENABLE_TCPIP) || !MG_ENABLE_TCPIP) && \ + (!defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP) && \ (!defined(MG_ENABLE_FREERTOS_TCP) || !MG_ENABLE_FREERTOS_TCP) #define MG_ENABLE_WINSOCK 1 #else @@ -596,7 +571,7 @@ static inline int mg_mkdir(const char *path, mode_t mode) { #include #include -#include // fix missing macros and types +#include // fix missing macros and types #if defined(_MSC_VER) && _MSC_VER < 1700 #define __func__ "" @@ -627,17 +602,17 @@ typedef enum { false = 0, true = 1 } bool; #endif #if defined(_MSC_VER) && _MSC_VER <= 1200 - #ifndef IPPROTO_IP - #define IPPROTO_IP 0 - #endif +#ifndef IPPROTO_IP +#define IPPROTO_IP 0 +#endif - #ifndef IP_ADD_MEMBERSHIP - struct ip_mreq { - struct in_addr imr_multiaddr; - struct in_addr imr_interface; - }; - #define IP_ADD_MEMBERSHIP 12 - #endif +#ifndef IP_ADD_MEMBERSHIP +struct ip_mreq { + struct in_addr imr_multiaddr; + struct in_addr imr_interface; +}; +#define IP_ADD_MEMBERSHIP 12 +#endif #endif // Protect from calls like std::snprintf in app code @@ -645,7 +620,7 @@ typedef enum { false = 0, true = 1 } bool; #ifndef __cplusplus #define snprintf _snprintf #define vsnprintf _vsnprintf -#ifndef strdup // For MSVC with _DEBUG, see #1359 +#ifndef strdup // For MSVC with _DEBUG, see #1359 #define strdup(x) _strdup(x) #endif #endif @@ -675,28 +650,28 @@ typedef unsigned long nfds_t; typedef int socklen_t; #ifndef SO_EXCLUSIVEADDRUSE -#define SO_EXCLUSIVEADDRUSE ((int) (~SO_REUSEADDR)) +#define SO_EXCLUSIVEADDRUSE ((int)(~SO_REUSEADDR)) #endif #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? WSAGetLastError() : 0) -#define MG_SOCK_PENDING(errcode) \ - (((errcode) < 0) && \ - (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEINPROGRESS || \ +#define MG_SOCK_PENDING(errcode) \ + (((errcode) < 0) && \ + (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEINPROGRESS || \ WSAGetLastError() == WSAEWOULDBLOCK)) -#define MG_SOCK_RESET(errcode) \ +#define MG_SOCK_RESET(errcode) \ (((errcode) < 0) && (WSAGetLastError() == WSAECONNRESET)) -#endif // MG_ENABLE_WINSOCK +#endif // MG_ENABLE_WINSOCK #define realpath(a, b) _fullpath((b), (a), MG_PATH_MAX) -#define sleep(x) Sleep((x) *1000) +#define sleep(x) Sleep((x) * 1000) #define mkdir(a, b) _mkdir(a) #define timegm(x) _mkgmtime(x) #ifndef S_ISDIR -#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR) +#define S_ISDIR(x) (((x) & _S_IFMT) == _S_IFDIR) #endif #ifndef MG_ENABLE_DIRLIST @@ -717,7 +692,6 @@ typedef int socklen_t; #endif - #if MG_ARCH == MG_ARCH_ZEPHYR #include @@ -725,9 +699,6 @@ typedef int socklen_t; #include #include -#include -#include -#include #include #include #include @@ -736,10 +707,13 @@ typedef int socklen_t; #include #include #include +#include +#include +#include #define MG_PUTCHAR(x) printk("%c", x) #ifndef strdup -#define strdup(s) ((char *) mg_strdup(mg_str(s)).buf) +#define strdup(s) ((char *)mg_strdup(mg_str(s)).buf) #endif #define strerror(x) zsock_gai_strerror(x) @@ -758,7 +732,6 @@ int sscanf(const char *, const char *, ...); #endif - #if defined(MG_ENABLE_FREERTOS_TCP) && MG_ENABLE_FREERTOS_TCP #include @@ -784,10 +757,10 @@ int sscanf(const char *, const char *, ...); #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? (errcode) : 0) -#define MG_SOCK_PENDING(errcode) \ - ((errcode) == -pdFREERTOS_ERRNO_EWOULDBLOCK || \ - (errcode) == -pdFREERTOS_ERRNO_EISCONN || \ - (errcode) == -pdFREERTOS_ERRNO_EINPROGRESS || \ +#define MG_SOCK_PENDING(errcode) \ + ((errcode) == -pdFREERTOS_ERRNO_EWOULDBLOCK || \ + (errcode) == -pdFREERTOS_ERRNO_EISCONN || \ + (errcode) == -pdFREERTOS_ERRNO_EINPROGRESS || \ (errcode) == -pdFREERTOS_ERRNO_EAGAIN) #define MG_SOCK_RESET(errcode) ((errcode) == -pdFREERTOS_ERRNO_ENOTCONN) @@ -809,7 +782,7 @@ int sscanf(const char *, const char *, ...); #define recv(a, b, c, d) FreeRTOS_recv((a), (b), (c), (d)) #define setsockopt(a, b, c, d, e) FreeRTOS_setsockopt((a), (b), (c), (d), (e)) #define sendto(a, b, c, d, e, f) FreeRTOS_sendto((a), (b), (c), (d), (e), (f)) -#define recvfrom(a, b, c, d, e, f) \ +#define recvfrom(a, b, c, d, e, f) \ FreeRTOS_recvfrom((a), (b), (c), (d), (e), (f)) #define closesocket(x) FreeRTOS_closesocket(x) #define gethostbyname(x) FreeRTOS_gethostbyname(x) @@ -817,17 +790,16 @@ int sscanf(const char *, const char *, ...); #define getpeername(a, b, c) mg_getpeername((a), (b), (c)) static inline int mg_getsockname(MG_SOCKET_TYPE fd, void *buf, socklen_t *len) { - (void) fd, (void) buf, (void) len; + (void)fd, (void)buf, (void)len; return -1; } static inline int mg_getpeername(MG_SOCKET_TYPE fd, void *buf, socklen_t *len) { - (void) fd, (void) buf, (void) len; + (void)fd, (void)buf, (void)len; return 0; } #endif - #if defined(MG_ENABLE_LWIP) && MG_ENABLE_LWIP #if defined(__GNUC__) && !defined(__ARMCC_VERSION) @@ -855,7 +827,6 @@ struct timeval { #endif #endif - #if defined(MG_ENABLE_RL) && MG_ENABLE_RL #include @@ -865,11 +836,11 @@ struct timeval { #define MG_SOCK_ERR(errcode) ((errcode) < 0 ? (errcode) : 0) -#define MG_SOCK_PENDING(errcode) \ - ((errcode) == BSD_EWOULDBLOCK || (errcode) == BSD_EALREADY || \ +#define MG_SOCK_PENDING(errcode) \ + ((errcode) == BSD_EWOULDBLOCK || (errcode) == BSD_EALREADY || \ (errcode) == BSD_EINPROGRESS) -#define MG_SOCK_RESET(errcode) \ +#define MG_SOCK_RESET(errcode) \ ((errcode) == BSD_ECONNABORTED || (errcode) == BSD_ECONNRESET) // In blocking mode, which is enabled by default, accept() waits for a @@ -880,7 +851,6 @@ struct timeval { #define socklen_t int #endif - #ifndef MG_ENABLE_LOG #define MG_ENABLE_LOG 1 #endif @@ -890,23 +860,23 @@ struct timeval { #endif #ifndef MG_ENABLE_CUSTOM_LOG -#define MG_ENABLE_CUSTOM_LOG 0 // Let user define their own MG_LOG +#define MG_ENABLE_CUSTOM_LOG 0 // Let user define their own MG_LOG #endif #ifndef MG_ENABLE_TCPIP -#define MG_ENABLE_TCPIP 0 // Mongoose built-in network stack +#define MG_ENABLE_TCPIP 0 // Mongoose built-in network stack #endif #ifndef MG_ENABLE_LWIP -#define MG_ENABLE_LWIP 0 // lWIP network stack +#define MG_ENABLE_LWIP 0 // lWIP network stack #endif #ifndef MG_ENABLE_FREERTOS_TCP -#define MG_ENABLE_FREERTOS_TCP 0 // Amazon FreeRTOS-TCP network stack +#define MG_ENABLE_FREERTOS_TCP 0 // Amazon FreeRTOS-TCP network stack #endif #ifndef MG_ENABLE_RL -#define MG_ENABLE_RL 0 // ARM MDK network stack +#define MG_ENABLE_RL 0 // ARM MDK network stack #endif #ifndef MG_ENABLE_SOCKET @@ -934,7 +904,7 @@ struct timeval { #endif #ifndef MG_IPV6_V6ONLY -#define MG_IPV6_V6ONLY 0 // IPv6 socket binds only to V6, not V4 address +#define MG_IPV6_V6ONLY 0 // IPv6 socket binds only to V6, not V4 address #endif #ifndef MG_ENABLE_MD5 @@ -968,15 +938,15 @@ struct timeval { #endif #ifndef MG_IO_SIZE -#define MG_IO_SIZE 512 // Granularity of the send/recv IO buffer growth +#define MG_IO_SIZE 512 // Granularity of the send/recv IO buffer growth #endif #ifndef MG_MAX_RECV_SIZE -#define MG_MAX_RECV_SIZE (3UL * 1024UL * 1024UL) // Maximum recv IO buffer size +#define MG_MAX_RECV_SIZE (3UL * 1024UL * 1024UL) // Maximum recv IO buffer size #endif #ifndef MG_DATA_SIZE -#define MG_DATA_SIZE 32 // struct mg_connection :: data size +#define MG_DATA_SIZE 32 // struct mg_connection :: data size #endif #ifndef MG_MAX_HTTP_HEADERS @@ -1020,16 +990,17 @@ struct timeval { #endif #if MG_ENABLE_EPOLL -#define MG_EPOLL_ADD(c) \ - do { \ - struct epoll_event ev = {EPOLLIN | EPOLLERR | EPOLLHUP, {c}}; \ - epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_ADD, (int) (size_t) c->fd, &ev); \ +#define MG_EPOLL_ADD(c) \ + do { \ + struct epoll_event ev = {EPOLLIN | EPOLLERR | EPOLLHUP, {c}}; \ + epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_ADD, (int)(size_t)c->fd, &ev); \ } while (0) -#define MG_EPOLL_MOD(c, wr) \ - do { \ - struct epoll_event ev = {EPOLLIN | EPOLLERR | EPOLLHUP, {c}}; \ - if (wr) ev.events |= EPOLLOUT; \ - epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_MOD, (int) (size_t) c->fd, &ev); \ +#define MG_EPOLL_MOD(c, wr) \ + do { \ + struct epoll_event ev = {EPOLLIN | EPOLLERR | EPOLLHUP, {c}}; \ + if (wr) \ + ev.events |= EPOLLOUT; \ + epoll_ctl(c->mgr->epoll_fd, EPOLL_CTL_MOD, (int)(size_t)c->fd, &ev); \ } while (0) #else #define MG_EPOLL_ADD(c) @@ -1040,20 +1011,20 @@ struct timeval { #define MG_ENABLE_PROFILE 0 #endif -#ifndef MG_ENABLE_TCPIP_DRIVER_INIT // mg_mgr_init() will also initialize -#define MG_ENABLE_TCPIP_DRIVER_INIT 1 // enabled built-in driver for -#endif // Mongoose built-in network stack +#ifndef MG_ENABLE_TCPIP_DRIVER_INIT // mg_mgr_init() will also initialize +#define MG_ENABLE_TCPIP_DRIVER_INIT 1 // enabled built-in driver for +#endif // Mongoose built-in network stack -#ifndef MG_TCPIP_IP // e.g. MG_IPV4(192, 168, 0, 223) -#define MG_TCPIP_IP MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP) +#ifndef MG_TCPIP_IP // e.g. MG_IPV4(192, 168, 0, 223) +#define MG_TCPIP_IP MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP) #endif #ifndef MG_TCPIP_MASK -#define MG_TCPIP_MASK MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP) +#define MG_TCPIP_MASK MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP) #endif #ifndef MG_TCPIP_GW -#define MG_TCPIP_GW MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP) +#define MG_TCPIP_GW MG_IPV4(0, 0, 0, 0) // Default is 0.0.0.0 (DHCP) #endif #ifndef MG_SET_MAC_ADDRESS @@ -1069,11 +1040,9 @@ struct timeval { #endif #ifndef MG_ENABLE_CHACHA20 -#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN +#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN #endif - - // Macros to record timestamped events that happens with a connection. // They are saved into a c->prof IO buffer, each event is a name and a 32-bit // timestamp in milliseconds since connection init time. @@ -1082,10 +1051,10 @@ struct timeval { // make -C tutorials/http/http-server/ CFLAGS_EXTRA=-DMG_ENABLE_PROFILE=1 // curl localhost:8000 // Output: -// 1ea1f1e7 2 net.c:150:mg_close_conn 3 profile: -// 1ea1f1e8 2 net.c:150:mg_close_conn 1ea1f1e6 init +// 1ea1f1e7 2 net.c:150:mg_close_conn 3 profile: +// 1ea1f1e8 2 net.c:150:mg_close_conn 1ea1f1e6 init // 1ea1f1e8 2 net.c:150:mg_close_conn 0 EV_OPEN -// 1ea1f1e8 2 net.c:150:mg_close_conn 0 EV_ACCEPT +// 1ea1f1e8 2 net.c:150:mg_close_conn 0 EV_ACCEPT // 1ea1f1e8 2 net.c:150:mg_close_conn 0 EV_READ // 1ea1f1e8 2 net.c:150:mg_close_conn 0 EV_HTTP_MSG // 1ea1f1e8 2 net.c:150:mg_close_conn 0 EV_WRITE @@ -1097,46 +1066,46 @@ struct timeval { #if MG_ENABLE_PROFILE struct mg_profitem { - const char *name; // Event name - uint32_t timestamp; // Milliseconds since connection creation (MG_EV_OPEN) + const char *name; // Event name + uint32_t timestamp; // Milliseconds since connection creation (MG_EV_OPEN) }; -#define MG_PROFILE_ALLOC_GRANULARITY 256 // Can save 32 items wih to realloc +#define MG_PROFILE_ALLOC_GRANULARITY 256 // Can save 32 items wih to realloc // Adding a profile item to the c->prof. Must be as fast as possible. // Reallocation of the c->prof iobuf is not desirable here, that's why we // pre-allocate c->prof with MG_PROFILE_ALLOC_GRANULARITY. // This macro just inits and copies 8 bytes, and calls mg_millis(), // which should be fast enough. -#define MG_PROF_ADD(c, name_) \ - do { \ - struct mg_iobuf *io = &c->prof; \ - uint32_t inittime = ((struct mg_profitem *) io->buf)->timestamp; \ - struct mg_profitem item = {name_, (uint32_t) mg_millis() - inittime}; \ - mg_iobuf_add(io, io->len, &item, sizeof(item)); \ +#define MG_PROF_ADD(c, name_) \ + do { \ + struct mg_iobuf *io = &c->prof; \ + uint32_t inittime = ((struct mg_profitem *)io->buf)->timestamp; \ + struct mg_profitem item = {name_, (uint32_t)mg_millis() - inittime}; \ + mg_iobuf_add(io, io->len, &item, sizeof(item)); \ } while (0) // Initialising profile for a new connection. Not time sensitive -#define MG_PROF_INIT(c) \ - do { \ - struct mg_profitem first = {"init", (uint32_t) mg_millis()}; \ - mg_iobuf_init(&(c)->prof, 0, MG_PROFILE_ALLOC_GRANULARITY); \ - mg_iobuf_add(&c->prof, c->prof.len, &first, sizeof(first)); \ +#define MG_PROF_INIT(c) \ + do { \ + struct mg_profitem first = {"init", (uint32_t)mg_millis()}; \ + mg_iobuf_init(&(c)->prof, 0, MG_PROFILE_ALLOC_GRANULARITY); \ + mg_iobuf_add(&c->prof, c->prof.len, &first, sizeof(first)); \ } while (0) #define MG_PROF_FREE(c) mg_iobuf_free(&(c)->prof) // Dumping the profile. Not time sensitive -#define MG_PROF_DUMP(c) \ - do { \ - struct mg_iobuf *io = &c->prof; \ - struct mg_profitem *p = (struct mg_profitem *) io->buf; \ - struct mg_profitem *e = &p[io->len / sizeof(*p)]; \ - MG_INFO(("%lu profile:", c->id)); \ - while (p < e) { \ - MG_INFO(("%5lx %s", (unsigned long) p->timestamp, p->name)); \ - p++; \ - } \ +#define MG_PROF_DUMP(c) \ + do { \ + struct mg_iobuf *io = &c->prof; \ + struct mg_profitem *p = (struct mg_profitem *)io->buf; \ + struct mg_profitem *e = &p[io->len / sizeof(*p)]; \ + MG_INFO(("%lu profile:", c->id)); \ + while (p < e) { \ + MG_INFO(("%5lx %s", (unsigned long)p->timestamp, p->name)); \ + p++; \ + } \ } while (0) #else @@ -1146,13 +1115,10 @@ struct mg_profitem { #define MG_PROF_DUMP(c) #endif - - - // Describes an arbitrary chunk of memory struct mg_str { - char *buf; // String data - size_t len; // String length + char *buf; // String data + size_t len; // String length }; // Using macro to avoid shadowing C++ struct constructor, see #1298 @@ -1169,9 +1135,6 @@ bool mg_span(struct mg_str s, struct mg_str *a, struct mg_str *b, char delim); bool mg_str_to_num(struct mg_str, int base, void *val, size_t val_len); - - - // Single producer, single consumer non-blocking queue struct mg_queue { @@ -1181,26 +1144,18 @@ struct mg_queue { volatile size_t head; }; -void mg_queue_init(struct mg_queue *, char *, size_t); // Init queue -size_t mg_queue_book(struct mg_queue *, char **buf, size_t); // Reserve space -void mg_queue_add(struct mg_queue *, size_t); // Add new message -size_t mg_queue_next(struct mg_queue *, char **); // Get oldest message -void mg_queue_del(struct mg_queue *, size_t); // Delete oldest message +void mg_queue_init(struct mg_queue *, char *, size_t); // Init queue +size_t mg_queue_book(struct mg_queue *, char **buf, size_t); // Reserve space +void mg_queue_add(struct mg_queue *, size_t); // Add new message +size_t mg_queue_next(struct mg_queue *, char **); // Get oldest message +void mg_queue_del(struct mg_queue *, size_t); // Delete oldest message - - - -typedef void (*mg_pfn_t)(char, void *); // Output function -typedef size_t (*mg_pm_t)(mg_pfn_t, void *, va_list *); // %M printer +typedef void (*mg_pfn_t)(char, void *); // Output function +typedef size_t (*mg_pm_t)(mg_pfn_t, void *, va_list *); // %M printer size_t mg_vxprintf(void (*)(char, void *), void *, const char *fmt, va_list *); size_t mg_xprintf(void (*fn)(char, void *), void *, const char *fmt, ...); - - - - - // Convenience wrappers around mg_xprintf size_t mg_vsnprintf(char *buf, size_t len, const char *fmt, va_list *ap); size_t mg_snprintf(char *, size_t, const char *fmt, ...); @@ -1220,19 +1175,14 @@ size_t mg_print_ip6(void (*out)(char, void *), void *arg, va_list *ap); size_t mg_print_mac(void (*out)(char, void *), void *arg, va_list *ap); // Various output functions -void mg_pfn_iobuf(char ch, void *param); // param: struct mg_iobuf * -void mg_pfn_stdout(char c, void *param); // param: ignored +void mg_pfn_iobuf(char ch, void *param); // param: struct mg_iobuf * +void mg_pfn_stdout(char c, void *param); // param: ignored // A helper macro for printing JSON: mg_snprintf(buf, len, "%m", MG_ESC("hi")) #define MG_ESC(str) mg_print_esc, 0, (str) - - - - - enum { MG_LL_NONE, MG_LL_ERROR, MG_LL_INFO, MG_LL_DEBUG, MG_LL_VERBOSE }; -extern int mg_log_level; // Current log level, one of MG_LL_* +extern int mg_log_level; // Current log level, one of MG_LL_* void mg_log(const char *fmt, ...); void mg_log_prefix(int ll, const char *file, int line, const char *fname); @@ -1243,17 +1193,18 @@ void mg_log_set_fn(mg_pfn_t fn, void *param); #define mg_log_set(level_) mg_log_level = (level_) #if MG_ENABLE_LOG -#define MG_LOG(level, args) \ - do { \ - if ((level) <= mg_log_level) { \ - mg_log_prefix((level), __FILE__, __LINE__, __func__); \ - mg_log args; \ - } \ +#define MG_LOG(level, args) \ + do { \ + if ((level) <= mg_log_level) { \ + mg_log_prefix((level), __FILE__, __LINE__, __func__); \ + mg_log args; \ + } \ } while (0) #else -#define MG_LOG(level, args) \ - do { \ - if (0) mg_log args; \ +#define MG_LOG(level, args) \ + do { \ + if (0) \ + mg_log args; \ } while (0) #endif @@ -1262,21 +1213,18 @@ void mg_log_set_fn(mg_pfn_t fn, void *param); #define MG_DEBUG(args) MG_LOG(MG_LL_DEBUG, args) #define MG_VERBOSE(args) MG_LOG(MG_LL_VERBOSE, args) - - - struct mg_timer { - uint64_t period_ms; // Timer period in milliseconds - uint64_t expire; // Expiration timestamp in milliseconds - unsigned flags; // Possible flags values below -#define MG_TIMER_ONCE 0 // Call function once -#define MG_TIMER_REPEAT 1 // Call function periodically -#define MG_TIMER_RUN_NOW 2 // Call immediately when timer is set -#define MG_TIMER_CALLED 4 // Timer function was called at least once -#define MG_TIMER_AUTODELETE 8 // mg_free() timer when done - void (*fn)(void *); // Function to call - void *arg; // Function argument - struct mg_timer *next; // Linkage + uint64_t period_ms; // Timer period in milliseconds + uint64_t expire; // Expiration timestamp in milliseconds + unsigned flags; // Possible flags values below +#define MG_TIMER_ONCE 0 // Call function once +#define MG_TIMER_REPEAT 1 // Call function periodically +#define MG_TIMER_RUN_NOW 2 // Call immediately when timer is set +#define MG_TIMER_CALLED 4 // Timer function was called at least once +#define MG_TIMER_AUTODELETE 8 // mg_free() timer when done + void (*fn)(void *); // Function to call + void *arg; // Function argument + struct mg_timer *next; // Linkage }; void mg_timer_init(struct mg_timer **head, struct mg_timer *timer, @@ -1286,10 +1234,6 @@ void mg_timer_free(struct mg_timer **head, struct mg_timer *); void mg_timer_poll(struct mg_timer **head, uint64_t new_ms); bool mg_timer_expired(uint64_t *expiration, uint64_t period, uint64_t now); - - - - enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4 }; // Filesystem API functions @@ -1300,23 +1244,23 @@ enum { MG_FS_READ = 1, MG_FS_WRITE = 2, MG_FS_DIR = 4 }; // chosen to avoid conflicts with some libraries that make macros for e.g. // stat(), write(), read() calls. struct mg_fs { - int (*st)(const char *path, size_t *size, time_t *mtime); // stat file + int (*st)(const char *path, size_t *size, time_t *mtime); // stat file void (*ls)(const char *path, void (*fn)(const char *, void *), - void *); // List directory entries: call fn(file_name, fn_data) - // for each directory entry - void *(*op)(const char *path, int flags); // Open file - void (*cl)(void *fd); // Close file - size_t (*rd)(void *fd, void *buf, size_t len); // Read file - size_t (*wr)(void *fd, const void *buf, size_t len); // Write file - size_t (*sk)(void *fd, size_t offset); // Set file position - bool (*mv)(const char *from, const char *to); // Rename file - bool (*rm)(const char *path); // Delete file - bool (*mkd)(const char *path); // Create directory + void *); // List directory entries: call fn(file_name, fn_data) + // for each directory entry + void *(*op)(const char *path, int flags); // Open file + void (*cl)(void *fd); // Close file + size_t (*rd)(void *fd, void *buf, size_t len); // Read file + size_t (*wr)(void *fd, const void *buf, size_t len); // Write file + size_t (*sk)(void *fd, size_t offset); // Set file position + bool (*mv)(const char *from, const char *to); // Rename file + bool (*rm)(const char *path); // Delete file + bool (*mkd)(const char *path); // Create directory }; -extern struct mg_fs mg_fs_posix; // POSIX open/close/read/write/seek -extern struct mg_fs mg_fs_packed; // see tutorials/core/embedded-filesystem -extern struct mg_fs mg_fs_fat; // FAT FS +extern struct mg_fs mg_fs_posix; // POSIX open/close/read/write/seek +extern struct mg_fs mg_fs_packed; // see tutorials/core/embedded-filesystem +extern struct mg_fs mg_fs_fat; // FAT FS // File descriptor struct mg_fd { @@ -1333,14 +1277,8 @@ bool mg_file_printf(struct mg_fs *fs, const char *path, const char *fmt, ...); // Packed API const char *mg_unpack(const char *path, size_t *size, time_t *mtime); -const char *mg_unlist(size_t no); // Get no'th packed filename -struct mg_str mg_unpacked(const char *path); // Packed file as mg_str - - - - - - +const char *mg_unlist(size_t no); // Get no'th packed filename +struct mg_str mg_unpacked(const char *path); // Packed file as mg_str #if MG_ENABLE_ASSERT #include @@ -1354,47 +1292,47 @@ void mg_bzero(volatile unsigned char *buf, size_t len); bool mg_random(void *buf, size_t len); char *mg_random_str(char *buf, size_t len); uint32_t mg_crc32(uint32_t crc, const char *buf, size_t len); -uint64_t mg_millis(void); // Return milliseconds since boot +uint64_t mg_millis(void); // Return milliseconds since boot bool mg_path_is_sane(const struct mg_str path); void mg_delayms(unsigned int ms); -#define MG_U32(a, b, c, d) \ - (((uint32_t) ((a) &255) << 24) | ((uint32_t) ((b) &255) << 16) | \ - ((uint32_t) ((c) &255) << 8) | (uint32_t) ((d) &255)) +#define MG_U32(a, b, c, d) \ + (((uint32_t)((a) & 255) << 24) | ((uint32_t)((b) & 255) << 16) | \ + ((uint32_t)((c) & 255) << 8) | (uint32_t)((d) & 255)) #define MG_IPV4(a, b, c, d) mg_htonl(MG_U32(a, b, c, d)) // For printing IPv4 addresses: printf("%d.%d.%d.%d\n", MG_IPADDR_PARTS(&ip)) -#define MG_U8P(ADDR) ((uint8_t *) (ADDR)) -#define MG_IPADDR_PARTS(ADDR) \ +#define MG_U8P(ADDR) ((uint8_t *)(ADDR)) +#define MG_IPADDR_PARTS(ADDR) \ MG_U8P(ADDR)[0], MG_U8P(ADDR)[1], MG_U8P(ADDR)[2], MG_U8P(ADDR)[3] -#define MG_LOAD_BE16(p) \ - ((uint16_t) (((uint16_t) MG_U8P(p)[0] << 8U) | MG_U8P(p)[1])) -#define MG_LOAD_BE24(p) \ - ((uint32_t) (((uint32_t) MG_U8P(p)[0] << 16U) | \ - ((uint32_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[2])) -#define MG_LOAD_BE32(p) \ - ((uint32_t) (((uint32_t) MG_U8P(p)[0] << 24U) | \ - ((uint32_t) MG_U8P(p)[1] << 16U) | \ - ((uint32_t) MG_U8P(p)[2] << 8U) | MG_U8P(p)[3])) -#define MG_STORE_BE16(p, n) \ - do { \ - MG_U8P(p)[0] = ((n) >> 8U) & 255; \ - MG_U8P(p)[1] = (n) &255; \ +#define MG_LOAD_BE16(p) \ + ((uint16_t)(((uint16_t)MG_U8P(p)[0] << 8U) | MG_U8P(p)[1])) +#define MG_LOAD_BE24(p) \ + ((uint32_t)(((uint32_t)MG_U8P(p)[0] << 16U) | \ + ((uint32_t)MG_U8P(p)[1] << 8U) | MG_U8P(p)[2])) +#define MG_LOAD_BE32(p) \ + ((uint32_t)(((uint32_t)MG_U8P(p)[0] << 24U) | \ + ((uint32_t)MG_U8P(p)[1] << 16U) | \ + ((uint32_t)MG_U8P(p)[2] << 8U) | MG_U8P(p)[3])) +#define MG_STORE_BE16(p, n) \ + do { \ + MG_U8P(p)[0] = ((n) >> 8U) & 255; \ + MG_U8P(p)[1] = (n) & 255; \ } while (0) -#define MG_STORE_BE24(p, n) \ - do { \ - MG_U8P(p)[0] = ((n) >> 16U) & 255; \ - MG_U8P(p)[1] = ((n) >> 8U) & 255; \ - MG_U8P(p)[2] = (n) &255; \ +#define MG_STORE_BE24(p, n) \ + do { \ + MG_U8P(p)[0] = ((n) >> 16U) & 255; \ + MG_U8P(p)[1] = ((n) >> 8U) & 255; \ + MG_U8P(p)[2] = (n) & 255; \ } while (0) -#define MG_STORE_BE32(p, n) \ - do { \ - MG_U8P(p)[0] = ((n) >> 24U) & 255; \ - MG_U8P(p)[1] = ((n) >> 16U) & 255; \ - MG_U8P(p)[2] = ((n) >> 8U) & 255; \ - MG_U8P(p)[3] = (n) &255; \ +#define MG_STORE_BE32(p, n) \ + do { \ + MG_U8P(p)[0] = ((n) >> 24U) & 255; \ + MG_U8P(p)[1] = ((n) >> 16U) & 255; \ + MG_U8P(p)[2] = ((n) >> 8U) & 255; \ + MG_U8P(p)[3] = (n) & 255; \ } while (0) uint16_t mg_ntohs(uint16_t net); @@ -1402,11 +1340,11 @@ uint32_t mg_ntohl(uint32_t net); #define mg_htons(x) mg_ntohs(x) #define mg_htonl(x) mg_ntohl(x) -#define MG_REG(x) ((volatile uint32_t *) (x))[0] -#define MG_BIT(x) (((uint32_t) 1U) << (x)) +#define MG_REG(x) ((volatile uint32_t *)(x))[0] +#define MG_BIT(x) (((uint32_t)1U) << (x)) #define MG_SET_BITS(R, CLRMASK, SETMASK) (R) = ((R) & ~(CLRMASK)) | (SETMASK) -#define MG_ROUND_UP(x, a) ((a) == 0 ? (x) : ((((x) + (a) -1) / (a)) * (a))) +#define MG_ROUND_UP(x, a) ((a) == 0 ? (x) : ((((x) + (a) - 1) / (a)) * (a))) #define MG_ROUND_DOWN(x, a) ((a) == 0 ? (x) : (((x) / (a)) * (a))) #if defined(__GNUC__) && defined(__arm__) @@ -1445,28 +1383,28 @@ struct mg_addr; int mg_check_ip_acl(struct mg_str acl, struct mg_addr *remote_ip); // Linked list management macros -#define LIST_ADD_HEAD(type_, head_, elem_) \ - do { \ - (elem_)->next = (*head_); \ - *(head_) = (elem_); \ +#define LIST_ADD_HEAD(type_, head_, elem_) \ + do { \ + (elem_)->next = (*head_); \ + *(head_) = (elem_); \ } while (0) -#define LIST_ADD_TAIL(type_, head_, elem_) \ - do { \ - type_ **h = head_; \ - while (*h != NULL) h = &(*h)->next; \ - *h = (elem_); \ +#define LIST_ADD_TAIL(type_, head_, elem_) \ + do { \ + type_ **h = head_; \ + while (*h != NULL) \ + h = &(*h)->next; \ + *h = (elem_); \ } while (0) -#define LIST_DELETE(type_, head_, elem_) \ - do { \ - type_ **h = head_; \ - while (*h != (elem_)) h = &(*h)->next; \ - *h = (elem_)->next; \ +#define LIST_DELETE(type_, head_, elem_) \ + do { \ + type_ **h = head_; \ + while (*h != (elem_)) \ + h = &(*h)->next; \ + *h = (elem_)->next; \ } while (0) - - unsigned short mg_url_port(const char *url); int mg_url_is_ssl(const char *url); struct mg_str mg_url_host(const char *url); @@ -1474,14 +1412,11 @@ struct mg_str mg_url_user(const char *url); struct mg_str mg_url_pass(const char *url); const char *mg_url_uri(const char *url); - - - struct mg_iobuf { - unsigned char *buf; // Pointer to stored data - size_t size; // Total size available - size_t len; // Current number of bytes - size_t align; // Alignment during allocation + unsigned char *buf; // Pointer to stored data + size_t size; // Total size available + size_t len; // Current number of bytes + size_t align; // Alignment during allocation }; int mg_iobuf_init(struct mg_iobuf *, size_t, size_t); @@ -1490,15 +1425,11 @@ void mg_iobuf_free(struct mg_iobuf *); size_t mg_iobuf_add(struct mg_iobuf *, size_t, const void *, size_t); size_t mg_iobuf_del(struct mg_iobuf *, size_t ofs, size_t len); - size_t mg_base64_update(unsigned char input_byte, char *buf, size_t len); size_t mg_base64_final(char *buf, size_t len); size_t mg_base64_encode(const unsigned char *p, size_t n, char *buf, size_t); size_t mg_base64_decode(const char *src, size_t n, char *dst, size_t); - - - typedef struct { uint32_t buf[4]; uint32_t bits[2]; @@ -1509,9 +1440,6 @@ void mg_md5_init(mg_md5_ctx *c); void mg_md5_update(mg_md5_ctx *c, const unsigned char *data, size_t len); void mg_md5_final(mg_md5_ctx *c, unsigned char[16]); - - - typedef struct { uint32_t state[5]; uint32_t count[2]; @@ -1527,10 +1455,6 @@ void mg_sha1_final(unsigned char digest[20], mg_sha1_ctx *); // Details: Defines the API for the corresponding SHA1 implementation. // Copyright: public domain - - - - typedef struct { uint32_t state[8]; uint64_t bits; @@ -1538,7 +1462,6 @@ typedef struct { unsigned char buffer[64]; } mg_sha256_ctx; - void mg_sha256_init(mg_sha256_ctx *); void mg_sha256_update(mg_sha256_ctx *, const unsigned char *data, size_t len); void mg_sha256_final(unsigned char digest[32], mg_sha256_ctx *); @@ -1547,18 +1470,16 @@ void mg_hmac_sha256(uint8_t dst[32], uint8_t *key, size_t keysz, uint8_t *data, size_t datasz); typedef struct { - uint64_t state[8]; - uint8_t buffer[128]; - uint64_t bitlen[2]; - uint32_t datalen; + uint64_t state[8]; + uint8_t buffer[128]; + uint64_t bitlen[2]; + uint32_t datalen; } mg_sha384_ctx; void mg_sha384_init(mg_sha384_ctx *ctx); void mg_sha384_update(mg_sha384_ctx *ctx, const uint8_t *data, size_t len); void mg_sha384_final(uint8_t digest[48], mg_sha384_ctx *ctx); void mg_sha384(uint8_t dst[48], uint8_t *data, size_t datasz); - - struct mg_connection; typedef void (*mg_event_handler_t)(struct mg_connection *, int ev, void *ev_data); @@ -1566,107 +1487,98 @@ void mg_call(struct mg_connection *c, int ev, void *ev_data); void mg_error(struct mg_connection *c, const char *fmt, ...); enum { - MG_EV_ERROR, // Error char *error_message - MG_EV_OPEN, // Connection created NULL - MG_EV_POLL, // mg_mgr_poll iteration uint64_t *uptime_millis - MG_EV_RESOLVE, // Host name is resolved NULL - MG_EV_CONNECT, // Connection established NULL - MG_EV_ACCEPT, // Connection accepted NULL - MG_EV_TLS_HS, // TLS handshake succeeded NULL - MG_EV_READ, // Data received from socket long *bytes_read - MG_EV_WRITE, // Data written to socket long *bytes_written - MG_EV_CLOSE, // Connection closed NULL - MG_EV_HTTP_HDRS, // HTTP headers struct mg_http_message * - MG_EV_HTTP_MSG, // Full HTTP request/response struct mg_http_message * - MG_EV_WS_OPEN, // Websocket handshake done struct mg_http_message * - MG_EV_WS_MSG, // Websocket msg, text or bin struct mg_ws_message * - MG_EV_WS_CTL, // Websocket control msg struct mg_ws_message * - MG_EV_MQTT_CMD, // MQTT low-level command struct mg_mqtt_message * - MG_EV_MQTT_MSG, // MQTT PUBLISH received struct mg_mqtt_message * - MG_EV_MQTT_OPEN, // MQTT CONNACK received int *connack_status_code - MG_EV_SNTP_TIME, // SNTP time received uint64_t *epoch_millis - MG_EV_WAKEUP, // mg_wakeup() data received struct mg_str *data - MG_EV_USER // Starting ID for user events + MG_EV_ERROR, // Error char *error_message + MG_EV_OPEN, // Connection created NULL + MG_EV_POLL, // mg_mgr_poll iteration uint64_t *uptime_millis + MG_EV_RESOLVE, // Host name is resolved NULL + MG_EV_CONNECT, // Connection established NULL + MG_EV_ACCEPT, // Connection accepted NULL + MG_EV_TLS_HS, // TLS handshake succeeded NULL + MG_EV_READ, // Data received from socket long *bytes_read + MG_EV_WRITE, // Data written to socket long *bytes_written + MG_EV_CLOSE, // Connection closed NULL + MG_EV_HTTP_HDRS, // HTTP headers struct mg_http_message * + MG_EV_HTTP_MSG, // Full HTTP request/response struct mg_http_message * + MG_EV_WS_OPEN, // Websocket handshake done struct mg_http_message * + MG_EV_WS_MSG, // Websocket msg, text or bin struct mg_ws_message * + MG_EV_WS_CTL, // Websocket control msg struct mg_ws_message * + MG_EV_MQTT_CMD, // MQTT low-level command struct mg_mqtt_message * + MG_EV_MQTT_MSG, // MQTT PUBLISH received struct mg_mqtt_message * + MG_EV_MQTT_OPEN, // MQTT CONNACK received int *connack_status_code + MG_EV_SNTP_TIME, // SNTP time received uint64_t *epoch_millis + MG_EV_WAKEUP, // mg_wakeup() data received struct mg_str *data + MG_EV_USER // Starting ID for user events }; - - - - - - - - - struct mg_dns { - const char *url; // DNS server URL - struct mg_connection *c; // DNS server connection + const char *url; // DNS server URL + struct mg_connection *c; // DNS server connection }; struct mg_addr { - uint8_t ip[16]; // Holds IPv4 or IPv6 address, in network byte order - uint16_t port; // TCP or UDP port in network byte order - uint8_t scope_id; // IPv6 scope ID - bool is_ip6; // True when address is IPv6 address + uint8_t ip[16]; // Holds IPv4 or IPv6 address, in network byte order + uint16_t port; // TCP or UDP port in network byte order + uint8_t scope_id; // IPv6 scope ID + bool is_ip6; // True when address is IPv6 address }; struct mg_mgr { - struct mg_connection *conns; // List of active connections - struct mg_dns dns4; // DNS for IPv4 - struct mg_dns dns6; // DNS for IPv6 - int dnstimeout; // DNS resolve timeout in milliseconds - bool use_dns6; // Use DNS6 server by default, see #1532 - unsigned long nextid; // Next connection ID - void *userdata; // Arbitrary user data pointer - void *tls_ctx; // TLS context shared by all TLS sessions - uint16_t mqtt_id; // MQTT IDs for pub/sub - void *active_dns_requests; // DNS requests in progress - struct mg_timer *timers; // Active timers - int epoll_fd; // Used when MG_EPOLL_ENABLE=1 - struct mg_tcpip_if *ifp; // Builtin TCP/IP stack only. Interface pointer - size_t extraconnsize; // Builtin TCP/IP stack only. Extra space - MG_SOCKET_TYPE pipe; // Socketpair end for mg_wakeup() + struct mg_connection *conns; // List of active connections + struct mg_dns dns4; // DNS for IPv4 + struct mg_dns dns6; // DNS for IPv6 + int dnstimeout; // DNS resolve timeout in milliseconds + bool use_dns6; // Use DNS6 server by default, see #1532 + unsigned long nextid; // Next connection ID + void *userdata; // Arbitrary user data pointer + void *tls_ctx; // TLS context shared by all TLS sessions + uint16_t mqtt_id; // MQTT IDs for pub/sub + void *active_dns_requests; // DNS requests in progress + struct mg_timer *timers; // Active timers + int epoll_fd; // Used when MG_EPOLL_ENABLE=1 + struct mg_tcpip_if *ifp; // Builtin TCP/IP stack only. Interface pointer + size_t extraconnsize; // Builtin TCP/IP stack only. Extra space + MG_SOCKET_TYPE pipe; // Socketpair end for mg_wakeup() #if MG_ENABLE_FREERTOS_TCP - SocketSet_t ss; // NOTE(lsm): referenced from socket struct + SocketSet_t ss; // NOTE(lsm): referenced from socket struct #endif }; struct mg_connection { - struct mg_connection *next; // Linkage in struct mg_mgr :: connections - struct mg_mgr *mgr; // Our container - struct mg_addr loc; // Local address - struct mg_addr rem; // Remote address - void *fd; // Connected socket, or LWIP data - unsigned long id; // Auto-incrementing unique connection ID - struct mg_iobuf recv; // Incoming data - struct mg_iobuf send; // Outgoing data - struct mg_iobuf prof; // Profile data enabled by MG_ENABLE_PROFILE - struct mg_iobuf rtls; // TLS only. Incoming encrypted data - mg_event_handler_t fn; // User-specified event handler function - void *fn_data; // User-specified function parameter - mg_event_handler_t pfn; // Protocol-specific handler function - void *pfn_data; // Protocol-specific function parameter - char data[MG_DATA_SIZE]; // Arbitrary connection data - void *tls; // TLS specific data - unsigned is_listening : 1; // Listening connection - unsigned is_client : 1; // Outbound (client) connection - unsigned is_accepted : 1; // Accepted (server) connection - unsigned is_resolving : 1; // Non-blocking DNS resolution is in progress - unsigned is_arplooking : 1; // Non-blocking ARP resolution is in progress - unsigned is_connecting : 1; // Non-blocking connect is in progress - unsigned is_tls : 1; // TLS-enabled connection - unsigned is_tls_hs : 1; // TLS handshake is in progress - unsigned is_udp : 1; // UDP connection - unsigned is_websocket : 1; // WebSocket connection - unsigned is_mqtt5 : 1; // For MQTT connection, v5 indicator - unsigned is_hexdumping : 1; // Hexdump in/out traffic - unsigned is_draining : 1; // Send remaining data, then close and free - unsigned is_closing : 1; // Close and free the connection immediately - unsigned is_full : 1; // Stop reads, until cleared - unsigned is_tls_throttled : 1; // Last TLS write: MG_SOCK_PENDING() was true - unsigned is_resp : 1; // Response is still being generated - unsigned is_readable : 1; // Connection is ready to read - unsigned is_writable : 1; // Connection is ready to write + struct mg_connection *next; // Linkage in struct mg_mgr :: connections + struct mg_mgr *mgr; // Our container + struct mg_addr loc; // Local address + struct mg_addr rem; // Remote address + void *fd; // Connected socket, or LWIP data + unsigned long id; // Auto-incrementing unique connection ID + struct mg_iobuf recv; // Incoming data + struct mg_iobuf send; // Outgoing data + struct mg_iobuf prof; // Profile data enabled by MG_ENABLE_PROFILE + struct mg_iobuf rtls; // TLS only. Incoming encrypted data + mg_event_handler_t fn; // User-specified event handler function + void *fn_data; // User-specified function parameter + mg_event_handler_t pfn; // Protocol-specific handler function + void *pfn_data; // Protocol-specific function parameter + char data[MG_DATA_SIZE]; // Arbitrary connection data + void *tls; // TLS specific data + unsigned is_listening : 1; // Listening connection + unsigned is_client : 1; // Outbound (client) connection + unsigned is_accepted : 1; // Accepted (server) connection + unsigned is_resolving : 1; // Non-blocking DNS resolution is in progress + unsigned is_arplooking : 1; // Non-blocking ARP resolution is in progress + unsigned is_connecting : 1; // Non-blocking connect is in progress + unsigned is_tls : 1; // TLS-enabled connection + unsigned is_tls_hs : 1; // TLS handshake is in progress + unsigned is_udp : 1; // UDP connection + unsigned is_websocket : 1; // WebSocket connection + unsigned is_mqtt5 : 1; // For MQTT connection, v5 indicator + unsigned is_hexdumping : 1; // Hexdump in/out traffic + unsigned is_draining : 1; // Send remaining data, then close and free + unsigned is_closing : 1; // Close and free the connection immediately + unsigned is_full : 1; // Stop reads, until cleared + unsigned is_tls_throttled : 1; // Last TLS write: MG_SOCK_PENDING() was true + unsigned is_resp : 1; // Response is still being generated + unsigned is_readable : 1; // Connection is ready to read + unsigned is_writable : 1; // Connection is ready to write }; void mg_mgr_poll(struct mg_mgr *, int ms); @@ -1699,41 +1611,34 @@ struct mg_connection *mg_connect_svc(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data, mg_event_handler_t pfn, void *pfn_data); - - - - - - - struct mg_http_header { - struct mg_str name; // Header name - struct mg_str value; // Header value + struct mg_str name; // Header name + struct mg_str value; // Header value }; struct mg_http_message { - struct mg_str method, uri, query, proto; // Request/response line - struct mg_http_header headers[MG_MAX_HTTP_HEADERS]; // Headers - struct mg_str body; // Body - struct mg_str head; // Request + headers - struct mg_str message; // Request + headers + body + struct mg_str method, uri, query, proto; // Request/response line + struct mg_http_header headers[MG_MAX_HTTP_HEADERS]; // Headers + struct mg_str body; // Body + struct mg_str head; // Request + headers + struct mg_str message; // Request + headers + body }; // Parameter for mg_http_serve_dir() struct mg_http_serve_opts { - const char *root_dir; // Web root directory, must be non-NULL - const char *ssi_pattern; // SSI file name pattern, e.g. #.shtml - const char *extra_headers; // Extra HTTP headers to add in responses - const char *mime_types; // Extra mime types, ext1=type1,ext2=type2,.. - const char *page404; // Path to the 404 page, or NULL by default - struct mg_fs *fs; // Filesystem implementation. Use NULL for POSIX + const char *root_dir; // Web root directory, must be non-NULL + const char *ssi_pattern; // SSI file name pattern, e.g. #.shtml + const char *extra_headers; // Extra HTTP headers to add in responses + const char *mime_types; // Extra mime types, ext1=type1,ext2=type2,.. + const char *page404; // Path to the 404 page, or NULL by default + struct mg_fs *fs; // Filesystem implementation. Use NULL for POSIX }; // Parameter for mg_http_next_multipart struct mg_http_part { - struct mg_str name; // Form field name - struct mg_str filename; // Filename for file uploads - struct mg_str body; // Part contents + struct mg_str name; // Form field name + struct mg_str filename; // Filename for file uploads + struct mg_str body; // Part contents }; int mg_http_parse(const char *s, size_t len, struct mg_http_message *); @@ -1764,32 +1669,26 @@ struct mg_str mg_http_get_header_var(struct mg_str s, struct mg_str v); size_t mg_http_next_multipart(struct mg_str, size_t, struct mg_http_part *); int mg_http_status(const struct mg_http_message *hm); - void mg_http_serve_ssi(struct mg_connection *c, const char *root, const char *fullpath); - -#define MG_TLS_NONE 0 // No TLS support -#define MG_TLS_MBED 1 // mbedTLS -#define MG_TLS_OPENSSL 2 // OpenSSL -#define MG_TLS_WOLFSSL 5 // WolfSSL (based on OpenSSL) -#define MG_TLS_BUILTIN 3 // Built-in -#define MG_TLS_CUSTOM 4 // Custom implementation +#define MG_TLS_NONE 0 // No TLS support +#define MG_TLS_MBED 1 // mbedTLS +#define MG_TLS_OPENSSL 2 // OpenSSL +#define MG_TLS_WOLFSSL 5 // WolfSSL (based on OpenSSL) +#define MG_TLS_BUILTIN 3 // Built-in +#define MG_TLS_CUSTOM 4 // Custom implementation #ifndef MG_TLS #define MG_TLS MG_TLS_NONE #endif - - - - struct mg_tls_opts { - struct mg_str ca; // PEM or DER - struct mg_str cert; // PEM or DER - struct mg_str key; // PEM or DER - struct mg_str name; // If not empty, enable host name verification - int skip_verification; // Skip certificate and host name verification + struct mg_str ca; // PEM or DER + struct mg_str cert; // PEM or DER + struct mg_str key; // PEM or DER + struct mg_str name; // If not empty, enable host name verification + int skip_verification; // Skip certificate and host name verification }; void mg_tls_init(struct mg_connection *, const struct mg_tls_opts *opts); @@ -1811,15 +1710,12 @@ long mg_io_recv(struct mg_connection *c, void *buf, size_t len); #ifndef TLS_X15519_H #define TLS_X15519_H - - #define X25519_BYTES 32 extern const uint8_t X25519_BASE_POINT[X25519_BYTES]; int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES], const uint8_t x1[X25519_BYTES], int clamp); - #endif /* TLS_X15519_H */ /****************************************************************************** * @@ -1851,14 +1747,13 @@ int mg_tls_x25519(uint8_t out[X25519_BYTES], const uint8_t scalar[X25519_BYTES], * AES_CONTEXT : cipher context / holds inter-call data ******************************************************************************/ typedef struct { - int mode; // 1 for Encryption, 0 for Decryption - int rounds; // keysize-based rounds count - uint32_t *rk; // pointer to current round key - uint32_t buf[68]; // key expansion buffer + int mode; // 1 for Encryption, 0 for Decryption + int rounds; // keysize-based rounds count + uint32_t *rk; // pointer to current round key + uint32_t buf[68]; // key expansion buffer } aes_context; - -#define GCM_AUTH_FAILURE 0x55555555 // authentication failure +#define GCM_AUTH_FAILURE 0x55555555 // authentication failure /****************************************************************************** * GCM_CONTEXT : MUST be called once before ANY use of this library @@ -1888,8 +1783,6 @@ int mg_aes_gcm_decrypt(unsigned char *output, const unsigned char *input, // End of aes128 PD - - #define MG_UECC_SUPPORTS_secp256r1 1 /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */ @@ -2275,7 +2168,7 @@ int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash, #ifndef MG_UECC_PLATFORM #if defined(__AVR__) && __AVR__ #define MG_UECC_PLATFORM mg_uecc_avr -#elif defined(__thumb2__) || \ +#elif defined(__thumb2__) || \ defined(_M_ARMT) /* I think MSVC only supports Thumb-2 targets */ #define MG_UECC_PLATFORM mg_uecc_arm_thumb2 #elif defined(__thumb__) @@ -2284,7 +2177,7 @@ int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash, #define MG_UECC_PLATFORM mg_uecc_arm #elif defined(__aarch64__) #define MG_UECC_PLATFORM mg_uecc_arm64 -#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) || \ +#elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) || \ defined(__I86__) #define MG_UECC_PLATFORM mg_uecc_x86 #elif defined(__amd64__) || defined(_M_X64) @@ -2297,7 +2190,7 @@ int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash, #ifndef MG_UECC_ARM_USE_UMAAL #if (MG_UECC_PLATFORM == mg_uecc_arm) && (__ARM_ARCH >= 6) #define MG_UECC_ARM_USE_UMAAL 1 -#elif (MG_UECC_PLATFORM == mg_uecc_arm_thumb2) && (__ARM_ARCH >= 6) && \ +#elif (MG_UECC_PLATFORM == mg_uecc_arm_thumb2) && (__ARM_ARCH >= 6) && \ (!defined(__ARM_ARCH_7M__) || !__ARM_ARCH_7M__) #define MG_UECC_ARM_USE_UMAAL 1 #else @@ -2315,7 +2208,7 @@ int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash, #endif #endif -#if (MG_UECC_WORD_SIZE != 1) && (MG_UECC_WORD_SIZE != 4) && \ +#if (MG_UECC_WORD_SIZE != 1) && (MG_UECC_WORD_SIZE != 4) && \ (MG_UECC_WORD_SIZE != 8) #error "Unsupported value for MG_UECC_WORD_SIZE" #endif @@ -2326,9 +2219,9 @@ int mg_uecc_verify(const uint8_t *public_key, const uint8_t *message_hash, #define MG_UECC_WORD_SIZE 1 #endif -#if ((MG_UECC_PLATFORM == mg_uecc_arm || \ - MG_UECC_PLATFORM == mg_uecc_arm_thumb || \ - MG_UECC_PLATFORM == mg_uecc_arm_thumb2) && \ +#if ((MG_UECC_PLATFORM == mg_uecc_arm || \ + MG_UECC_PLATFORM == mg_uecc_arm_thumb || \ + MG_UECC_PLATFORM == mg_uecc_arm_thumb2) && \ (MG_UECC_WORD_SIZE != 4)) #pragma message("MG_UECC_WORD_SIZE must be 4 for ARM") #undef MG_UECC_WORD_SIZE @@ -2377,8 +2270,8 @@ typedef uint64_t mg_uecc_word_t; #ifndef _UECC_VLI_H_ #define _UECC_VLI_H_ -// -// +// +// /* Functions for raw large-integer manipulation. These are only available if uECC.c is compiled with MG_UECC_ENABLE_VLI_API defined to 1. */ @@ -2547,10 +2440,6 @@ int mg_uecc_generate_random_int(mg_uecc_word_t *random, // Contains poly1305-donna e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781 (Public // Domain) - - - - #if MG_TLS == MG_TLS_BUILTIN #ifndef __PORTABLE_8439_H #define __PORTABLE_8439_H @@ -2583,7 +2472,7 @@ extern "C" { #if defined(_MSC_VER) || defined(__cplusplus) // add restrict support is possible -#if (defined(_MSC_VER) && _MSC_VER >= 1900) || defined(__clang__) || \ +#if (defined(_MSC_VER) && _MSC_VER >= 1900) || defined(__clang__) || \ defined(__GNUC__) #define restrict __restrict #else @@ -2657,17 +2546,12 @@ PORTABLE_8439_DECL size_t mg_chacha20_poly1305_decrypt( #ifndef TLS_RSA_H #define TLS_RSA_H - -int mg_rsa_mod_pow(const uint8_t *mod, size_t modsz, const uint8_t *exp, size_t expsz, const uint8_t *msg, size_t msgsz, uint8_t *out, size_t outsz); +int mg_rsa_mod_pow(const uint8_t *mod, size_t modsz, const uint8_t *exp, + size_t expsz, const uint8_t *msg, size_t msgsz, uint8_t *out, + size_t outsz); #endif // TLS_RSA_H - - - - - - #if MG_TLS == MG_TLS_MBED #include #include @@ -2683,21 +2567,20 @@ struct mg_tls_ctx { }; struct mg_tls { - mbedtls_x509_crt ca; // Parsed CA certificate - mbedtls_x509_crt cert; // Parsed certificate - mbedtls_pk_context pk; // Private key context - mbedtls_ssl_context ssl; // SSL/TLS context - mbedtls_ssl_config conf; // SSL-TLS config + mbedtls_x509_crt ca; // Parsed CA certificate + mbedtls_x509_crt cert; // Parsed certificate + mbedtls_pk_context pk; // Private key context + mbedtls_ssl_context ssl; // SSL/TLS context + mbedtls_ssl_config conf; // SSL-TLS config #ifdef MBEDTLS_SSL_SESSION_TICKETS - mbedtls_ssl_ticket_context ticket; // Session tickets context + mbedtls_ssl_ticket_context ticket; // Session tickets context #endif // https://github.com/Mbed-TLS/mbedtls/blob/3b3c652d/include/mbedtls/ssl.h#L5071C18-L5076C29 - unsigned char *throttled_buf; // see #3074 + unsigned char *throttled_buf; // see #3074 size_t throttled_len; }; #endif - #if MG_TLS == MG_TLS_OPENSSL || MG_TLS == MG_TLS_WOLFSSL #include @@ -2710,7 +2593,6 @@ struct mg_tls { }; #endif - #define WEBSOCKET_OP_CONTINUE 0 #define WEBSOCKET_OP_TEXT 1 #define WEBSOCKET_OP_BINARY 2 @@ -2718,11 +2600,9 @@ struct mg_tls { #define WEBSOCKET_OP_PING 9 #define WEBSOCKET_OP_PONG 10 - - struct mg_ws_message { - struct mg_str data; // Websocket message data - uint8_t flags; // Websocket message flags + struct mg_str data; // Websocket message data + uint8_t flags; // Websocket message flags }; struct mg_connection *mg_ws_connect(struct mg_mgr *, const char *url, @@ -2736,19 +2616,12 @@ size_t mg_ws_printf(struct mg_connection *c, int op, const char *fmt, ...); size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt, va_list *); - - - struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr, const char *url, mg_event_handler_t fn, void *fn_data); void mg_sntp_request(struct mg_connection *c); int64_t mg_sntp_parse(const unsigned char *buf, size_t len); -uint64_t mg_now(void); // Return milliseconds since Epoch - - - - +uint64_t mg_now(void); // Return milliseconds since Epoch #define MQTT_CMD_CONNECT 1 #define MQTT_CMD_CONNACK 2 @@ -2807,40 +2680,40 @@ enum { enum { MQTT_OK, MQTT_INCOMPLETE, MQTT_MALFORMED }; struct mg_mqtt_prop { - uint8_t id; // Enumerated at MQTT5 Reference - uint32_t iv; // Integer value for 8-, 16-, 32-bit integers types - struct mg_str key; // Non-NULL only for user property type - struct mg_str val; // Non-NULL only for UTF-8 types and user properties + uint8_t id; // Enumerated at MQTT5 Reference + uint32_t iv; // Integer value for 8-, 16-, 32-bit integers types + struct mg_str key; // Non-NULL only for user property type + struct mg_str val; // Non-NULL only for UTF-8 types and user properties }; struct mg_mqtt_opts { - struct mg_str user; // Username, can be empty - struct mg_str pass; // Password, can be empty - struct mg_str client_id; // Client ID - struct mg_str topic; // message/subscription topic - struct mg_str message; // message content - uint8_t qos; // message quality of service - uint8_t version; // Can be 4 (3.1.1), or 5. If 0, assume 4 - uint16_t keepalive; // Keep-alive timer in seconds - uint16_t retransmit_id; // For PUBLISH, init to 0 - bool retain; // Retain flag - bool clean; // Clean session flag - struct mg_mqtt_prop *props; // MQTT5 props array - size_t num_props; // number of props - struct mg_mqtt_prop *will_props; // Valid only for CONNECT packet (MQTT5) - size_t num_will_props; // Number of will props + struct mg_str user; // Username, can be empty + struct mg_str pass; // Password, can be empty + struct mg_str client_id; // Client ID + struct mg_str topic; // message/subscription topic + struct mg_str message; // message content + uint8_t qos; // message quality of service + uint8_t version; // Can be 4 (3.1.1), or 5. If 0, assume 4 + uint16_t keepalive; // Keep-alive timer in seconds + uint16_t retransmit_id; // For PUBLISH, init to 0 + bool retain; // Retain flag + bool clean; // Clean session flag + struct mg_mqtt_prop *props; // MQTT5 props array + size_t num_props; // number of props + struct mg_mqtt_prop *will_props; // Valid only for CONNECT packet (MQTT5) + size_t num_will_props; // Number of will props }; struct mg_mqtt_message { - struct mg_str topic; // Parsed topic for PUBLISH - struct mg_str data; // Parsed message for PUBLISH - struct mg_str dgram; // Whole MQTT packet, including headers - uint16_t id; // For PUBACK, PUBREC, PUBREL, PUBCOMP, SUBACK, PUBLISH - uint8_t cmd; // MQTT command, one of MQTT_CMD_* - uint8_t qos; // Quality of service - uint8_t ack; // CONNACK return code, 0 = success - size_t props_start; // Offset to the start of the properties (MQTT5) - size_t props_size; // Length of the properties + struct mg_str topic; // Parsed topic for PUBLISH + struct mg_str data; // Parsed message for PUBLISH + struct mg_str dgram; // Whole MQTT packet, including headers + uint16_t id; // For PUBACK, PUBREC, PUBREL, PUBCOMP, SUBACK, PUBLISH + uint8_t cmd; // MQTT command, one of MQTT_CMD_* + uint8_t qos; // Quality of service + uint8_t ack; // CONNACK return code, 0 = success + size_t props_start; // Offset to the start of the properties (MQTT5) + size_t props_size; // Length of the properties }; struct mg_connection *mg_mqtt_connect(struct mg_mgr *, const char *url, @@ -2860,23 +2733,19 @@ void mg_mqtt_disconnect(struct mg_connection *, const struct mg_mqtt_opts *); size_t mg_mqtt_next_prop(struct mg_mqtt_message *, struct mg_mqtt_prop *, size_t ofs); - - - - // Mongoose sends DNS queries that contain only one question: // either A (IPv4) or AAAA (IPv6) address lookup. // Therefore, we expect zero or one answer. // If `resolved` is true, then `addr` contains resolved IPv4 or IPV6 address. struct mg_dns_message { - uint16_t txnid; // Transaction ID - bool resolved; // Resolve successful, addr is set - struct mg_addr addr; // Resolved address - char name[256]; // Host name + uint16_t txnid; // Transaction ID + bool resolved; // Resolve successful, addr is set + struct mg_addr addr; // Resolved address + char name[256]; // Host name }; struct mg_dns_header { - uint16_t txnid; // Transaction ID + uint16_t txnid; // Transaction ID uint16_t flags; uint16_t num_questions; uint16_t num_answers; @@ -2886,10 +2755,10 @@ struct mg_dns_header { // DNS resource record struct mg_dns_rr { - uint16_t nlen; // Name or pointer length - uint16_t atype; // Address type - uint16_t aclass; // Address class - uint16_t alen; // Address length + uint16_t nlen; // Name or pointer length + uint16_t atype; // Address type + uint16_t aclass; // Address class + uint16_t alen; // Address length }; void mg_resolve(struct mg_connection *, const char *url); @@ -2897,13 +2766,9 @@ void mg_resolve_cancel(struct mg_connection *); bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *); size_t mg_dns_parse_rr(const uint8_t *buf, size_t len, size_t ofs, bool is_question, struct mg_dns_rr *); - + struct mg_connection *mg_mdns_listen(struct mg_mgr *mgr, char *name); - - - - #ifndef MG_JSON_MAX_DEPTH #define MG_JSON_MAX_DEPTH 30 #endif @@ -2924,25 +2789,22 @@ bool mg_json_unescape(struct mg_str str, char *buf, size_t len); size_t mg_json_next(struct mg_str obj, size_t ofs, struct mg_str *key, struct mg_str *val); - - - // JSON-RPC request descriptor struct mg_rpc_req { - struct mg_rpc **head; // RPC handlers list head - struct mg_rpc *rpc; // RPC handler being called - mg_pfn_t pfn; // Response printing function - void *pfn_data; // Response printing function data - void *req_data; // Arbitrary request data - struct mg_str frame; // Request, e.g. {"id":1,"method":"add","params":[1,2]} + struct mg_rpc **head; // RPC handlers list head + struct mg_rpc *rpc; // RPC handler being called + mg_pfn_t pfn; // Response printing function + void *pfn_data; // Response printing function data + void *req_data; // Arbitrary request data + struct mg_str frame; // Request, e.g. {"id":1,"method":"add","params":[1,2]} }; // JSON-RPC method handler struct mg_rpc { - struct mg_rpc *next; // Next in list - struct mg_str method; // Method pattern - void (*fn)(struct mg_rpc_req *); // Handler function - void *fn_data; // Handler function argument + struct mg_rpc *next; // Next in list + struct mg_str method; // Method pattern + void (*fn)(struct mg_rpc_req *); // Handler function + void *fn_data; // Handler function argument }; void mg_rpc_add(struct mg_rpc **head, struct mg_str method_pattern, @@ -2959,28 +2821,24 @@ void mg_rpc_list(struct mg_rpc_req *r); // Copyright (c) 2023 Cesanta Software Limited // All rights reserved - - - - -#define MG_OTA_NONE 0 // No OTA support -#define MG_OTA_STM32H5 1 // STM32 H5 -#define MG_OTA_STM32H7 2 // STM32 H7 +#define MG_OTA_NONE 0 // No OTA support +#define MG_OTA_STM32H5 1 // STM32 H5 +#define MG_OTA_STM32H7 2 // STM32 H7 #define MG_OTA_STM32H7_DUAL_CORE 3 // STM32 H7 dual core -#define MG_OTA_STM32F 4 // STM32 F7/F4/F2 -#define MG_OTA_CH32V307 100 // WCH CH32V307 -#define MG_OTA_U2A 200 // Renesas U2A16, U2A8, U2A6 -#define MG_OTA_RT1020 300 // IMXRT1020 -#define MG_OTA_RT1050 301 // IMXRT1050 -#define MG_OTA_RT1060 302 // IMXRT1060 -#define MG_OTA_RT1064 303 // IMXRT1064 -#define MG_OTA_RT1170 304 // IMXRT1170 -#define MG_OTA_MCXN 310 // MCXN947 -#define MG_OTA_FRDM 320 // FRDM-RW612 -#define MG_OTA_FLASH 900 // OTA via an internal flash -#define MG_OTA_ESP32 910 // ESP32 OTA implementation -#define MG_OTA_PICOSDK 920 // RP2040/2350 using Pico-SDK hardware_flash -#define MG_OTA_CUSTOM 1000 // Custom implementation +#define MG_OTA_STM32F 4 // STM32 F7/F4/F2 +#define MG_OTA_CH32V307 100 // WCH CH32V307 +#define MG_OTA_U2A 200 // Renesas U2A16, U2A8, U2A6 +#define MG_OTA_RT1020 300 // IMXRT1020 +#define MG_OTA_RT1050 301 // IMXRT1050 +#define MG_OTA_RT1060 302 // IMXRT1060 +#define MG_OTA_RT1064 303 // IMXRT1064 +#define MG_OTA_RT1170 304 // IMXRT1170 +#define MG_OTA_MCXN 310 // MCXN947 +#define MG_OTA_FRDM 320 // FRDM-RW612 +#define MG_OTA_FLASH 900 // OTA via an internal flash +#define MG_OTA_ESP32 910 // ESP32 OTA implementation +#define MG_OTA_PICOSDK 920 // RP2040/2350 using Pico-SDK hardware_flash +#define MG_OTA_CUSTOM 1000 // Custom implementation #ifndef MG_OTA #define MG_OTA MG_OTA_NONE @@ -2995,21 +2853,19 @@ void mg_rpc_list(struct mg_rpc_req *r); #endif // OTA // Firmware update API -bool mg_ota_begin(size_t new_firmware_size); // Start writing -bool mg_ota_write(const void *buf, size_t len); // Write chunk, aligned to 1k -bool mg_ota_end(void); // Stop writing - - +bool mg_ota_begin(size_t new_firmware_size); // Start writing +bool mg_ota_write(const void *buf, size_t len); // Write chunk, aligned to 1k +bool mg_ota_end(void); // Stop writing #if MG_OTA != MG_OTA_NONE && MG_OTA != MG_OTA_CUSTOM struct mg_flash { - void *start; // Address at which flash starts - size_t size; // Flash size - size_t secsz; // Sector size - size_t align; // Write alignment - bool (*write_fn)(void *, const void *, size_t); // Write function - bool (*swap_fn)(void); // Swap partitions + void *start; // Address at which flash starts + size_t size; // Flash size + size_t secsz; // Sector size + size_t align; // Write alignment + bool (*write_fn)(void *, const void *, size_t); // Write function + bool (*swap_fn)(void); // Swap partitions }; bool mg_ota_flash_begin(size_t new_firmware_size, struct mg_flash *flash); @@ -3018,108 +2874,97 @@ bool mg_ota_flash_end(struct mg_flash *flash); #endif - - - - - struct mg_wifi_scan_bss_data { - struct mg_str SSID; - char *BSSID; - int16_t RSSI; - uint8_t security; + struct mg_str SSID; + char *BSSID; + int16_t RSSI; + uint8_t security; #define MG_WIFI_SECURITY_OPEN 0 -#define MG_WIFI_SECURITY_WEP MG_BIT(0) -#define MG_WIFI_SECURITY_WPA MG_BIT(1) +#define MG_WIFI_SECURITY_WEP MG_BIT(0) +#define MG_WIFI_SECURITY_WPA MG_BIT(1) #define MG_WIFI_SECURITY_WPA2 MG_BIT(2) #define MG_WIFI_SECURITY_WPA3 MG_BIT(3) - uint8_t channel; - unsigned band :2; + uint8_t channel; + unsigned band : 2; #define MG_WIFI_BAND_2G 0 #define MG_WIFI_BAND_5G 1 - unsigned has_n :1; + unsigned has_n : 1; }; - bool mg_wifi_scan(void); bool mg_wifi_connect(char *ssid, char *pass); bool mg_wifi_disconnect(void); bool mg_wifi_ap_start(char *ssid, char *pass, unsigned int channel); bool mg_wifi_ap_stop(void); - - - - - - #if MG_ENABLE_TCPIP -struct mg_tcpip_if; // Mongoose TCP/IP network interface +struct mg_tcpip_if; // Mongoose TCP/IP network interface struct mg_tcpip_driver { - bool (*init)(struct mg_tcpip_if *); // Init driver - size_t (*tx)(const void *, size_t, struct mg_tcpip_if *); // Transmit frame - size_t (*rx)(void *buf, size_t len, struct mg_tcpip_if *); // Receive frame - bool (*poll)(struct mg_tcpip_if *, bool); // Poll, return Up/down status + bool (*init)(struct mg_tcpip_if *); // Init driver + size_t (*tx)(const void *, size_t, struct mg_tcpip_if *); // Transmit frame + size_t (*rx)(void *buf, size_t len, struct mg_tcpip_if *); // Receive frame + bool (*poll)(struct mg_tcpip_if *, bool); // Poll, return Up/down status }; typedef void (*mg_tcpip_event_handler_t)(struct mg_tcpip_if *ifp, int ev, void *ev_data); enum { - MG_TCPIP_EV_ST_CHG, // state change uint8_t * (&ifp->state) - MG_TCPIP_EV_DHCP_DNS, // DHCP DNS assignment uint32_t *ipaddr - MG_TCPIP_EV_DHCP_SNTP, // DHCP SNTP assignment uint32_t *ipaddr - MG_TCPIP_EV_ARP, // Got ARP packet struct mg_str * - MG_TCPIP_EV_TIMER_1S, // 1 second timer NULL - MG_TCPIP_EV_WIFI_SCAN_RESULT, // Wi-Fi scan results struct mg_wifi_scan_bss_data * + MG_TCPIP_EV_ST_CHG, // state change uint8_t * (&ifp->state) + MG_TCPIP_EV_DHCP_DNS, // DHCP DNS assignment uint32_t *ipaddr + MG_TCPIP_EV_DHCP_SNTP, // DHCP SNTP assignment uint32_t *ipaddr + MG_TCPIP_EV_ARP, // Got ARP packet struct mg_str * + MG_TCPIP_EV_TIMER_1S, // 1 second timer NULL + MG_TCPIP_EV_WIFI_SCAN_RESULT, // Wi-Fi scan results struct + // mg_wifi_scan_bss_data * MG_TCPIP_EV_WIFI_SCAN_END, // Wi-Fi scan has finished NULL - MG_TCPIP_EV_WIFI_CONNECT_ERR, // Wi-Fi connect has failed driver and chip specific - MG_TCPIP_EV_DRIVER, // Driver event driver specific - MG_TCPIP_EV_USER // Starting ID for user events + MG_TCPIP_EV_WIFI_CONNECT_ERR, // Wi-Fi connect has failed driver and + // chip specific + MG_TCPIP_EV_DRIVER, // Driver event driver specific + MG_TCPIP_EV_USER // Starting ID for user events }; - // Network interface struct mg_tcpip_if { - uint8_t mac[6]; // MAC address. Must be set to a valid MAC - uint32_t ip, mask, gw; // IP address, mask, default gateway - struct mg_str tx; // Output (TX) buffer - bool enable_dhcp_client; // Enable DCHP client - bool enable_dhcp_server; // Enable DCHP server - bool enable_get_gateway; // DCHP server sets client as gateway - bool enable_req_dns; // DCHP client requests DNS server - bool enable_req_sntp; // DCHP client requests SNTP server - bool enable_crc32_check; // Do a CRC check on RX frames and strip it - bool enable_mac_check; // Do a MAC check on RX frames - bool update_mac_hash_table; // Signal drivers to update MAC controller - struct mg_tcpip_driver *driver; // Low level driver - void *driver_data; // Driver-specific data - mg_tcpip_event_handler_t fn; // User-specified event handler function - struct mg_mgr *mgr; // Mongoose event manager - struct mg_queue recv_queue; // Receive queue - char dhcp_name[12]; // Name reported to DHCP, "mip" if unset - uint16_t mtu; // Interface MTU + uint8_t mac[6]; // MAC address. Must be set to a valid MAC + uint32_t ip, mask, gw; // IP address, mask, default gateway + struct mg_str tx; // Output (TX) buffer + bool enable_dhcp_client; // Enable DCHP client + bool enable_dhcp_server; // Enable DCHP server + bool enable_get_gateway; // DCHP server sets client as gateway + bool enable_req_dns; // DCHP client requests DNS server + bool enable_req_sntp; // DCHP client requests SNTP server + bool enable_crc32_check; // Do a CRC check on RX frames and strip it + bool enable_mac_check; // Do a MAC check on RX frames + bool update_mac_hash_table; // Signal drivers to update MAC controller + struct mg_tcpip_driver *driver; // Low level driver + void *driver_data; // Driver-specific data + mg_tcpip_event_handler_t fn; // User-specified event handler function + struct mg_mgr *mgr; // Mongoose event manager + struct mg_queue recv_queue; // Receive queue + char dhcp_name[12]; // Name reported to DHCP, "mip" if unset + uint16_t mtu; // Interface MTU #define MG_TCPIP_MTU_DEFAULT 1500 // Internal state, user can use it but should not change it - uint8_t gwmac[6]; // Router's MAC - char *dns4_url; // DNS server URL - uint64_t now; // Current time - uint64_t timer_1000ms; // 1000 ms timer: for DHCP and link state - uint64_t lease_expire; // Lease expiration time, in ms - uint16_t eport; // Next ephemeral port - volatile uint32_t ndrop; // Number of received, but dropped frames - volatile uint32_t nrecv; // Number of received frames - volatile uint32_t nsent; // Number of transmitted frames - volatile uint32_t nerr; // Number of driver errors - uint8_t state; // Current state -#define MG_TCPIP_STATE_DOWN 0 // Interface is down -#define MG_TCPIP_STATE_UP 1 // Interface is up -#define MG_TCPIP_STATE_REQ 2 // Interface is up, DHCP REQUESTING state -#define MG_TCPIP_STATE_IP 3 // Interface is up and has an IP assigned -#define MG_TCPIP_STATE_READY 4 // Interface has fully come up, ready to work + uint8_t gwmac[6]; // Router's MAC + char *dns4_url; // DNS server URL + uint64_t now; // Current time + uint64_t timer_1000ms; // 1000 ms timer: for DHCP and link state + uint64_t lease_expire; // Lease expiration time, in ms + uint16_t eport; // Next ephemeral port + volatile uint32_t ndrop; // Number of received, but dropped frames + volatile uint32_t nrecv; // Number of received frames + volatile uint32_t nsent; // Number of transmitted frames + volatile uint32_t nerr; // Number of driver errors + uint8_t state; // Current state +#define MG_TCPIP_STATE_DOWN 0 // Interface is down +#define MG_TCPIP_STATE_UP 1 // Interface is up +#define MG_TCPIP_STATE_REQ 2 // Interface is up, DHCP REQUESTING state +#define MG_TCPIP_STATE_IP 3 // Interface is up and has an IP assigned +#define MG_TCPIP_STATE_READY 4 // Interface has fully come up, ready to work }; void mg_tcpip_init(struct mg_mgr *, struct mg_tcpip_if *); @@ -3146,34 +2991,31 @@ extern struct mg_tcpip_driver mg_tcpip_driver_cyw; // Drivers that require SPI, can use this SPI abstraction struct mg_tcpip_spi { - void *spi; // Opaque SPI bus descriptor - void (*begin)(void *); // SPI begin: slave select low - void (*end)(void *); // SPI end: slave select high - uint8_t (*txn)(void *, uint8_t); // SPI transaction: write 1 byte, read reply + void *spi; // Opaque SPI bus descriptor + void (*begin)(void *); // SPI begin: slave select low + void (*end)(void *); // SPI end: slave select high + uint8_t (*txn)(void *, uint8_t); // SPI transaction: write 1 byte, read reply }; - #endif - #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS -#include "Driver_ETH_MAC.h" // keep this include -#include "Driver_ETH_PHY.h" // keep this include +#include "Driver_ETH_MAC.h" // keep this include +#include "Driver_ETH_PHY.h" // keep this include #endif - -#if MG_ENABLE_TCPIP && \ - ((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \ +#if MG_ENABLE_TCPIP && \ + ((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \ (defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO)) struct mg_tcpip_spi_ { - void *spi; // Opaque SPI bus descriptor - void (*begin)(void *); // SPI begin: slave select low - void (*end)(void *); // SPI end: slave select high + void *spi; // Opaque SPI bus descriptor + void (*begin)(void *); // SPI begin: slave select low + void (*end)(void *); // SPI end: slave select high void (*txn)(void *, uint8_t *, uint8_t *, - size_t len); // SPI transaction: write-read len bytes + size_t len); // SPI transaction: write-read len bytes }; struct mg_tcpip_driver_cyw_firmware { @@ -3192,37 +3034,38 @@ struct mg_tcpip_driver_cyw_data { char *pass; char *apssid; char *appass; - uint8_t security; // TBD + uint8_t security; // TBD uint8_t apsecurity; // TBD uint8_t apchannel; - bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not NULL - bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3 Table 6) + bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not + // NULL + bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3 + // Table 6) }; #if 0 -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_cyw_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - MG_SET_WIFI_CONFIG(&driver_data_); \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_pico_w; \ - mif_.driver_data = &driver_data_; \ - mif_.recv_queue.size = 8192; \ - mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: cyw, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_cyw_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + MG_SET_WIFI_CONFIG(&driver_data_); \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_pico_w; \ + mif_.driver_data = &driver_data_; \ + mif_.recv_queue.size = 8192; \ + mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: cyw, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif #endif - -#if MG_ENABLE_TCPIP && \ - (defined(MG_ENABLE_DRIVER_IMXRT10) && MG_ENABLE_DRIVER_IMXRT10) || \ - (defined(MG_ENABLE_DRIVER_IMXRT11) && MG_ENABLE_DRIVER_IMXRT11) +#if MG_ENABLE_TCPIP && \ + (defined(MG_ENABLE_DRIVER_IMXRT10) && MG_ENABLE_DRIVER_IMXRT10) || \ + (defined(MG_ENABLE_DRIVER_IMXRT11) && MG_ENABLE_DRIVER_IMXRT11) struct mg_tcpip_driver_imxrt_data { // MDC clock divider. MDC clock is derived from IPS Bus clock (ipg_clk), @@ -3236,9 +3079,9 @@ struct mg_tcpip_driver_imxrt_data { // 40 MHz 7 // 50 MHz 9 // 66 MHz 13 - int mdc_cr; // Valid values: -1 to 63 + int mdc_cr; // Valid values: -1 to 63 - uint8_t phy_addr; // PHY address + uint8_t phy_addr; // PHY address }; #ifndef MG_TCPIP_PHY_ADDR @@ -3249,27 +3092,24 @@ struct mg_tcpip_driver_imxrt_data { #define MG_DRIVER_MDC_CR 24 #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_imxrt_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_imxrt; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: imxrt, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_imxrt_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_imxrt; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: imxrt, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - - - struct mg_phy { uint16_t (*read_reg)(uint8_t addr, uint8_t reg); void (*write_reg)(uint8_t addr, uint8_t reg, uint16_t value); @@ -3289,64 +3129,62 @@ void mg_phy_init(struct mg_phy *, uint8_t addr, uint8_t config); bool mg_phy_up(struct mg_phy *, uint8_t addr, bool *full_duplex, uint8_t *speed); - -#if MG_ENABLE_TCPIP && MG_ARCH == MG_ARCH_PICOSDK && \ +#if MG_ENABLE_TCPIP && MG_ARCH == MG_ARCH_PICOSDK && \ defined(MG_ENABLE_DRIVER_PICO_W) && MG_ENABLE_DRIVER_PICO_W -#include "cyw43.h" // keep this include -#include "pico/cyw43_arch.h" // keep this include -#include "pico/unique_id.h" // keep this include +#include "cyw43.h" // keep this include +#include "pico/cyw43_arch.h" // keep this include +#include "pico/unique_id.h" // keep this include struct mg_tcpip_driver_pico_w_data { char *ssid; char *pass; char *apssid; char *appass; - uint8_t security; // TBD + uint8_t security; // TBD uint8_t apsecurity; // TBD uint8_t apchannel; - bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not NULL + bool apmode; // start in AP mode; 'false' starts connection to 'ssid' if not + // NULL }; -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_pico_w_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - MG_SET_WIFI_CONFIG(&driver_data_); \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_pico_w; \ - mif_.driver_data = &driver_data_; \ - mif_.recv_queue.size = 8192; \ - mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: pico-w, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_pico_w_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + MG_SET_WIFI_CONFIG(&driver_data_); \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_pico_w; \ + mif_.driver_data = &driver_data_; \ + mif_.recv_queue.size = 8192; \ + mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: pico-w, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - struct mg_tcpip_driver_ppp_data { - void *uart; // Opaque UART bus descriptor - void (*reset)(void *); // Modem hardware reset - void (*tx)(void *, uint8_t); // UART transmit single byte - int (*rx)(void *); // UART receive single byte - const char **script; // List of AT commands and expected replies - int script_index; // Index of the current AT command in the list - uint64_t deadline; // AT command deadline in ms + void *uart; // Opaque UART bus descriptor + void (*reset)(void *); // Modem hardware reset + void (*tx)(void *, uint8_t); // UART transmit single byte + int (*rx)(void *); // UART receive single byte + const char **script; // List of AT commands and expected replies + int script_index; // Index of the current AT command in the list + uint64_t deadline; // AT command deadline in ms }; - -#if MG_ENABLE_TCPIP && \ - (defined(MG_ENABLE_DRIVER_RA6) && MG_ENABLE_DRIVER_RA6) || \ - (defined(MG_ENABLE_DRIVER_RA8) && MG_ENABLE_DRIVER_RA8) +#if MG_ENABLE_TCPIP && \ + (defined(MG_ENABLE_DRIVER_RA6) && MG_ENABLE_DRIVER_RA6) || \ + (defined(MG_ENABLE_DRIVER_RA8) && MG_ENABLE_DRIVER_RA8) struct mg_tcpip_driver_ra_data { // MDC clock "divider". MDC clock is software generated, - uint32_t clock; // core clock frequency in Hz - uint16_t irqno; // IRQn, R_ICU->IELSR[irqno] - uint8_t phy_addr; // PHY address + uint32_t clock; // core clock frequency in Hz + uint16_t irqno; // IRQn, R_ICU->IELSR[irqno] + uint8_t phy_addr; // PHY address }; #ifndef MG_DRIVER_CLK_FREQ @@ -3361,26 +3199,25 @@ struct mg_tcpip_driver_ra_data { #define MG_TCPIP_PHY_ADDR 0 #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_ra_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.clock = MG_DRIVER_CLK_FREQ; \ - driver_data_.irqno = MG_DRIVER_IRQ_NO; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_ra; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: ra, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_ra_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.clock = MG_DRIVER_CLK_FREQ; \ + driver_data_.irqno = MG_DRIVER_IRQ_NO; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_ra; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: ra, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612) && MG_ENABLE_DRIVER_RW612 struct mg_tcpip_driver_rw612_data { @@ -3408,26 +3245,25 @@ struct mg_tcpip_driver_rw612_data { #define MG_DRIVER_MDC_HOLDTIME 3 #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_rw612_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_rw612; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: rw612, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_rw612_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_rw612; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: rw612, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - -#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && \ +#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && \ MG_ENABLE_DRIVER_SAME54 #ifndef MG_DRIVER_MDC_CR @@ -3443,26 +3279,25 @@ struct mg_tcpip_driver_same54_data { uint8_t phy_addr; }; -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_same54_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_DRIVER_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_same54; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: same54, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_same54_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_DRIVER_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_same54; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: same54, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - -#if MG_ENABLE_TCPIP && \ +#if MG_ENABLE_TCPIP && \ (defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO) // Specific chip/card driver --> SDIO driver --> HAL --> SDIO hw controller @@ -3471,8 +3306,8 @@ struct mg_tcpip_driver_same54_data { // - Provide a function to init the controller (external) // - Provide these functions: struct mg_tcpip_sdio { - void *sdio; // Opaque SDIO bus descriptor - void (*cfg)(void *, uint8_t); // select operating parameters + void *sdio; // Opaque SDIO bus descriptor + void (*cfg)(void *, uint8_t); // select operating parameters // SDIO transaction: send cmd with a possible 1-byte read or write bool (*txn)(void *, uint8_t cmd, uint32_t arg, uint32_t *r); // SDIO extended transaction: write or read len bytes, using blksz blocks @@ -3500,8 +3335,7 @@ bool mg_sdio_transfer(struct mg_tcpip_sdio *sdio, bool write, unsigned int f, #endif - -#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \ +#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \ MG_ENABLE_DRIVER_STM32F struct mg_tcpip_driver_stm32f_data { @@ -3516,9 +3350,9 @@ struct mg_tcpip_driver_stm32f_data { // 150-216 MHz HCLK/102 4 <-- value for Nucleo-F* on max speed // 216-310 MHz HCLK/124 5 // 110, 111 Reserved - int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 + int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 - uint8_t phy_addr; // PHY address + uint8_t phy_addr; // PHY address }; #ifndef MG_TCPIP_PHY_ADDR @@ -3535,26 +3369,25 @@ struct mg_tcpip_driver_stm32f_data { #define MG_ENABLE_ETH_IRQ() #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_stm32f_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_stm32f; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - MG_ENABLE_ETH_IRQ(); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_stm32f_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_stm32f; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + MG_ENABLE_ETH_IRQ(); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - #if MG_ENABLE_TCPIP #if !defined(MG_ENABLE_DRIVER_STM32H) #define MG_ENABLE_DRIVER_STM32H 0 @@ -3577,10 +3410,10 @@ struct mg_tcpip_driver_stm32h_data { // 250-300 MHz HCLK/124 5 <-- value for Nucleo-H* on CSI // 300-500 MHz HCLK/204 6 // 500-800 MHz HCLK/324 7 - int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 + int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 - uint8_t phy_addr; // PHY address - uint8_t phy_conf; // PHY config + uint8_t phy_addr; // PHY address + uint8_t phy_conf; // PHY config }; #ifndef MG_TCPIP_PHY_CONF @@ -3601,28 +3434,27 @@ struct mg_tcpip_driver_stm32h_data { #define MG_ENABLE_ETH_IRQ() #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_stm32h_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - driver_data_.phy_conf = MG_TCPIP_PHY_CONF; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_stm32h; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_ENABLE_ETH_IRQ(); \ - MG_INFO(("Driver: stm32h, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_stm32h_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + driver_data_.phy_conf = MG_TCPIP_PHY_CONF; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_stm32h; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_ENABLE_ETH_IRQ(); \ + MG_INFO(("Driver: stm32h, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif #endif - #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C struct mg_tcpip_driver_tm4c_data { @@ -3635,32 +3467,32 @@ struct mg_tcpip_driver_tm4c_data { // 20-35 MHz SYSCLK/16 2 // 35-60 MHz SYSCLK/26 3 // 0x4-0xF Reserved - int mdc_cr; // Valid values: -1, 0, 1, 2, 3 + int mdc_cr; // Valid values: -1, 0, 1, 2, 3 }; #ifndef MG_DRIVER_MDC_CR #define MG_DRIVER_MDC_CR 1 #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_tm4c_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_tm4c; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: tm4c, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_tm4c_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_tm4c; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: tm4c, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - -#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TMS570) && MG_ENABLE_DRIVER_TMS570 +#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TMS570) && \ + MG_ENABLE_DRIVER_TMS570 struct mg_tcpip_driver_tms570_data { int mdc_cr; int phy_addr; @@ -3674,29 +3506,27 @@ struct mg_tcpip_driver_tms570_data { #define MG_DRIVER_MDC_CR 1 #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_tms570_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_tms570; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: tms570, MAC: %M", mg_print_mac, mif_.mac));\ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_tms570_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_tms570; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: tms570, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - - #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7 struct mg_tcpip_driver_xmc7_data { - int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 + int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 uint8_t phy_addr; }; @@ -3708,26 +3538,24 @@ struct mg_tcpip_driver_xmc7_data { #define MG_DRIVER_MDC_CR 3 #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_xmc7_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_xmc7; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: xmc7, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_xmc7_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_xmc7; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: xmc7, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif - - #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC struct mg_tcpip_driver_xmc_data { @@ -3744,7 +3572,7 @@ struct mg_tcpip_driver_xmc_data { // 150-250 MHz ETH Clock/102 4 // 250-300 MHz ETH Clock/124 5 // 110, 111 Reserved - int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 + int mdc_cr; // Valid values: -1, 0, 1, 2, 3, 4, 5 uint8_t phy_addr; }; @@ -3756,20 +3584,20 @@ struct mg_tcpip_driver_xmc_data { #define MG_DRIVER_MDC_CR 4 #endif -#define MG_TCPIP_DRIVER_INIT(mgr) \ - do { \ - static struct mg_tcpip_driver_xmc_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ - driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.driver = &mg_tcpip_driver_xmc; \ - mif_.driver_data = &driver_data_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mg_tcpip_init(mgr, &mif_); \ - MG_INFO(("Driver: xmc, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_INIT(mgr) \ + do { \ + static struct mg_tcpip_driver_xmc_data driver_data_; \ + static struct mg_tcpip_if mif_; \ + driver_data_.mdc_cr = MG_DRIVER_MDC_CR; \ + driver_data_.phy_addr = MG_TCPIP_PHY_ADDR; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.driver = &mg_tcpip_driver_xmc; \ + mif_.driver_data = &driver_data_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: xmc, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #endif @@ -3777,4 +3605,4 @@ struct mg_tcpip_driver_xmc_data { #ifdef __cplusplus } #endif -#endif // MONGOOSE_H +#endif // MONGOOSE_H diff --git a/src/terminal.c b/src/terminal.c index c5f0b66..63486cc 100644 --- a/src/terminal.c +++ b/src/terminal.c @@ -1,158 +1,158 @@ #include "terminal.h" +#include +#include +#include +#include #include #include #include -#include -#include #include #include -#include +#include #include -#include -#include -int create_terminal_session(struct terminal_session *session, const char *shell) { - // Создаем pty - int master, slave; - char slave_name[64]; - - if (openpty(&master, &slave, slave_name, NULL, NULL) == -1) { - perror("openpty failed"); - return -1; - } - - pid_t pid = fork(); - if (pid == -1) { - perror("fork failed"); - close(master); - close(slave); - return -1; - } - - if (pid == 0) { - // Дочерний процесс - close(master); - - // Устанавливаем pty как контролирующий терминал - setsid(); - ioctl(slave, TIOCSCTTY, 1); - - // Перенаправляем стандартные потоки - dup2(slave, STDIN_FILENO); - dup2(slave, STDOUT_FILENO); - dup2(slave, STDERR_FILENO); - - if (slave > STDERR_FILENO) { - close(slave); - } - - // Устанавливаем переменные окружения - setenv("TERM", "xterm-256color", 1); - setenv("COLORTERM", "truecolor", 1); - - // Запускаем shell - execlp(shell, shell, NULL); - - // Если execlp вернулся, значит произошла ошибка - perror("execlp failed"); - exit(EXIT_FAILURE); - } - - // Родительский процесс +int create_terminal_session(struct terminal_session *session, + const char *shell) { + // Создаем pty + int master, slave; + char slave_name[64]; + + if (openpty(&master, &slave, slave_name, NULL, NULL) == -1) { + perror("openpty failed"); + return -1; + } + + pid_t pid = fork(); + if (pid == -1) { + perror("fork failed"); + close(master); close(slave); - - session->master_pty = master; - session->slave_pty = slave; - session->child_pid = pid; - session->active = true; - - // Устанавливаем неблокирующий режим - int flags = fcntl(master, F_GETFL, 0); - fcntl(master, F_SETFL, flags | O_NONBLOCK); - - printf("Created terminal session with PID %d\n", pid); - return 0; + return -1; + } + + if (pid == 0) { + // Дочерний процесс + close(master); + + // Устанавливаем pty как контролирующий терминал + setsid(); + ioctl(slave, TIOCSCTTY, 1); + + // Перенаправляем стандартные потоки + dup2(slave, STDIN_FILENO); + dup2(slave, STDOUT_FILENO); + dup2(slave, STDERR_FILENO); + + if (slave > STDERR_FILENO) { + close(slave); + } + + // Устанавливаем переменные окружения + setenv("TERM", "xterm-256color", 1); + setenv("COLORTERM", "truecolor", 1); + + // Запускаем shell + execlp(shell, shell, NULL); + + // Если execlp вернулся, значит произошла ошибка + perror("execlp failed"); + exit(EXIT_FAILURE); + } + + // Родительский процесс + close(slave); + + session->master_pty = master; + session->slave_pty = slave; + session->child_pid = pid; + session->active = true; + + // Устанавливаем неблокирующий режим + int flags = fcntl(master, F_GETFL, 0); + fcntl(master, F_SETFL, flags | O_NONBLOCK); + + printf("Created terminal session with PID %d\n", pid); + return 0; } void destroy_terminal_session(struct terminal_session *session) { - if (!session || !session->active) { - return; - } - - printf("Destroying terminal session with PID %d\n", session->child_pid); - - // Завершаем дочерний процесс - if (session->child_pid > 0) { - // Отправляем SIGKILL - int status; - kill(session->child_pid, SIGKILL); - waitpid(session->child_pid, &status, 0); - } - - // Закрываем pty - if (session->master_pty != -1) { - close(session->master_pty); - session->master_pty = -1; - } - - session->active = false; - session->child_pid = 0; - printf("Terminal session destroyed\n"); + if (!session || !session->active) { + return; + } + + printf("Destroying terminal session with PID %d\n", session->child_pid); + + // Завершаем дочерний процесс + if (session->child_pid > 0) { + // Отправляем SIGKILL + int status; + kill(session->child_pid, SIGKILL); + waitpid(session->child_pid, &status, 0); + } + + // Закрываем pty + if (session->master_pty != -1) { + close(session->master_pty); + session->master_pty = -1; + } + + session->active = false; + session->child_pid = 0; + printf("Terminal session destroyed\n"); } -ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_t size) { - if (!session || !session->active) { - return -1; - } - - ssize_t bytes_read = read(session->master_pty, buffer, size - 1); - if (bytes_read > 0) { - buffer[bytes_read] = '\0'; - } else if (bytes_read == 0) { - // EOF - соединение закрыто - return 0; - } else if (bytes_read < 0) { - if (errno != EAGAIN && errno != EWOULDBLOCK) { - perror("read from terminal failed"); - return -1; - } - // Нет данных для чтения - это нормально в неблокирующем режиме - return -2; - } - - return bytes_read; -} +ssize_t read_from_terminal(struct terminal_session *session, char *buffer, + size_t size) { + if (!session || !session->active) { + return -1; + } -ssize_t write_to_terminal(struct terminal_session *session, const char *data, size_t size) { - if (!session || !session->active) { - return -1; - } - - ssize_t bytes_written = write(session->master_pty, data, size); - if (bytes_written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { - perror("write to terminal failed"); - return -1; - } - - return bytes_written; -} - -int resize_terminal(struct terminal_session *session, uint16_t rows, uint16_t cols) { - if (!session || !session->active) { - return -1; - } - - struct winsize ws = { - .ws_row = rows, - .ws_col = cols, - .ws_xpixel = 0, - .ws_ypixel = 0 - }; - - if (ioctl(session->master_pty, TIOCSWINSZ, &ws) == -1) { - perror("ioctl TIOCSWINSZ failed"); - return -1; - } - + ssize_t bytes_read = read(session->master_pty, buffer, size - 1); + if (bytes_read > 0) { + buffer[bytes_read] = '\0'; + } else if (bytes_read == 0) { + // EOF - соединение закрыто return 0; -} \ No newline at end of file + } else if (bytes_read < 0) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { + perror("read from terminal failed"); + return -1; + } + // Нет данных для чтения - это нормально в неблокирующем режиме + return -2; + } + + return bytes_read; +} + +ssize_t write_to_terminal(struct terminal_session *session, const char *data, + size_t size) { + if (!session || !session->active) { + return -1; + } + + ssize_t bytes_written = write(session->master_pty, data, size); + if (bytes_written < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { + perror("write to terminal failed"); + return -1; + } + + return bytes_written; +} + +int resize_terminal(struct terminal_session *session, uint16_t rows, + uint16_t cols) { + if (!session || !session->active) { + return -1; + } + + struct winsize ws = { + .ws_row = rows, .ws_col = cols, .ws_xpixel = 0, .ws_ypixel = 0}; + + if (ioctl(session->master_pty, TIOCSWINSZ, &ws) == -1) { + perror("ioctl TIOCSWINSZ failed"); + return -1; + } + + return 0; +} diff --git a/src/terminal.h b/src/terminal.h index 1ac9285..752316a 100644 --- a/src/terminal.h +++ b/src/terminal.h @@ -1,25 +1,29 @@ #ifndef TERMINAL_H #define TERMINAL_H +#include +#include #include #include -#include -#include #include #include struct terminal_session { - int master_pty; - int slave_pty; - pid_t child_pid; - bool active; + int master_pty; + int slave_pty; + pid_t child_pid; + bool active; }; // Функции для работы с терминалом -int create_terminal_session(struct terminal_session *session, const char *shell); +int create_terminal_session(struct terminal_session *session, + const char *shell); void destroy_terminal_session(struct terminal_session *session); -ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_t size); -ssize_t write_to_terminal(struct terminal_session *session, const char *data, size_t size); -int resize_terminal(struct terminal_session *session, uint16_t rows, uint16_t cols); +ssize_t read_from_terminal(struct terminal_session *session, char *buffer, + size_t size); +ssize_t write_to_terminal(struct terminal_session *session, const char *data, + size_t size); +int resize_terminal(struct terminal_session *session, uint16_t rows, + uint16_t cols); #endif diff --git a/static/index.html b/static/index.html index de3bf29..39585e1 100644 --- a/static/index.html +++ b/static/index.html @@ -1,176 +1,195 @@ - + - - Web Terminal - - - - -

Web Terminal

-
Connecting...
-
+ + Web Terminal + + + + +

Web Terminal

+
Connecting...
+
+ + + + - - \ No newline at end of file + + // Initialize terminal when page loads + document.addEventListener("DOMContentLoaded", () => { + new WebTerminal(); + }); + + + diff --git a/static/xterm-addon-fit.js b/static/xterm-addon-fit.js index 7cfd9de..9dbb5c0 100644 --- a/static/xterm-addon-fit.js +++ b/static/xterm-addon-fit.js @@ -1,2 +1,73 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.FitAddon=t():e.FitAddon=t()}(self,(()=>(()=>{"use strict";var e={};return(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){const e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;const t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal)return;if(!this._terminal.element||!this._terminal.element.parentElement)return;const e=this._terminal._core,t=e._renderService.dimensions;if(0===t.css.cell.width||0===t.css.cell.height)return;const r=0===this._terminal.options.scrollback?0:e.viewport.scrollBarWidth,i=window.getComputedStyle(this._terminal.element.parentElement),o=parseInt(i.getPropertyValue("height")),s=Math.max(0,parseInt(i.getPropertyValue("width"))),n=window.getComputedStyle(this._terminal.element),l=o-(parseInt(n.getPropertyValue("padding-top"))+parseInt(n.getPropertyValue("padding-bottom"))),a=s-(parseInt(n.getPropertyValue("padding-right"))+parseInt(n.getPropertyValue("padding-left")))-r;return{cols:Math.max(2,Math.floor(a/t.css.cell.width)),rows:Math.max(1,Math.floor(l/t.css.cell.height))}}}})(),e})())); -//# sourceMappingURL=xterm-addon-fit.js.map \ No newline at end of file +!(function (e, t) { + "object" == typeof exports && "object" == typeof module + ? (module.exports = t()) + : "function" == typeof define && define.amd + ? define([], t) + : "object" == typeof exports + ? (exports.FitAddon = t()) + : (e.FitAddon = t()); +})(self, () => + (() => { + "use strict"; + var e = {}; + return ( + (() => { + var t = e; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.FitAddon = void 0), + (t.FitAddon = class { + activate(e) { + this._terminal = e; + } + dispose() {} + fit() { + const e = this.proposeDimensions(); + if (!e || !this._terminal || isNaN(e.cols) || isNaN(e.rows)) + return; + const t = this._terminal._core; + (this._terminal.rows === e.rows && + this._terminal.cols === e.cols) || + (t._renderService.clear(), + this._terminal.resize(e.cols, e.rows)); + } + proposeDimensions() { + if (!this._terminal) return; + if ( + !this._terminal.element || + !this._terminal.element.parentElement + ) + return; + const e = this._terminal._core, + t = e._renderService.dimensions; + if (0 === t.css.cell.width || 0 === t.css.cell.height) return; + const r = + 0 === this._terminal.options.scrollback + ? 0 + : e.viewport.scrollBarWidth, + i = window.getComputedStyle( + this._terminal.element.parentElement, + ), + o = parseInt(i.getPropertyValue("height")), + s = Math.max(0, parseInt(i.getPropertyValue("width"))), + n = window.getComputedStyle(this._terminal.element), + l = + o - + (parseInt(n.getPropertyValue("padding-top")) + + parseInt(n.getPropertyValue("padding-bottom"))), + a = + s - + (parseInt(n.getPropertyValue("padding-right")) + + parseInt(n.getPropertyValue("padding-left"))) - + r; + return { + cols: Math.max(2, Math.floor(a / t.css.cell.width)), + rows: Math.max(1, Math.floor(l / t.css.cell.height)), + }; + } + })); + })(), + e + ); + })(), +); +//# sourceMappingURL=xterm-addon-fit.js.map diff --git a/static/xterm.css b/static/xterm.css index 74acc26..18e66dc 100644 --- a/static/xterm.css +++ b/static/xterm.css @@ -79,7 +79,7 @@ .xterm .composition-view { /* TODO: Composition position got messed up somewhere */ background: #000; - color: #FFF; + color: #fff; display: none; position: absolute; white-space: nowrap; @@ -166,33 +166,55 @@ opacity: 1 !important; } -.xterm-underline-1 { text-decoration: underline; } -.xterm-underline-2 { text-decoration: double underline; } -.xterm-underline-3 { text-decoration: wavy underline; } -.xterm-underline-4 { text-decoration: dotted underline; } -.xterm-underline-5 { text-decoration: dashed underline; } +.xterm-underline-1 { + text-decoration: underline; +} +.xterm-underline-2 { + text-decoration: double underline; +} +.xterm-underline-3 { + text-decoration: wavy underline; +} +.xterm-underline-4 { + text-decoration: dotted underline; +} +.xterm-underline-5 { + text-decoration: dashed underline; +} .xterm-overline { text-decoration: overline; } -.xterm-overline.xterm-underline-1 { text-decoration: overline underline; } -.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; } -.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; } -.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; } -.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; } +.xterm-overline.xterm-underline-1 { + text-decoration: overline underline; +} +.xterm-overline.xterm-underline-2 { + text-decoration: overline double underline; +} +.xterm-overline.xterm-underline-3 { + text-decoration: overline wavy underline; +} +.xterm-overline.xterm-underline-4 { + text-decoration: overline dotted underline; +} +.xterm-overline.xterm-underline-5 { + text-decoration: overline dashed underline; +} .xterm-strikethrough { text-decoration: line-through; } .xterm-screen .xterm-decoration-container .xterm-decoration { - z-index: 6; - position: absolute; + z-index: 6; + position: absolute; } -.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { - z-index: 7; +.xterm-screen + .xterm-decoration-container + .xterm-decoration.xterm-decoration-top-layer { + z-index: 7; } .xterm-decoration-overview-ruler { diff --git a/static/xterm.js b/static/xterm.js index a68eae6..c365134 100644 --- a/static/xterm.js +++ b/static/xterm.js @@ -1,2 +1,14698 @@ -!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var s in i)("object"==typeof exports?exports:e)[s]=i[s]}}(self,(()=>(()=>{"use strict";var e={4567:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;const n=i(9042),o=i(6114),a=i(9924),h=i(844),c=i(5596),l=i(4725),d=i(3656);let _=t.AccessibilityManager=class extends h.Disposable{constructor(e,t){super(),this._terminal=e,this._renderService=t,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=document.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=document.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=document.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new a.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((e=>this._handleResize(e.rows)))),this.register(this._terminal.onRender((e=>this._refreshRows(e.start,e.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((e=>this._handleChar(e)))),this.register(this._terminal.onLineFeed((()=>this._handleChar("\n")))),this.register(this._terminal.onA11yTab((e=>this._handleTab(e)))),this.register(this._terminal.onKey((e=>this._handleKey(e.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this._screenDprMonitor=new c.ScreenDprMonitor(window),this.register(this._screenDprMonitor),this._screenDprMonitor.setListener((()=>this._refreshRowsDimensions())),this.register((0,d.addDisposableDomListener)(window,"resize",(()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,h.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,"\n"===e&&(this._liveRegionLineCount++,21===this._liveRegionLineCount&&(this._liveRegion.textContent+=n.tooMuchOutput)),o.isMac&&this._liveRegion.textContent&&this._liveRegion.textContent.length>0&&!this._liveRegion.parentNode&&setTimeout((()=>{this._accessibilityContainer.appendChild(this._liveRegion)}),0))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0,o.isMac&&this._liveRegion.remove()}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){const i=this._terminal.buffer,s=i.lines.length.toString();for(let r=e;r<=t;r++){const e=i.translateBufferLineToString(i.ydisp+r,!0),t=(i.ydisp+r+1).toString(),n=this._rowElements[r];n&&(0===e.length?n.innerText=" ":n.textContent=e,n.setAttribute("aria-posinset",t),n.setAttribute("aria-setsize",s))}this._announceCharacters()}_announceCharacters(){0!==this._charsToAnnounce.length&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){const i=e.target,s=this._rowElements[0===t?1:this._rowElements.length-2];if(i.getAttribute("aria-posinset")===(0===t?"1":`${this._terminal.buffer.lines.length}`))return;if(e.relatedTarget!==s)return;let r,n;if(0===t?(r=i,n=this._rowElements.pop(),this._rowContainer.removeChild(n)):(r=this._rowElements.shift(),n=i,this._rowContainer.removeChild(r)),r.removeEventListener("focus",this._topBoundaryFocusListener),n.removeEventListener("focus",this._bottomBoundaryFocusListener),0===t){const e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement("afterbegin",e)}else{const e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(0===t?-1:1),this._rowElements[0===t?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const e=document.createElement("div");return e.setAttribute("role","listitem"),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{function i(e){return e.replace(/\r?\n/g,"\r")}function s(e,t){return t?"[200~"+e+"[201~":e}function r(e,t,r,n){e=s(e=i(e),r.decPrivateModes.bracketedPasteMode&&!0!==n.rawOptions.ignoreBracketedPasteMode),r.triggerDataEvent(e,!0),t.value=""}function n(e,t,i){const s=i.getBoundingClientRect(),r=e.clientX-s.left-10,n=e.clientY-s.top-10;t.style.width="20px",t.style.height="20px",t.style.left=`${r}px`,t.style.top=`${n}px`,t.style.zIndex="1000",t.focus()}Object.defineProperty(t,"__esModule",{value:!0}),t.rightClickHandler=t.moveTextAreaUnderMouseCursor=t.paste=t.handlePasteEvent=t.copyHandler=t.bracketTextForPaste=t.prepareTextForTerminal=void 0,t.prepareTextForTerminal=i,t.bracketTextForPaste=s,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData("text/plain",t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,i,s){e.stopPropagation(),e.clipboardData&&r(e.clipboardData.getData("text/plain"),t,i,s)},t.paste=r,t.moveTextAreaUnderMouseCursor=n,t.rightClickHandler=function(e,t,i,s,r){n(e,t,i),r&&s.rightClickSelect(e),t.value=s.selectionText,t.select()}},7239:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorContrastCache=void 0;const s=i(1505);t.ColorContrastCache=class{constructor(){this._color=new s.TwoKeyMap,this._css=new s.TwoKeyMap}setCss(e,t,i){this._css.set(e,t,i)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,i){this._color.set(e,t,i)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},3656:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.addDisposableDomListener=void 0,t.addDisposableDomListener=function(e,t,i,s){e.addEventListener(t,i,s);let r=!1;return{dispose:()=>{r||(r=!0,e.removeEventListener(t,i,s))}}}},6465:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Linkifier2=void 0;const n=i(3656),o=i(8460),a=i(844),h=i(2585);let c=t.Linkifier2=class extends a.Disposable{get currentLink(){return this._currentLink}constructor(e){super(),this._bufferService=e,this._linkProviders=[],this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new o.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new o.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,a.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,a.toDisposable)((()=>{this._lastMouseEvent=void 0}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0})))}registerLinkProvider(e){return this._linkProviders.push(e),{dispose:()=>{const t=this._linkProviders.indexOf(e);-1!==t&&this._linkProviders.splice(t,1)}}}attachToDom(e,t,i){this._element=e,this._mouseService=t,this._renderService=i,this.register((0,n.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,n.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,n.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(e){if(this._lastMouseEvent=e,!this._element||!this._mouseService)return;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;const i=e.composedPath();for(let e=0;e{null==e||e.forEach((e=>{e.link.dispose&&e.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=e.y);let r=!1;for(const[i,n]of this._linkProviders.entries())t?(null===(s=this._activeProviderReplies)||void 0===s?void 0:s.get(i))&&(r=this._checkLinkProviderResult(i,e,r)):n.provideLinks(e.y,(t=>{var s,n;if(this._isMouseOut)return;const o=null==t?void 0:t.map((e=>({link:e})));null===(s=this._activeProviderReplies)||void 0===s||s.set(i,o),r=this._checkLinkProviderResult(i,e,r),(null===(n=this._activeProviderReplies)||void 0===n?void 0:n.size)===this._linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)}))}_removeIntersectingLinks(e,t){const i=new Set;for(let s=0;se?this._bufferService.cols:s.link.range.end.x;for(let e=n;e<=o;e++){if(i.has(e)){r.splice(t--,1);break}i.add(e)}}}}_checkLinkProviderResult(e,t,i){var s;if(!this._activeProviderReplies)return i;const r=this._activeProviderReplies.get(e);let n=!1;for(let t=0;tthis._linkAtPosition(e.link,t)));e&&(i=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviders.length&&!i)for(let e=0;ethis._linkAtPosition(e.link,t)));if(r){i=!0,this._handleNewLink(r);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._element||!this._mouseService||!this._currentLink)return;const t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){this._element&&this._currentLink&&this._lastMouseEvent&&(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,a.disposeArray)(this._linkCacheDisposables))}_handleNewLink(e){if(!this._element||!this._lastMouseEvent||!this._mouseService)return;const t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:void 0===e.link.decorations||e.link.decorations.underline,pointerCursor:void 0===e.link.decorations||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>{var e,t;return null===(t=null===(e=this._currentLink)||void 0===e?void 0:e.state)||void 0===t?void 0:t.decorations.pointerCursor},set:e=>{var t,i;(null===(t=this._currentLink)||void 0===t?void 0:t.state)&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&(null===(i=this._element)||void 0===i||i.classList.toggle("xterm-cursor-pointer",e)))}},underline:{get:()=>{var e,t;return null===(t=null===(e=this._currentLink)||void 0===e?void 0:e.state)||void 0===t?void 0:t.decorations.underline},set:t=>{var i,s,r;(null===(i=this._currentLink)||void 0===i?void 0:i.state)&&(null===(r=null===(s=this._currentLink)||void 0===s?void 0:s.state)||void 0===r?void 0:r.decorations.underline)!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._renderService&&this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((e=>{if(!this._currentLink)return;const t=0===e.start?0:e.start+1+this._bufferService.buffer.ydisp,i=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=i&&(this._clearCurrentLink(t,i),this._lastMouseEvent&&this._element)){const e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}}))))}_linkHover(e,t,i){var s;(null===(s=this._currentLink)||void 0===s?void 0:s.state)&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add("xterm-cursor-pointer")),t.hover&&t.hover(i,t.text)}_fireUnderlineEvent(e,t){const i=e.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(e,t,i){var s;(null===(s=this._currentLink)||void 0===s?void 0:s.state)&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove("xterm-cursor-pointer")),t.leave&&t.leave(i,t.text)}_linkAtPosition(e,t){const i=e.range.start.y*this._bufferService.cols+e.range.start.x,s=e.range.end.y*this._bufferService.cols+e.range.end.x,r=t.y*this._bufferService.cols+t.x;return i<=r&&r<=s}_positionFromMouseEvent(e,t,i){const s=i.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,i,s,r){return{x1:e,y1:t,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};t.Linkifier2=c=s([r(0,h.IBufferService)],c)},9042:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tooMuchOutput=t.promptLabel=void 0,t.promptLabel="Terminal input",t.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkProvider=void 0;const n=i(511),o=i(2585);let a=t.OscLinkProvider=class{constructor(e,t,i){this._bufferService=e,this._optionsService=t,this._oscLinkService=i}provideLinks(e,t){var i;const s=this._bufferService.buffer.lines.get(e-1);if(!s)return void t(void 0);const r=[],o=this._optionsService.rawOptions.linkHandler,a=new n.CellData,c=s.getTrimmedLength();let l=-1,d=-1,_=!1;for(let t=0;to?o.activate(e,t,i):h(0,t),hover:(e,t)=>{var s;return null===(s=null==o?void 0:o.hover)||void 0===s?void 0:s.call(o,e,t,i)},leave:(e,t)=>{var s;return null===(s=null==o?void 0:o.leave)||void 0===s?void 0:s.call(o,e,t,i)}})}_=!1,a.hasExtendedAttrs()&&a.extended.urlId?(d=t,l=a.extended.urlId):(d=-1,l=-1)}}t(r)}};function h(e,t){if(confirm(`Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`)){const e=window.open();if(e){try{e.opener=null}catch(e){}e.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}}t.OscLinkProvider=a=s([r(0,o.IBufferService),r(1,o.IOptionsService),r(2,o.IOscLinkService)],a)},6193:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenderDebouncer=void 0,t.RenderDebouncer=class{constructor(e,t){this._parentWindow=e,this._renderCallback=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._parentWindow.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t,this._animationFrame||(this._animationFrame=this._parentWindow.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return void this._runRefreshCallbacks();const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}}},5596:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ScreenDprMonitor=void 0;const s=i(844);class r extends s.Disposable{constructor(e){super(),this._parentWindow=e,this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this.register((0,s.toDisposable)((()=>{this.clearListener()})))}setListener(e){this._listener&&this.clearListener(),this._listener=e,this._outerListener=()=>{this._listener&&(this._listener(this._parentWindow.devicePixelRatio,this._currentDevicePixelRatio),this._updateDpr())},this._updateDpr()}_updateDpr(){var e;this._outerListener&&(null===(e=this._resolutionMediaMatchList)||void 0===e||e.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._listener&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._listener=void 0,this._outerListener=void 0)}}t.ScreenDprMonitor=r},3236:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Terminal=void 0;const s=i(3614),r=i(3656),n=i(6465),o=i(9042),a=i(3730),h=i(1680),c=i(3107),l=i(5744),d=i(2950),_=i(1296),u=i(428),f=i(4269),v=i(5114),p=i(8934),g=i(3230),m=i(9312),S=i(4725),C=i(6731),b=i(8055),y=i(8969),w=i(8460),E=i(844),k=i(6114),L=i(8437),D=i(2584),R=i(7399),x=i(5941),A=i(9074),B=i(2585),T=i(5435),M=i(4567),O="undefined"!=typeof window?window.document:null;class P extends y.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(e={}){super(e),this.browser=k,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new E.MutableDisposable),this._onCursorMove=this.register(new w.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new w.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new w.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new w.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new w.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new w.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new w.EventEmitter),this._onBlur=this.register(new w.EventEmitter),this._onA11yCharEmitter=this.register(new w.EventEmitter),this._onA11yTabEmitter=this.register(new w.EventEmitter),this._onWillOpen=this.register(new w.EventEmitter),this._setup(),this.linkifier2=this.register(this._instantiationService.createInstance(n.Linkifier2)),this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(a.OscLinkProvider)),this._decorationService=this._instantiationService.createInstance(A.DecorationService),this._instantiationService.setService(B.IDecorationService,this._decorationService),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((e,t)=>this.refresh(e,t)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((e=>this._reportWindowsOptions(e)))),this.register(this._inputHandler.onColor((e=>this._handleColorEvent(e)))),this.register((0,w.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,w.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,w.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,w.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((e=>this._afterResize(e.cols,e.rows)))),this.register((0,E.toDisposable)((()=>{var e,t;this._customKeyEventHandler=void 0,null===(t=null===(e=this.element)||void 0===e?void 0:e.parentNode)||void 0===t||t.removeChild(this.element)})))}_handleColorEvent(e){if(this._themeService)for(const t of e){let e,i="";switch(t.index){case 256:e="foreground",i="10";break;case 257:e="background",i="11";break;case 258:e="cursor",i="12";break;default:e="ansi",i="4;"+t.index}switch(t.type){case 0:const s=b.color.toColorRGB("ansi"===e?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${D.C0.ESC}]${i};${(0,x.toRgbString)(s)}${D.C1_ESCAPED.ST}`);break;case 1:if("ansi"===e)this._themeService.modifyColors((e=>e.ansi[t.index]=b.rgba.toColor(...t.color)));else{const i=e;this._themeService.modifyColors((e=>e[i]=b.rgba.toColor(...t.color)))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(M.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(D.C0.ESC+"[I"),this.updateCursorStyle(e),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var e;return null===(e=this.textarea)||void 0===e?void 0:e.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(D.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;const i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=t.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,r.addDisposableDomListener)(this.element,"copy",(e=>{this.hasSelection()&&(0,s.copyHandler)(e,this._selectionService)})));const e=e=>(0,s.handlePasteEvent)(e,this.textarea,this.coreService,this.optionsService);this.register((0,r.addDisposableDomListener)(this.textarea,"paste",e)),this.register((0,r.addDisposableDomListener)(this.element,"paste",e)),k.isFirefox?this.register((0,r.addDisposableDomListener)(this.element,"mousedown",(e=>{2===e.button&&(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this.register((0,r.addDisposableDomListener)(this.element,"contextmenu",(e=>{(0,s.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),k.isLinux&&this.register((0,r.addDisposableDomListener)(this.element,"auxclick",(e=>{1===e.button&&(0,s.moveTextAreaUnderMouseCursor)(e,this.textarea,this.screenElement)})))}_bindKeys(){this.register((0,r.addDisposableDomListener)(this.textarea,"keyup",(e=>this._keyUp(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"keydown",(e=>this._keyDown(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"keypress",(e=>this._keyPress(e)),!0)),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionupdate",(e=>this._compositionHelper.compositionupdate(e)))),this.register((0,r.addDisposableDomListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this.register((0,r.addDisposableDomListener)(this.textarea,"input",(e=>this._inputEvent(e)),!0)),this.register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(e){var t;if(!e)throw new Error("Terminal requires a parent element.");e.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this._document=e.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),e.appendChild(this.element);const i=O.createDocumentFragment();this._viewportElement=O.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),i.appendChild(this._viewportElement),this._viewportScrollArea=O.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=O.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._helperContainer=O.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),i.appendChild(this.screenElement),this.textarea=O.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",o.promptLabel),k.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this._instantiationService.createInstance(v.CoreBrowserService,this.textarea,null!==(t=this._document.defaultView)&&void 0!==t?t:window),this._instantiationService.setService(S.ICoreBrowserService,this._coreBrowserService),this.register((0,r.addDisposableDomListener)(this.textarea,"focus",(e=>this._handleTextAreaFocus(e)))),this.register((0,r.addDisposableDomListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(u.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(S.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(C.ThemeService),this._instantiationService.setService(S.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(f.CharacterJoinerService),this._instantiationService.setService(S.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(g.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(S.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange((e=>this._onRender.fire(e)))),this.onResize((e=>this._renderService.resize(e.cols,e.rows))),this._compositionView=O.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(d.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this.element.appendChild(i);try{this._onWillOpen.fire(this.element)}catch(e){}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._mouseService=this._instantiationService.createInstance(p.MouseService),this._instantiationService.setService(S.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(h.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent,1))),this.register(this._inputHandler.onRequestSyncScrollBar((()=>this.viewport.syncScrollArea()))),this.register(this.viewport),this.register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this.register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this.register(this.onBlur((()=>this._renderService.handleBlur()))),this.register(this.onFocus((()=>this._renderService.handleFocus()))),this.register(this._renderService.onDimensionsChange((()=>this.viewport.syncScrollArea()))),this._selectionService=this.register(this._instantiationService.createInstance(m.SelectionService,this.element,this.screenElement,this.linkifier2)),this._instantiationService.setService(S.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent)))),this.register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this.register(this._selectionService.onRequestRedraw((e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode)))),this.register(this._selectionService.onLinuxMouseSelection((e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()}))),this.register(this._onScroll.event((e=>{this.viewport.syncScrollArea(),this._selectionService.refresh()}))),this.register((0,r.addDisposableDomListener)(this._viewportElement,"scroll",(()=>this._selectionService.refresh()))),this.linkifier2.attachToDom(this.screenElement,this._mouseService,this._renderService),this.register(this._instantiationService.createInstance(c.BufferDecorationRenderer,this.screenElement)),this.register((0,r.addDisposableDomListener)(this.element,"mousedown",(e=>this._selectionService.handleMouseDown(e)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(M.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",(e=>this._handleScreenReaderModeOptionChange(e)))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",(e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(l.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(_.DomRenderer,this.element,this.screenElement,this._viewportElement,this.linkifier2)}bindMouse(){const e=this,t=this.element;function i(t){const i=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!i)return!1;let s,r;switch(t.overrideType||t.type){case"mousemove":r=32,void 0===t.buttons?(s=3,void 0!==t.button&&(s=t.button<3?t.button:3)):s=1&t.buttons?0:4&t.buttons?1:2&t.buttons?2:3;break;case"mouseup":r=0,s=t.button<3?t.button:3;break;case"mousedown":r=1,s=t.button<3?t.button:3;break;case"wheel":if(0===e.viewport.getLinesScrolled(t))return!1;r=t.deltaY<0?0:1,s=4;break;default:return!1}return!(void 0===r||void 0===s||s>4)&&e.coreMouseService.triggerMouseEvent({col:i.col,row:i.row,x:i.x,y:i.y,button:s,action:r,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}const s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},n={mouseup:e=>(i(e),e.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(e)),wheel:e=>(i(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&i(e)},mousemove:e=>{e.buttons||i(e)}};this.register(this.coreMouseService.onProtocolChange((e=>{e?("debug"===this.optionsService.rawOptions.logLevel&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(e)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&e?s.mousemove||(t.addEventListener("mousemove",n.mousemove),s.mousemove=n.mousemove):(t.removeEventListener("mousemove",s.mousemove),s.mousemove=null),16&e?s.wheel||(t.addEventListener("wheel",n.wheel,{passive:!1}),s.wheel=n.wheel):(t.removeEventListener("wheel",s.wheel),s.wheel=null),2&e?s.mouseup||(t.addEventListener("mouseup",n.mouseup),s.mouseup=n.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),t.removeEventListener("mouseup",s.mouseup),s.mouseup=null),4&e?s.mousedrag||(s.mousedrag=n.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,r.addDisposableDomListener)(t,"mousedown",(e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return i(e),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(e)}))),this.register((0,r.addDisposableDomListener)(t,"wheel",(e=>{if(!s.wheel){if(!this.buffer.hasScrollback){const t=this.viewport.getLinesScrolled(e);if(0===t)return;const i=D.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(e.deltaY<0?"A":"B");let s="";for(let e=0;e{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(e),this.cancel(e)}),{passive:!0})),this.register((0,r.addDisposableDomListener)(t,"touchmove",(e=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(e)?void 0:this.cancel(e)}),{passive:!1}))}refresh(e,t){var i;null===(i=this._renderService)||void 0===i||i.refreshRows(e,t)}updateCursorStyle(e){var t;(null===(t=this._selectionService)||void 0===t?void 0:t.shouldColumnSelect(e))?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t,i=0){var s;1===i?(super.scrollLines(e,t,i),this.refresh(0,this.rows-1)):null===(s=this.viewport)||void 0===s||s.scrollLines(e)}paste(e){(0,s.paste)(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}registerLinkProvider(e){return this.linkifier2.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,t,i){this._selectionService.setSelection(e,t,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var e;null===(e=this._selectionService)||void 0===e||e.clearSelection()}selectAll(){var e;null===(e=this._selectionService)||void 0===e||e.selectAll()}selectLines(e,t){var i;null===(i=this._selectionService)||void 0===i||i.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;const t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;t||"Dead"!==e.key&&"AltGraph"!==e.key||(this._unprocessedDeadKey=!0);const i=(0,R.evaluateKeyboardEvent)(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),3===i.type||2===i.type){const t=this.rows-1;return this.scrollLines(2===i.type?-t:t),this.cancel(e,!0)}return 1===i.type&&this.selectAll(),!!this._isThirdLevelShift(this.browser,e)||(i.cancel&&this.cancel(e,!0),!i.key||!!(e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&1===e.key.length&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(i.key!==D.C0.ETX&&i.key!==D.C0.CR||(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey?this.cancel(e,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(e,t){const i=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState("AltGraph");return"keypress"===t.type?i:i&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return 16===e.keyCode||17===e.keyCode||18===e.keyCode}(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled)return!1;if(this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(null===e.which||void 0===e.which)t=e.keyCode;else{if(0===e.which||0===e.charCode)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)||(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(e){if(e.data&&"insertText"===e.inputType&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e!==this.cols||t!==this.rows?super.resize(e,t):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(e,t){var i,s;null===(i=this._charSizeService)||void 0===i||i.measure(),null===(s=this.viewport)||void 0===s||s.syncScrollArea(!0)}clear(){var e;if(0!==this.buffer.ybase||0!==this.buffer.y){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeBasedDebouncer=void 0,t.TimeBasedDebouncer=class{constructor(e,t=1e3){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,i){this._rowCount=i,e=void 0!==e?e:0,t=void 0!==t?t:this._rowCount-1,this._rowStart=void 0!==this._rowStart?Math.min(this._rowStart,e):e,this._rowEnd=void 0!==this._rowEnd?Math.max(this._rowEnd,t):t;const s=Date.now();if(s-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=s,this._innerRefresh();else if(!this._additionalRefreshRequested){const e=s-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),t)}}_innerRefresh(){if(void 0===this._rowStart||void 0===this._rowEnd||void 0===this._rowCount)return;const e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}}},1680:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Viewport=void 0;const n=i(3656),o=i(4725),a=i(8460),h=i(844),c=i(2585);let l=t.Viewport=class extends h.Disposable{constructor(e,t,i,s,r,o,h,c){super(),this._viewportElement=e,this._scrollArea=t,this._bufferService=i,this._optionsService=s,this._charSizeService=r,this._renderService=o,this._coreBrowserService=h,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new a.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,n.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange((e=>this._renderDimensions=e))),this._handleThemeChange(c.colors),this.register(c.onChangeColors((e=>this._handleThemeChange(e)))),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.syncScrollArea()))),setTimeout((()=>this.syncScrollArea()))}_handleThemeChange(e){this._viewportElement.style.backgroundColor=e.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame((()=>this.syncScrollArea()))}_refresh(e){if(e)return this._innerRefresh(),void(null!==this._refreshAnimationFrame&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));null===this._refreshAnimationFrame&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderService.dimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderService.dimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const e=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.css.canvas.height);this._lastRecordedBufferHeight!==e&&(this._lastRecordedBufferHeight=e,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const e=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==e&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=e),this._refreshAnimationFrame=null}syncScrollArea(e=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(e);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(e)}_handleScroll(e){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const t=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:t,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||-1===this._smoothScrollState.origin||-1===this._smoothScrollState.target)return;const e=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(e*(this._smoothScrollState.target-this._smoothScrollState.origin)),e<1?this._coreBrowserService.window.requestAnimationFrame((()=>this._smoothScroll())):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(e,t){const i=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(t<0&&0!==this._viewportElement.scrollTop||t>0&&i0&&(s=e),r=""}}return{bufferElements:n,cursorElement:s}}getLinesScrolled(e){if(0===e.deltaY||e.shiftKey)return 0;let t=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(t/=this._currentRowHeight+0,this._wheelPartialScroll+=t,t=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(t*=this._bufferService.rows),t}_applyScrollModifier(e,t){const i=this._optionsService.rawOptions.fastScrollModifier;return"alt"===i&&t.altKey||"ctrl"===i&&t.ctrlKey||"shift"===i&&t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(e){this._lastTouchY=e.touches[0].pageY}handleTouchMove(e){const t=this._lastTouchY-e.touches[0].pageY;return this._lastTouchY=e.touches[0].pageY,0!==t&&(this._viewportElement.scrollTop+=t,this._bubbleScroll(e,t))}};t.Viewport=l=s([r(2,c.IBufferService),r(3,c.IOptionsService),r(4,o.ICharSizeService),r(5,o.IRenderService),r(6,o.ICoreBrowserService),r(7,o.IThemeService)],l)},3107:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferDecorationRenderer=void 0;const n=i(3656),o=i(4725),a=i(844),h=i(2585);let c=t.BufferDecorationRenderer=class extends a.Disposable{constructor(e,t,i,s){super(),this._screenElement=e,this._bufferService=t,this._decorationService=i,this._renderService=s,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this.register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this.register((0,n.addDisposableDomListener)(window,"resize",(()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this.register(this._decorationService.onDecorationRemoved((e=>this._removeDecoration(e)))),this.register((0,a.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){void 0===this._animationFrame&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var t,i;const s=document.createElement("div");s.classList.add("xterm-decoration"),s.classList.toggle("xterm-decoration-top-layer","top"===(null===(t=null==e?void 0:e.options)||void 0===t?void 0:t.layer)),s.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,s.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+"px",s.style.top=(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",s.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const r=null!==(i=e.options.x)&&void 0!==i?i:0;return r&&r>this._bufferService.cols&&(s.style.display="none"),this._refreshXPosition(e,s),s}_refreshStyle(e){const t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display="none",e.onRenderEmitter.fire(e.element));else{let i=this._decorationElements.get(e);i||(i=this._createElement(e),e.element=i,this._decorationElements.set(e,i),this._container.appendChild(i),e.onDispose((()=>{this._decorationElements.delete(e),i.remove()}))),i.style.top=t*this._renderService.dimensions.css.cell.height+"px",i.style.display=this._altBufferIsActive?"none":"block",e.onRenderEmitter.fire(i)}}_refreshXPosition(e,t=e.element){var i;if(!t)return;const s=null!==(i=e.options.x)&&void 0!==i?i:0;"right"===(e.options.anchor||"left")?t.style.right=s?s*this._renderService.dimensions.css.cell.width+"px":"":t.style.left=s?s*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(e){var t;null===(t=this._decorationElements.get(e))||void 0===t||t.remove(),this._decorationElements.delete(e),e.dispose()}};t.BufferDecorationRenderer=c=s([r(1,h.IBufferService),r(2,h.IDecorationService),r(3,o.IRenderService)],c)},5871:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorZoneStore=void 0,t.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(const t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position))return void this._addLineToZone(t,e.marker.line)}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,i){return t>=e.startBufferLine-this._linePadding[i||"full"]&&t<=e.endBufferLine+this._linePadding[i||"full"]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}}},5744:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OverviewRulerRenderer=void 0;const n=i(5871),o=i(3656),a=i(4725),h=i(844),c=i(2585),l={full:0,left:0,center:0,right:0},d={full:0,left:0,center:0,right:0},_={full:0,left:0,center:0,right:0};let u=t.OverviewRulerRenderer=class extends h.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(e,t,i,s,r,o,a){var c;super(),this._viewportElement=e,this._screenElement=t,this._bufferService=i,this._decorationService=s,this._renderService=r,this._optionsService=o,this._coreBrowseService=a,this._colorZoneStore=new n.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=document.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),null===(c=this._viewportElement.parentElement)||void 0===c||c.insertBefore(this._canvas,this._viewportElement);const l=this._canvas.getContext("2d");if(!l)throw new Error("Ctx cannot be null");this._ctx=l,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,h.toDisposable)((()=>{var e;null===(e=this._canvas)||void 0===e||e.remove()})))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this.register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0))))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"}))),this.register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",(()=>this._queueRefresh(!0)))),this.register((0,o.addDisposableDomListener)(this._coreBrowseService.window,"resize",(()=>this._queueRefresh(!0)))),this._queueRefresh(!0)}_refreshDrawConstants(){const e=Math.floor(this._canvas.width/3),t=Math.ceil(this._canvas.width/3);d.full=this._canvas.width,d.left=e,d.center=t,d.right=e,this._refreshDrawHeightConstants(),_.full=0,_.left=0,_.center=d.left,_.right=d.left+d.center}_refreshDrawHeightConstants(){l.full=Math.round(2*this._coreBrowseService.dpr);const e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowseService.dpr);l.left=t,l.center=t,l.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowseService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowseService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1;const e=this._colorZoneStore.zones;for(const t of e)"full"!==t.position&&this._renderColorZone(t);for(const t of e)"full"===t.position&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(_[e.position||"full"],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-l[e.position||"full"]/2),d[e.position||"full"],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+l[e.position||"full"]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,void 0===this._animationFrame&&(this._animationFrame=this._coreBrowseService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};t.OverviewRulerRenderer=u=s([r(2,c.IBufferService),r(3,c.IDecorationService),r(4,a.IRenderService),r(5,c.IOptionsService),r(6,a.ICoreBrowserService)],u)},2950:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositionHelper=void 0;const n=i(4725),o=i(2585),a=i(2584);let h=t.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(e,t,i,s,r,n){this._textarea=e,this._compositionView=t,this._bufferService=i,this._optionsService=s,this._coreService=r,this._renderService=n,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(229===e.keyCode)return!1;if(16===e.keyCode||17===e.keyCode||18===e.keyCode)return!1;this._finalizeComposition(!1)}return 229!==e.keyCode||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=!1,e){const e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let t;this._isSendingComposition=!1,e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,e.end):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}}),0)}else{this._isSendingComposition=!1;const e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){const e=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const t=this._textarea.value,i=t.replace(e,"");this._dataAlreadySent=i,t.length>e.length?this._coreService.triggerDataEvent(i,!0):t.lengththis.updateCompositionElements(!0)),0)}}};t.CompositionHelper=h=s([r(2,o.IBufferService),r(3,o.IOptionsService),r(4,o.ICoreService),r(5,n.IRenderService)],h)},9806:(e,t)=>{function i(e,t,i){const s=i.getBoundingClientRect(),r=e.getComputedStyle(i),n=parseInt(r.getPropertyValue("padding-left")),o=parseInt(r.getPropertyValue("padding-top"));return[t.clientX-s.left-n,t.clientY-s.top-o]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoords=t.getCoordsRelativeToElement=void 0,t.getCoordsRelativeToElement=i,t.getCoords=function(e,t,s,r,n,o,a,h,c){if(!o)return;const l=i(e,t,s);return l?(l[0]=Math.ceil((l[0]+(c?a/2:0))/a),l[1]=Math.ceil(l[1]/h),l[0]=Math.min(Math.max(l[0],1),r+(c?1:0)),l[1]=Math.min(Math.max(l[1],1),n),l):void 0}},9504:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.moveToCellSequence=void 0;const s=i(2584);function r(e,t,i,s){const r=e-n(e,i),a=t-n(t,i),l=Math.abs(r-a)-function(e,t,i){let s=0;const r=e-n(e,i),a=t-n(t,i);for(let n=0;n=0&&et?"A":"B"}function a(e,t,i,s,r,n){let o=e,a=t,h="";for(;o!==i||a!==s;)o+=r?1:-1,r&&o>n.cols-1?(h+=n.buffer.translateBufferLineToString(a,!1,e,o),o=0,e=0,a++):!r&&o<0&&(h+=n.buffer.translateBufferLineToString(a,!1,0,e+1),o=n.cols-1,e=o,a--);return h+n.buffer.translateBufferLineToString(a,!1,e,o)}function h(e,t){const i=t?"O":"[";return s.C0.ESC+i+e}function c(e,t){e=Math.floor(e);let i="";for(let s=0;s0?s-n(s,o):t;const _=s,u=function(e,t,i,s,o,a){let h;return h=r(i,s,o,a).length>0?s-n(s,o):t,e=i&&he?"D":"C",c(Math.abs(o-e),h(d,s));d=l>t?"D":"C";const _=Math.abs(l-t);return c(function(e,t){return t.cols-e}(l>t?e:o,i)+(_-1)*i.cols+1+((l>t?o:e)-1),h(d,s))}},1296:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRenderer=void 0;const n=i(3787),o=i(2550),a=i(2223),h=i(6171),c=i(4725),l=i(8055),d=i(8460),_=i(844),u=i(2585),f="xterm-dom-renderer-owner-",v="xterm-rows",p="xterm-fg-",g="xterm-bg-",m="xterm-focus",S="xterm-selection";let C=1,b=t.DomRenderer=class extends _.Disposable{constructor(e,t,i,s,r,a,c,l,u,p){super(),this._element=e,this._screenElement=t,this._viewportElement=i,this._linkifier2=s,this._charSizeService=a,this._optionsService=c,this._bufferService=l,this._coreBrowserService=u,this._themeService=p,this._terminalClass=C++,this._rowElements=[],this.onRequestRedraw=this.register(new d.EventEmitter).event,this._rowContainer=document.createElement("div"),this._rowContainer.classList.add(v),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=document.createElement("div"),this._selectionContainer.classList.add(S),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,h.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._themeService.onChangeColors((e=>this._injectCss(e)))),this._injectCss(this._themeService.colors),this._rowFactory=r.createInstance(n.DomRendererRowFactory,document),this._element.classList.add(f+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline((e=>this._handleLinkHover(e)))),this.register(this._linkifier2.onHideLinkUnderline((e=>this._handleLinkLeave(e)))),this.register((0,_.toDisposable)((()=>{this._element.classList.remove(f+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new o.WidthCache(document),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const t=`${this._terminalSelector} .${v} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${v} { color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${v} .xterm-dim { color: ${l.color.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`,t+="@keyframes blink_box_shadow_"+this._terminalClass+" { 50% { border-bottom-style: hidden; }}",t+="@keyframes blink_block_"+this._terminalClass+" { 0% {"+` background-color: ${e.cursor.css};`+` color: ${e.cursorAccent.css}; } 50% { background-color: inherit;`+` color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${v}.${m} .xterm-cursor.xterm-cursor-blink:not(.xterm-cursor-block) { animation: blink_box_shadow_`+this._terminalClass+" 1s step-end infinite;}"+`${this._terminalSelector} .${v}.${m} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: blink_block_`+this._terminalClass+" 1s step-end infinite;}"+`${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-block {`+` background-color: ${e.cursor.css};`+` color: ${e.cursorAccent.css};}`+`${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-outline {`+` outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}`+`${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-bar {`+` box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}`+`${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-underline {`+` border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${S} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${S} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${S} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(const[i,s]of e.ansi.entries())t+=`${this._terminalSelector} .${p}${i} { color: ${s.css}; }${this._terminalSelector} .${p}${i}.xterm-dim { color: ${l.color.multiplyOpacity(s,.5).css}; }${this._terminalSelector} .${g}${i} { background-color: ${s.css}; }`;t+=`${this._terminalSelector} .${p}${a.INVERTED_DEFAULT_COLOR} { color: ${l.color.opaque(e.background).css}; }${this._terminalSelector} .${p}${a.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${l.color.multiplyOpacity(l.color.opaque(e.background),.5).css}; }${this._terminalSelector} .${g}${a.INVERTED_DEFAULT_COLOR} { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){const e=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){const e=document.createElement("div");this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions()}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(m)}handleFocus(){this._rowContainer.classList.add(m),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,i){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,i),this.renderRows(0,this._bufferService.rows-1),!e||!t)return;const s=e[1]-this._bufferService.buffer.ydisp,r=t[1]-this._bufferService.buffer.ydisp,n=Math.max(s,0),o=Math.min(r,this._bufferService.rows-1);if(n>=this._bufferService.rows||o<0)return;const a=document.createDocumentFragment();if(i){const i=e[0]>t[0];a.appendChild(this._createSelectionElement(n,i?t[0]:e[0],i?e[0]:t[0],o-n+1))}else{const i=s===n?e[0]:0,h=n===r?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(n,i,h));const c=o-n-1;if(a.appendChild(this._createSelectionElement(n+1,0,this._bufferService.cols,c)),n!==o){const e=r===o?t[0]:this._bufferService.cols;a.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(a)}_createSelectionElement(e,t,i,s=1){const r=document.createElement("div");return r.style.height=s*this.dimensions.css.cell.height+"px",r.style.top=e*this.dimensions.css.cell.height+"px",r.style.left=t*this.dimensions.css.cell.width+"px",r.style.width=this.dimensions.css.cell.width*(i-t)+"px",r}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const e of this._rowElements)e.replaceChildren()}renderRows(e,t){const i=this._bufferService.buffer,s=i.ybase+i.y,r=Math.min(i.x,this._bufferService.cols-1),n=this._optionsService.rawOptions.cursorBlink,o=this._optionsService.rawOptions.cursorStyle,a=this._optionsService.rawOptions.cursorInactiveStyle;for(let h=e;h<=t;h++){const e=h+i.ydisp,t=this._rowElements[h],c=i.lines.get(e);if(!t||!c)break;t.replaceChildren(...this._rowFactory.createRow(c,e,e===s,o,a,r,n,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${f}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,i,s,r,n){i<0&&(e=0),s<0&&(t=0);const o=this._bufferService.rows-1;i=Math.max(Math.min(i,o),0),s=Math.max(Math.min(s,o),0),r=Math.min(r,this._bufferService.cols);const a=this._bufferService.buffer,h=a.ybase+a.y,c=Math.min(a.x,r-1),l=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,_=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=i;o<=s;++o){const u=o+a.ydisp,f=this._rowElements[o],v=a.lines.get(u);if(!f||!v)break;f.replaceChildren(...this._rowFactory.createRow(v,u,u===h,d,_,c,l,this.dimensions.css.cell.width,this._widthCache,n?o===i?e:0:-1,n?(o===s?t:r)-1:-1))}}};t.DomRenderer=b=s([r(4,u.IInstantiationService),r(5,c.ICharSizeService),r(6,u.IOptionsService),r(7,u.IBufferService),r(8,c.ICoreBrowserService),r(9,c.IThemeService)],b)},3787:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRendererRowFactory=void 0;const n=i(2223),o=i(643),a=i(511),h=i(2585),c=i(8055),l=i(4725),d=i(4269),_=i(6171),u=i(3734);let f=t.DomRendererRowFactory=class{constructor(e,t,i,s,r,n,o){this._document=e,this._characterJoinerService=t,this._optionsService=i,this._coreBrowserService=s,this._coreService=r,this._decorationService=n,this._themeService=o,this._workCell=new a.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,i){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=i}createRow(e,t,i,s,r,a,h,l,_,f,p){const g=[],m=this._characterJoinerService.getJoinedCharacters(t),S=this._themeService.colors;let C,b=e.getNoBgTrimmedLength();i&&b0&&M===m[0][0]){O=!0;const t=m.shift();I=new d.JoinedCellData(this._workCell,e.translateToString(!0,t[0],t[1]),t[1]-t[0]),P=t[1]-1,b=I.getWidth()}const H=this._isCellInSelection(M,t),F=i&&M===a,W=T&&M>=f&&M<=p;let U=!1;this._decorationService.forEachDecorationAtCell(M,t,void 0,(e=>{U=!0}));let N=I.getChars()||o.WHITESPACE_CELL_CHAR;if(" "===N&&(I.isUnderline()||I.isOverline())&&(N=" "),A=b*l-_.get(N,I.isBold(),I.isItalic()),C){if(y&&(H&&x||!H&&!x&&I.bg===E)&&(H&&x&&S.selectionForeground||I.fg===k)&&I.extended.ext===L&&W===D&&A===R&&!F&&!O&&!U){w+=N,y++;continue}y&&(C.textContent=w),C=this._document.createElement("span"),y=0,w=""}else C=this._document.createElement("span");if(E=I.bg,k=I.fg,L=I.extended.ext,D=W,R=A,x=H,O&&a>=M&&a<=P&&(a=M),!this._coreService.isCursorHidden&&F)if(B.push("xterm-cursor"),this._coreBrowserService.isFocused)h&&B.push("xterm-cursor-blink"),B.push("bar"===s?"xterm-cursor-bar":"underline"===s?"xterm-cursor-underline":"xterm-cursor-block");else if(r)switch(r){case"outline":B.push("xterm-cursor-outline");break;case"block":B.push("xterm-cursor-block");break;case"bar":B.push("xterm-cursor-bar");break;case"underline":B.push("xterm-cursor-underline")}if(I.isBold()&&B.push("xterm-bold"),I.isItalic()&&B.push("xterm-italic"),I.isDim()&&B.push("xterm-dim"),w=I.isInvisible()?o.WHITESPACE_CELL_CHAR:I.getChars()||o.WHITESPACE_CELL_CHAR,I.isUnderline()&&(B.push(`xterm-underline-${I.extended.underlineStyle}`)," "===w&&(w=" "),!I.isUnderlineColorDefault()))if(I.isUnderlineColorRGB())C.style.textDecorationColor=`rgb(${u.AttributeData.toColorRGB(I.getUnderlineColor()).join(",")})`;else{let e=I.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&I.isBold()&&e<8&&(e+=8),C.style.textDecorationColor=S.ansi[e].css}I.isOverline()&&(B.push("xterm-overline")," "===w&&(w=" ")),I.isStrikethrough()&&B.push("xterm-strikethrough"),W&&(C.style.textDecoration="underline");let $=I.getFgColor(),j=I.getFgColorMode(),z=I.getBgColor(),K=I.getBgColorMode();const q=!!I.isInverse();if(q){const e=$;$=z,z=e;const t=j;j=K,K=t}let V,G,X,J=!1;switch(this._decorationService.forEachDecorationAtCell(M,t,void 0,(e=>{"top"!==e.options.layer&&J||(e.backgroundColorRGB&&(K=50331648,z=e.backgroundColorRGB.rgba>>8&16777215,V=e.backgroundColorRGB),e.foregroundColorRGB&&(j=50331648,$=e.foregroundColorRGB.rgba>>8&16777215,G=e.foregroundColorRGB),J="top"===e.options.layer)})),!J&&H&&(V=this._coreBrowserService.isFocused?S.selectionBackgroundOpaque:S.selectionInactiveBackgroundOpaque,z=V.rgba>>8&16777215,K=50331648,J=!0,S.selectionForeground&&(j=50331648,$=S.selectionForeground.rgba>>8&16777215,G=S.selectionForeground)),J&&B.push("xterm-decoration-top"),K){case 16777216:case 33554432:X=S.ansi[z],B.push(`xterm-bg-${z}`);break;case 50331648:X=c.rgba.toColor(z>>16,z>>8&255,255&z),this._addStyle(C,`background-color:#${v((z>>>0).toString(16),"0",6)}`);break;default:q?(X=S.foreground,B.push(`xterm-bg-${n.INVERTED_DEFAULT_COLOR}`)):X=S.background}switch(V||I.isDim()&&(V=c.color.multiplyOpacity(X,.5)),j){case 16777216:case 33554432:I.isBold()&&$<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&($+=8),this._applyMinimumContrast(C,X,S.ansi[$],I,V,void 0)||B.push(`xterm-fg-${$}`);break;case 50331648:const e=c.rgba.toColor($>>16&255,$>>8&255,255&$);this._applyMinimumContrast(C,X,e,I,V,G)||this._addStyle(C,`color:#${v($.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(C,X,S.foreground,I,V,void 0)||q&&B.push(`xterm-fg-${n.INVERTED_DEFAULT_COLOR}`)}B.length&&(C.className=B.join(" "),B.length=0),F||O||U?C.textContent=w:y++,A!==this.defaultSpacing&&(C.style.letterSpacing=`${A}px`),g.push(C),M=P}return C&&y&&(C.textContent=w),g}_applyMinimumContrast(e,t,i,s,r,n){if(1===this._optionsService.rawOptions.minimumContrastRatio||(0,_.excludeFromContrastRatioDemands)(s.getCode()))return!1;const o=this._getContrastCache(s);let a;if(r||n||(a=o.getColor(t.rgba,i.rgba)),void 0===a){const e=this._optionsService.rawOptions.minimumContrastRatio/(s.isDim()?2:1);a=c.color.ensureContrastRatio(r||t,n||i,e),o.setColor((r||t).rgba,(n||i).rgba,null!=a?a:null)}return!!a&&(this._addStyle(e,`color:${a.css}`),!0)}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute("style",`${e.getAttribute("style")||""}${t};`)}_isCellInSelection(e,t){const i=this._selectionStart,s=this._selectionEnd;return!(!i||!s)&&(this._columnSelectMode?i[0]<=s[0]?e>=i[0]&&t>=i[1]&&e=i[1]&&e>=s[0]&&t<=s[1]:t>i[1]&&t=i[0]&&e=i[0])}};function v(e,t,i){for(;e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.WidthCache=void 0,t.WidthCache=class{constructor(e){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=e.createElement("div"),this._container.style.position="absolute",this._container.style.top="-50000px",this._container.style.width="50000px",this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const t=e.createElement("span"),i=e.createElement("span");i.style.fontWeight="bold";const s=e.createElement("span");s.style.fontStyle="italic";const r=e.createElement("span");r.style.fontWeight="bold",r.style.fontStyle="italic",this._measureElements=[t,i,s,r],this._container.appendChild(t),this._container.appendChild(i),this._container.appendChild(s),this._container.appendChild(r),e.body.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(e,t,i,s){e===this._font&&t===this._fontSize&&i===this._weight&&s===this._weightBold||(this._font=e,this._fontSize=t,this._weight=i,this._weightBold=s,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${i}`,this._measureElements[1].style.fontWeight=`${s}`,this._measureElements[2].style.fontWeight=`${i}`,this._measureElements[3].style.fontWeight=`${s}`,this.clear())}get(e,t,i){let s=0;if(!t&&!i&&1===e.length&&(s=e.charCodeAt(0))<256)return-9999!==this._flat[s]?this._flat[s]:this._flat[s]=this._measure(e,0);let r=e;t&&(r+="B"),i&&(r+="I");let n=this._holey.get(r);if(void 0===n){let s=0;t&&(s|=1),i&&(s|=2),n=this._measure(e,s),this._holey.set(r,n)}return n}_measure(e,t){const i=this._measureElements[t];return i.textContent=e.repeat(32),i.offsetWidth/32}}},2223:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TEXT_BASELINE=t.DIM_OPACITY=t.INVERTED_DEFAULT_COLOR=void 0;const s=i(6114);t.INVERTED_DEFAULT_COLOR=257,t.DIM_OPACITY=.5,t.TEXT_BASELINE=s.isFirefox||s.isLegacyEdge?"bottom":"ideographic"},6171:(e,t)=>{function i(e){return 57508<=e&&e<=57558}Object.defineProperty(t,"__esModule",{value:!0}),t.createRenderDimensions=t.excludeFromContrastRatioDemands=t.isRestrictedPowerlineGlyph=t.isPowerlineGlyph=t.throwIfFalsy=void 0,t.throwIfFalsy=function(e){if(!e)throw new Error("value must not be falsy");return e},t.isPowerlineGlyph=i,t.isRestrictedPowerlineGlyph=function(e){return 57520<=e&&e<=57527},t.excludeFromContrastRatioDemands=function(e){return i(e)||function(e){return 9472<=e&&e<=9631}(e)},t.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}}},456:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionModel=void 0,t.SelectionModel=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharSizeService=void 0;const n=i(2585),o=i(8460),a=i(844);let h=t.CharSizeService=class extends a.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(e,t,i){super(),this._optionsService=i,this.width=0,this.height=0,this._onCharSizeChange=this.register(new o.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event,this._measureStrategy=new c(e,t,this._optionsService),this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};t.CharSizeService=h=s([r(2,n.IOptionsService)],h);class c{constructor(e,t,i){this._document=e,this._parentElement=t,this._optionsService=i,this._result={width:0,height:0},this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`;const e={height:Number(this._measureElement.offsetHeight),width:Number(this._measureElement.offsetWidth)};return 0!==e.width&&0!==e.height&&(this._result.width=e.width/32,this._result.height=Math.ceil(e.height)),this._result}}},4269:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharacterJoinerService=t.JoinedCellData=void 0;const n=i(3734),o=i(643),a=i(511),h=i(2585);class c extends n.AttributeData{constructor(e,t,i){super(),this.content=0,this.combinedData="",this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=i}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.JoinedCellData=c;let l=t.CharacterJoinerService=class e{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new a.CellData}register(e){const t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t1){const e=this._getJoinedRanges(s,a,n,t,r);for(let t=0;t1){const e=this._getJoinedRanges(s,a,n,t,r);for(let t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserService=void 0,t.CoreBrowserService=class{constructor(e,t){this._textarea=e,this.window=t,this._isFocused=!1,this._cachedIsFocused=void 0,this._textarea.addEventListener("focus",(()=>this._isFocused=!0)),this._textarea.addEventListener("blur",(()=>this._isFocused=!1))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return void 0===this._cachedIsFocused&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}},8934:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseService=void 0;const n=i(4725),o=i(9806);let a=t.MouseService=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,i,s,r){return(0,o.getCoords)(window,e,t,i,s,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,r)}getMouseReportCoords(e,t){const i=(0,o.getCoordsRelativeToElement)(window,e,t);if(this._charSizeService.hasValidSize)return i[0]=Math.min(Math.max(i[0],0),this._renderService.dimensions.css.canvas.width-1),i[1]=Math.min(Math.max(i[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(i[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(i[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(i[0]),y:Math.floor(i[1])}}};t.MouseService=a=s([r(0,n.IRenderService),r(1,n.ICharSizeService)],a)},3230:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RenderService=void 0;const n=i(3656),o=i(6193),a=i(5596),h=i(4725),c=i(8460),l=i(844),d=i(7226),_=i(2585);let u=t.RenderService=class extends l.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(e,t,i,s,r,h,_,u){if(super(),this._rowCount=e,this._charSizeService=s,this._renderer=this.register(new l.MutableDisposable),this._pausedResizeTask=new d.DebouncedIdleTask,this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new c.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new c.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new c.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new c.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new o.RenderDebouncer(_.window,((e,t)=>this._renderRows(e,t))),this.register(this._renderDebouncer),this._screenDprMonitor=new a.ScreenDprMonitor(_.window),this._screenDprMonitor.setListener((()=>this.handleDevicePixelRatioChange())),this.register(this._screenDprMonitor),this.register(h.onResize((()=>this._fullRefresh()))),this.register(h.buffers.onBufferActivate((()=>{var e;return null===(e=this._renderer.value)||void 0===e?void 0:e.clear()}))),this.register(i.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this.register(r.onDecorationRegistered((()=>this._fullRefresh()))),this.register(r.onDecorationRemoved((()=>this._fullRefresh()))),this.register(i.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio"],(()=>{this.clear(),this.handleResize(h.cols,h.rows),this._fullRefresh()}))),this.register(i.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(h.buffer.y,h.buffer.y,!0)))),this.register((0,n.addDisposableDomListener)(_.window,"resize",(()=>this.handleDevicePixelRatioChange()))),this.register(u.onChangeColors((()=>this._fullRefresh()))),"IntersectionObserver"in _.window){const e=new _.window.IntersectionObserver((e=>this._handleIntersectionChange(e[e.length-1])),{threshold:0});e.observe(t),this.register({dispose:()=>e.disconnect()})}}_handleIntersectionChange(e){this._isPaused=void 0===e.isIntersecting?0===e.intersectionRatio:!e.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,i=!1){this._isPaused?this._needsFullRefresh=!0:(i||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount))}_renderRows(e,t){this._renderer.value&&(e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0)}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value.onRequestRedraw((e=>this.refreshRows(e.start,e.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh()}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var e,t;this._renderer.value&&(null===(t=(e=this._renderer.value).clearTextureAtlas)||void 0===t||t.call(e),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value.handleResize(e,t))):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){var e;null===(e=this._renderer.value)||void 0===e||e.handleCharSizeChanged()}handleBlur(){var e;null===(e=this._renderer.value)||void 0===e||e.handleBlur()}handleFocus(){var e;null===(e=this._renderer.value)||void 0===e||e.handleFocus()}handleSelectionChanged(e,t,i){var s;this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=i,null===(s=this._renderer.value)||void 0===s||s.handleSelectionChanged(e,t,i)}handleCursorMove(){var e;null===(e=this._renderer.value)||void 0===e||e.handleCursorMove()}clear(){var e;null===(e=this._renderer.value)||void 0===e||e.clear()}};t.RenderService=u=s([r(2,_.IOptionsService),r(3,h.ICharSizeService),r(4,_.IDecorationService),r(5,_.IBufferService),r(6,h.ICoreBrowserService),r(7,h.IThemeService)],u)},9312:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionService=void 0;const n=i(9806),o=i(9504),a=i(456),h=i(4725),c=i(8460),l=i(844),d=i(6114),_=i(4841),u=i(511),f=i(2585),v=String.fromCharCode(160),p=new RegExp(v,"g");let g=t.SelectionService=class extends l.Disposable{constructor(e,t,i,s,r,n,o,h,d){super(),this._element=e,this._screenElement=t,this._linkifier=i,this._bufferService=s,this._coreService=r,this._mouseService=n,this._optionsService=o,this._renderService=h,this._coreBrowserService=d,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new u.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new c.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new c.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new c.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new c.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((e=>this._handleTrim(e))),this.register(this._bufferService.buffers.onBufferActivate((e=>this._handleBufferActivate(e)))),this.enable(),this._model=new a.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,l.toDisposable)((()=>{this._removeMouseDownListeners()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t||e[0]===t[0]&&e[1]===t[1])}get selectionText(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return"";const i=this._bufferService.buffer,s=[];if(3===this._activeSelectionMode){if(e[0]===t[0])return"";const r=e[0]e.replace(p," "))).join(d.isWindows?"\r\n":"\n")}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),d.isLinux&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:3===this._activeSelectionMode})}_isClickInSelection(e){const t=this._getMouseBufferCoords(e),i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!!(i&&s&&t)&&this._areCoordsInSelection(t,i,s)}isCellInSelection(e,t){const i=this._model.finalSelectionStart,s=this._model.finalSelectionEnd;return!(!i||!s)&&this._areCoordsInSelection([e,t],i,s)}_areCoordsInSelection(e,t,i){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){var i,s;const r=null===(s=null===(i=this._linkifier.currentLink)||void 0===i?void 0:i.link)||void 0===s?void 0:s.range;if(r)return this._model.selectionStart=[r.start.x-1,r.start.y-1],this._model.selectionStartLength=(0,_.getRangeLength)(r,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const n=this._getMouseBufferCoords(e);return!!n&&(this._selectWordAt(n,t),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){const t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=(0,n.getCoordsRelativeToElement)(this._coreBrowserService.window,e,this._screenElement)[1];const i=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=i?0:(t>i&&(t-=i),t=Math.min(Math.max(t,-50),50),t/=50,t/Math.abs(t)+Math.round(14*t))}shouldForceSelection(e){return d.isMac?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,(2!==e.button||!this.hasSelection)&&0===e.button){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):1===e.detail?this._handleSingleClick(e):2===e.detail?this._handleDoubleClick(e):3===e.detail&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&0===t.hasWidth(this._model.selectionStart[0])&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){const t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(d.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;const t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);2===this._activeSelectionMode?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const i=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(3!==this._activeSelectionMode&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){const t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&void 0!==t[0]&&void 0!==t[1]){const e=(0,o.moveToCellSequence)(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,i=!(!e||!t||e[0]===t[0]&&e[1]===t[1]);i?e&&t&&(this._oldSelectionStart&&this._oldSelectionEnd&&e[0]===this._oldSelectionStart[0]&&e[1]===this._oldSelectionStart[1]&&t[0]===this._oldSelectionEnd[0]&&t[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(e,t,i)):this._oldHasSelection&&this._fireOnSelectionChange(e,t,i)}_fireOnSelectionChange(e,t,i){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=i,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim((e=>this._handleTrim(e)))}_convertViewportColToCharacterIndex(e,t){let i=t;for(let s=0;t>=s;s++){const r=e.loadCell(s,this._workCell).getChars().length;0===this._workCell.getWidth()?i--:r>1&&t!==s&&(i+=r-1)}return i}setSelection(e,t,i){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=i,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,i=!0,s=!0){if(e[0]>=this._bufferService.cols)return;const r=this._bufferService.buffer,n=r.lines.get(e[1]);if(!n)return;const o=r.translateBufferLineToString(e[1],!1);let a=this._convertViewportColToCharacterIndex(n,e[0]),h=a;const c=e[0]-a;let l=0,d=0,_=0,u=0;if(" "===o.charAt(a)){for(;a>0&&" "===o.charAt(a-1);)a--;for(;h1&&(u+=s-1,h+=s-1);t>0&&a>0&&!this._isCharWordSeparator(n.loadCell(t-1,this._workCell));){n.loadCell(t-1,this._workCell);const e=this._workCell.getChars().length;0===this._workCell.getWidth()?(l++,t--):e>1&&(_+=e-1,a-=e-1),a--,t--}for(;i1&&(u+=e-1,h+=e-1),h++,i++}}h++;let f=a+c-l+_,v=Math.min(this._bufferService.cols,h-a+l+d-_-u);if(t||""!==o.slice(a,h).trim()){if(i&&0===f&&32!==n.getCodePoint(0)){const t=r.lines.get(e[1]-1);if(t&&n.isWrapped&&32!==t.getCodePoint(this._bufferService.cols-1)){const t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){const e=this._bufferService.cols-t.start;f-=e,v+=e}}}if(s&&f+v===this._bufferService.cols&&32!==n.getCodePoint(this._bufferService.cols-1)){const t=r.lines.get(e[1]+1);if((null==t?void 0:t.isWrapped)&&32!==t.getCodePoint(0)){const t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(v+=t.length)}}return{start:f,length:v}}}_selectWordAt(e,t){const i=this._getWordAt(e,t);if(i){for(;i.start<0;)i.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[i.start,e[1]],this._model.selectionStartLength=i.length}}_selectToWordAt(e){const t=this._getWordAt(e,!0);if(t){let i=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,i--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,i++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,i]}}_isCharWordSeparator(e){return 0!==e.getWidth()&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){const t=this._bufferService.buffer.getWrappedRangeForLine(e),i={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,_.getRangeLength)(i,this._bufferService.cols)}};t.SelectionService=g=s([r(3,f.IBufferService),r(4,f.ICoreService),r(5,h.IMouseService),r(6,f.IOptionsService),r(7,h.IRenderService),r(8,h.ICoreBrowserService)],g)},4725:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IThemeService=t.ICharacterJoinerService=t.ISelectionService=t.IRenderService=t.IMouseService=t.ICoreBrowserService=t.ICharSizeService=void 0;const s=i(8343);t.ICharSizeService=(0,s.createDecorator)("CharSizeService"),t.ICoreBrowserService=(0,s.createDecorator)("CoreBrowserService"),t.IMouseService=(0,s.createDecorator)("MouseService"),t.IRenderService=(0,s.createDecorator)("RenderService"),t.ISelectionService=(0,s.createDecorator)("SelectionService"),t.ICharacterJoinerService=(0,s.createDecorator)("CharacterJoinerService"),t.IThemeService=(0,s.createDecorator)("ThemeService")},6731:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ThemeService=t.DEFAULT_ANSI_COLORS=void 0;const n=i(7239),o=i(8055),a=i(8460),h=i(844),c=i(2585),l=o.css.toColor("#ffffff"),d=o.css.toColor("#000000"),_=o.css.toColor("#ffffff"),u=o.css.toColor("#000000"),f={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const e=[o.css.toColor("#2e3436"),o.css.toColor("#cc0000"),o.css.toColor("#4e9a06"),o.css.toColor("#c4a000"),o.css.toColor("#3465a4"),o.css.toColor("#75507b"),o.css.toColor("#06989a"),o.css.toColor("#d3d7cf"),o.css.toColor("#555753"),o.css.toColor("#ef2929"),o.css.toColor("#8ae234"),o.css.toColor("#fce94f"),o.css.toColor("#729fcf"),o.css.toColor("#ad7fa8"),o.css.toColor("#34e2e2"),o.css.toColor("#eeeeec")],t=[0,95,135,175,215,255];for(let i=0;i<216;i++){const s=t[i/36%6|0],r=t[i/6%6|0],n=t[i%6];e.push({css:o.channels.toCss(s,r,n),rgba:o.channels.toRgba(s,r,n)})}for(let t=0;t<24;t++){const i=8+10*t;e.push({css:o.channels.toCss(i,i,i),rgba:o.channels.toRgba(i,i,i)})}return e})());let v=t.ThemeService=class extends h.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new n.ColorContrastCache,this._halfContrastCache=new n.ColorContrastCache,this._onChangeColors=this.register(new a.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:l,background:d,cursor:_,cursorAccent:u,selectionForeground:void 0,selectionBackgroundTransparent:f,selectionBackgroundOpaque:o.color.blend(d,f),selectionInactiveBackgroundTransparent:f,selectionInactiveBackgroundOpaque:o.color.blend(d,f),ansi:t.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){const i=this._colors;if(i.foreground=p(e.foreground,l),i.background=p(e.background,d),i.cursor=p(e.cursor,_),i.cursorAccent=p(e.cursorAccent,u),i.selectionBackgroundTransparent=p(e.selectionBackground,f),i.selectionBackgroundOpaque=o.color.blend(i.background,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundTransparent=p(e.selectionInactiveBackground,i.selectionBackgroundTransparent),i.selectionInactiveBackgroundOpaque=o.color.blend(i.background,i.selectionInactiveBackgroundTransparent),i.selectionForeground=e.selectionForeground?p(e.selectionForeground,o.NULL_COLOR):void 0,i.selectionForeground===o.NULL_COLOR&&(i.selectionForeground=void 0),o.color.isOpaque(i.selectionBackgroundTransparent)){const e=.3;i.selectionBackgroundTransparent=o.color.opacity(i.selectionBackgroundTransparent,e)}if(o.color.isOpaque(i.selectionInactiveBackgroundTransparent)){const e=.3;i.selectionInactiveBackgroundTransparent=o.color.opacity(i.selectionInactiveBackgroundTransparent,e)}if(i.ansi=t.DEFAULT_ANSI_COLORS.slice(),i.ansi[0]=p(e.black,t.DEFAULT_ANSI_COLORS[0]),i.ansi[1]=p(e.red,t.DEFAULT_ANSI_COLORS[1]),i.ansi[2]=p(e.green,t.DEFAULT_ANSI_COLORS[2]),i.ansi[3]=p(e.yellow,t.DEFAULT_ANSI_COLORS[3]),i.ansi[4]=p(e.blue,t.DEFAULT_ANSI_COLORS[4]),i.ansi[5]=p(e.magenta,t.DEFAULT_ANSI_COLORS[5]),i.ansi[6]=p(e.cyan,t.DEFAULT_ANSI_COLORS[6]),i.ansi[7]=p(e.white,t.DEFAULT_ANSI_COLORS[7]),i.ansi[8]=p(e.brightBlack,t.DEFAULT_ANSI_COLORS[8]),i.ansi[9]=p(e.brightRed,t.DEFAULT_ANSI_COLORS[9]),i.ansi[10]=p(e.brightGreen,t.DEFAULT_ANSI_COLORS[10]),i.ansi[11]=p(e.brightYellow,t.DEFAULT_ANSI_COLORS[11]),i.ansi[12]=p(e.brightBlue,t.DEFAULT_ANSI_COLORS[12]),i.ansi[13]=p(e.brightMagenta,t.DEFAULT_ANSI_COLORS[13]),i.ansi[14]=p(e.brightCyan,t.DEFAULT_ANSI_COLORS[14]),i.ansi[15]=p(e.brightWhite,t.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){const s=Math.min(i.ansi.length-16,e.extendedAnsi.length);for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.CircularList=void 0;const s=i(8460),r=i(844);class n extends r.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this.register(new s.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new s.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new s.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;const t=new Array(e);for(let i=0;ithis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+i.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){const e=this._length+i.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=i.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,i){if(!(t<=0)){if(e<0||e>=this._length)throw new Error("start argument out of range");if(e+i<0)throw new Error("Cannot shift elements in list beyond index 0");if(i>0){for(let s=t-1;s>=0;s--)this.set(e+s+i,this.get(e+s));const s=e+t+i-this._length;if(s>0)for(this._length+=s;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let s=0;s{Object.defineProperty(t,"__esModule",{value:!0}),t.clone=void 0,t.clone=function e(t,i=5){if("object"!=typeof t)return t;const s=Array.isArray(t)?[]:{};for(const r in t)s[r]=i<=1?t[r]:t[r]&&e(t[r],i-1);return s}},8055:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.contrastRatio=t.toPaddedHex=t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0;const s=i(6114);let r=0,n=0,o=0,a=0;var h,c,l,d,_;function u(e){const t=e.toString(16);return t.length<2?"0"+t:t}function f(e,t){return e>>0}}(h||(t.channels=h={})),function(e){function t(e,t){return a=Math.round(255*t),[r,n,o]=_.toChannels(e.rgba),{css:h.toCss(r,n,o,a),rgba:h.toRgba(r,n,o,a)}}e.blend=function(e,t){if(a=(255&t.rgba)/255,1===a)return{css:t.css,rgba:t.rgba};const i=t.rgba>>24&255,s=t.rgba>>16&255,c=t.rgba>>8&255,l=e.rgba>>24&255,d=e.rgba>>16&255,_=e.rgba>>8&255;return r=l+Math.round((i-l)*a),n=d+Math.round((s-d)*a),o=_+Math.round((c-_)*a),{css:h.toCss(r,n,o),rgba:h.toRgba(r,n,o)}},e.isOpaque=function(e){return 255==(255&e.rgba)},e.ensureContrastRatio=function(e,t,i){const s=_.ensureContrastRatio(e.rgba,t.rgba,i);if(s)return _.toColor(s>>24&255,s>>16&255,s>>8&255)},e.opaque=function(e){const t=(255|e.rgba)>>>0;return[r,n,o]=_.toChannels(t),{css:h.toCss(r,n,o),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,i){return a=255&e.rgba,t(e,a*i/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(c||(t.color=c={})),function(e){let t,i;if(!s.isNode){const e=document.createElement("canvas");e.width=1,e.height=1;const s=e.getContext("2d",{willReadFrequently:!0});s&&(t=s,t.globalCompositeOperation="copy",i=t.createLinearGradient(0,0,1,1))}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return r=parseInt(e.slice(1,2).repeat(2),16),n=parseInt(e.slice(2,3).repeat(2),16),o=parseInt(e.slice(3,4).repeat(2),16),_.toColor(r,n,o);case 5:return r=parseInt(e.slice(1,2).repeat(2),16),n=parseInt(e.slice(2,3).repeat(2),16),o=parseInt(e.slice(3,4).repeat(2),16),a=parseInt(e.slice(4,5).repeat(2),16),_.toColor(r,n,o,a);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}const s=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(s)return r=parseInt(s[1]),n=parseInt(s[2]),o=parseInt(s[3]),a=Math.round(255*(void 0===s[5]?1:parseFloat(s[5]))),_.toColor(r,n,o,a);if(!t||!i)throw new Error("css.toColor: Unsupported css format");if(t.fillStyle=i,t.fillStyle=e,"string"!=typeof t.fillStyle)throw new Error("css.toColor: Unsupported css format");if(t.fillRect(0,0,1,1),[r,n,o,a]=t.getImageData(0,0,1,1).data,255!==a)throw new Error("css.toColor: Unsupported css format");return{rgba:h.toRgba(r,n,o,a),css:e}}}(l||(t.css=l={})),function(e){function t(e,t,i){const s=e/255,r=t/255,n=i/255;return.2126*(s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(d||(t.rgb=d={})),function(e){function t(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,h=t>>8&255,c=f(d.relativeLuminance2(o,a,h),d.relativeLuminance2(s,r,n));for(;c0||a>0||h>0);)o-=Math.max(0,Math.ceil(.1*o)),a-=Math.max(0,Math.ceil(.1*a)),h-=Math.max(0,Math.ceil(.1*h)),c=f(d.relativeLuminance2(o,a,h),d.relativeLuminance2(s,r,n));return(o<<24|a<<16|h<<8|255)>>>0}function i(e,t,i){const s=e>>24&255,r=e>>16&255,n=e>>8&255;let o=t>>24&255,a=t>>16&255,h=t>>8&255,c=f(d.relativeLuminance2(o,a,h),d.relativeLuminance2(s,r,n));for(;c>>0}e.ensureContrastRatio=function(e,s,r){const n=d.relativeLuminance(e>>8),o=d.relativeLuminance(s>>8);if(f(n,o)>8));if(af(n,d.relativeLuminance(t>>8))?o:t}return o}const a=i(e,s,r),h=f(n,d.relativeLuminance(a>>8));if(hf(n,d.relativeLuminance(i>>8))?a:i}return a}},e.reduceLuminance=t,e.increaseLuminance=i,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]},e.toColor=function(e,t,i,s){return{css:h.toCss(e,t,i,s),rgba:h.toRgba(e,t,i,s)}}}(_||(t.rgba=_={})),t.toPaddedHex=u,t.contrastRatio=f},8969:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreTerminal=void 0;const s=i(844),r=i(2585),n=i(4348),o=i(7866),a=i(744),h=i(7302),c=i(6975),l=i(8460),d=i(1753),_=i(1480),u=i(7994),f=i(9282),v=i(5435),p=i(5981),g=i(2660);let m=!1;class S extends s.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new l.EventEmitter),this._onScroll.event((e=>{var t;null===(t=this._onScrollApi)||void 0===t||t.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(const t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this.register(new s.MutableDisposable),this._onBinary=this.register(new l.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new l.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new l.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new l.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new l.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new l.EventEmitter),this._instantiationService=new n.InstantiationService,this.optionsService=this.register(new h.OptionsService(e)),this._instantiationService.setService(r.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(a.BufferService)),this._instantiationService.setService(r.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(o.LogService)),this._instantiationService.setService(r.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(c.CoreService)),this._instantiationService.setService(r.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(d.CoreMouseService)),this._instantiationService.setService(r.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(_.UnicodeService)),this._instantiationService.setService(r.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(u.CharsetService),this._instantiationService.setService(r.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(g.OscLinkService),this._instantiationService.setService(r.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new v.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,l.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,l.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,l.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,l.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((e=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new p.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this.register((0,l.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=r.LogLevelEnum.WARN&&!m&&(this._logService.warn("writeSync is unreliable and will be removed soon."),m=!0),this._writeBuffer.writeSync(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,a.MINIMUM_COLS),t=Math.max(t,a.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t,i){this._bufferService.scrollLines(e,t,i)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){const t=e-this._bufferService.buffer.ydisp;0!==t&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1;const t=this.optionsService.rawOptions.windowsPty;t&&void 0!==t.buildNumber&&void 0!==t.buildNumber?e=!!("conpty"===t.backend&&t.buildNumber<21376):this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const e=[];e.push(this.onLineFeed(f.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:"H"},(()=>((0,f.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,s.toDisposable)((()=>{for(const t of e)t.dispose()}))}}}t.CoreTerminal=S},8460:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.forwardEvent=t.EventEmitter=void 0,t.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=e=>(this._listeners.push(e),{dispose:()=>{if(!this._disposed)for(let t=0;tt.fire(e)))}},5435:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0;const n=i(2584),o=i(7116),a=i(2015),h=i(844),c=i(482),l=i(8437),d=i(8460),_=i(643),u=i(511),f=i(3734),v=i(2585),p=i(6242),g=i(6351),m=i(5941),S={"(":0,")":1,"*":2,"+":3,"-":1,".":2},C=131072;function b(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var y;!function(e){e[e.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",e[e.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"}(y||(t.WindowsOptionsReportType=y={}));let w=0;class E extends h.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,i,s,r,h,_,f,v=new a.EscapeSequenceParser){super(),this._bufferService=e,this._charsetService=t,this._coreService=i,this._logService=s,this._optionsService=r,this._oscLinkService=h,this._coreMouseService=_,this._unicodeService=f,this._parser=v,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new c.StringToUtf32,this._utf8Decoder=new c.Utf8ToUtf32,this._workCell=new u.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new d.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new d.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new d.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new d.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new d.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new d.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new d.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new d.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new d.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new d.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new d.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new d.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new k(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug("Unknown EXECUTE code: ",{code:e})})),this._parser.setOscHandlerFallback(((e,t,i)=>{this._logService.debug("Unknown OSC code: ",{identifier:e,action:t,data:i})})),this._parser.setDcsHandlerFallback(((e,t,i)=>{"HOOK"===t&&(i=i.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(e),action:t,payload:i})})),this._parser.setPrintHandler(((e,t,i)=>this.print(e,t,i))),this._parser.registerCsiHandler({final:"@"},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:"A"},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:"B"},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:"C"},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:"D"},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:"E"},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:"F"},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:"G"},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:"H"},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:"I"},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:"J"},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:"K"},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:"L"},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:"M"},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:"P"},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:"S"},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:"T"},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:"X"},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:"Z"},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:"a"},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:"b"},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:"c"},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:">",final:"c"},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:"d"},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:"e"},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:"f"},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:"g"},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:"h"},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:"l"},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:"m"},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:"n"},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:"r"},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:"s"},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:"t"},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:"u"},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(n.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(n.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(n.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(n.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(n.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(n.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(n.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(n.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(n.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(n.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new p.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new p.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new p.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new p.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new p.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new p.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new p.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new p.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new p.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new p.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new p.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new p.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const e in o.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:e},(()=>this.selectCharset("("+e))),this._parser.registerEscHandler({intermediates:")",final:e},(()=>this.selectCharset(")"+e))),this._parser.registerEscHandler({intermediates:"*",final:e},(()=>this.selectCharset("*"+e))),this._parser.registerEscHandler({intermediates:"+",final:e},(()=>this.selectCharset("+"+e))),this._parser.registerEscHandler({intermediates:"-",final:e},(()=>this.selectCharset("-"+e))),this._parser.registerEscHandler({intermediates:".",final:e},(()=>this.selectCharset("."+e))),this._parser.registerEscHandler({intermediates:"/",final:e},(()=>this.selectCharset("/"+e)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error("Parsing error: ",e),e))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new g.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,i,s){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=i,this._parseStack.position=s}_logSlowResolvingAsync(e){this._logService.logLevel<=v.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t("#SLOW_TIMEOUT")),5e3)))]).catch((e=>{if("#SLOW_TIMEOUT"!==e)throw e;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let i,s=this._activeBuffer.x,r=this._activeBuffer.y,n=0;const o=this._parseStack.paused;if(o){if(i=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(i),i;s=this._parseStack.cursorStartX,r=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>C&&(n=this._parseStack.position+C)}if(this._logService.logLevel<=v.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+("string"==typeof e?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join("")}"`),"string"==typeof e?e.split("").map((e=>e.charCodeAt(0))):e),this._parseBuffer.lengthC)for(let t=n;t0&&2===u.getWidth(this._activeBuffer.x-1)&&u.setCellFromCodePoint(this._activeBuffer.x-1,0,1,d.fg,d.bg,d.extended);for(let f=t;f=a)if(h){for(;this._activeBuffer.x=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),u=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)}else if(this._activeBuffer.x=a-1,2===r)continue;if(l&&(u.insertCells(this._activeBuffer.x,r,this._activeBuffer.getNullCell(d),d),2===u.getWidth(a-1)&&u.setCellFromCodePoint(a-1,_.NULL_CELL_CODE,_.NULL_CELL_WIDTH,d.fg,d.bg,d.extended)),u.setCellFromCodePoint(this._activeBuffer.x++,s,r,d.fg,d.bg,d.extended),r>0)for(;--r;)u.setCellFromCodePoint(this._activeBuffer.x++,0,0,d.fg,d.bg,d.extended)}else u.getWidth(this._activeBuffer.x-1)?u.addCodepointToCell(this._activeBuffer.x-1,s):u.addCodepointToCell(this._activeBuffer.x-2,s)}i-t>0&&(u.loadCell(this._activeBuffer.x-1,this._workCell),2===this._workCell.getWidth()||this._workCell.getCode()>65535?this._parser.precedingCodepoint=0:this._workCell.isCombined()?this._parser.precedingCodepoint=this._workCell.getChars().charCodeAt(0):this._parser.precedingCodepoint=this._workCell.content),this._activeBuffer.x0&&0===u.getWidth(this._activeBuffer.x)&&!u.hasContent(this._activeBuffer.x)&&u.setCellFromCodePoint(this._activeBuffer.x,0,1,d.fg,d.bg,d.extended),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return"t"!==e.final||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!b(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new g.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new p.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var e;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(0===this._activeBuffer.x&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&(null===(e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))||void 0===e?void 0:e.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){const t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){const t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){const t=e.params[0];return 0===t?delete this._activeBuffer.tabs[this._activeBuffer.x]:3===t&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){const t=e.params[0];return 1===t&&(this._curAttrData.bg|=536870912),2!==t&&0!==t||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,i,s=!1,r=!1){const n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.replaceCells(t,i,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData(),r),s&&(n.isWrapped=!1)}_resetBufferLine(e,t=!1){const i=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);i&&(i.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),i.isWrapped=!1)}eraseInDisplay(e,t=!1){let i;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(i=this._activeBuffer.y,this._dirtyRowTracker.markDirty(i),this._eraseInBufferLine(i++,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);i=this._bufferService.cols&&(this._activeBuffer.lines.get(i+1).isWrapped=!1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 2:for(i=this._bufferService.rows,this._dirtyRowTracker.markDirty(i-1);i--;)this._resetBufferLine(i,t);this._dirtyRowTracker.markDirty(0);break;case 3:const e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,0===this._activeBuffer.x,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(n.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(n.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(n.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(n.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(e.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(n.C0.ESC+"[>83;40003;0c")),!0}_is(e){return 0===(this._optionsService.rawOptions.termName+"").indexOf(e)}setMode(e){for(let t=0;te?1:2,u=e.params[0];return f=u,v=t?2===u?4:4===u?_(o.modes.insertMode):12===u?3:20===u?_(d.convertEol):0:1===u?_(i.applicationCursorKeys):3===u?d.windowOptions.setWinLines?80===h?2:132===h?1:0:0:6===u?_(i.origin):7===u?_(i.wraparound):8===u?3:9===u?_("X10"===s):12===u?_(d.cursorBlink):25===u?_(!o.isCursorHidden):45===u?_(i.reverseWraparound):66===u?_(i.applicationKeypad):67===u?4:1e3===u?_("VT200"===s):1002===u?_("DRAG"===s):1003===u?_("ANY"===s):1004===u?_(i.sendFocus):1005===u?4:1006===u?_("SGR"===r):1015===u?4:1016===u?_("SGR_PIXELS"===r):1048===u?1:47===u||1047===u||1049===u?_(c===l):2004===u?_(i.bracketedPasteMode):0,o.triggerDataEvent(`${n.C0.ESC}[${t?"":"?"}${f};${v}$y`),!0;var f,v}_updateAttrColor(e,t,i,s,r){return 2===t?(e|=50331648,e&=-16777216,e|=f.AttributeData.fromColorRGB([i,s,r])):5===t&&(e&=-50331904,e|=33554432|255&i),e}_extractColor(e,t,i){const s=[0,0,-1,0,0,0];let r=0,n=0;do{if(s[n+r]=e.params[t+n],e.hasSubParams(t+n)){const i=e.getSubParams(t+n);let o=0;do{5===s[1]&&(r=1),s[n+o+1+r]=i[o]}while(++o=2||2===s[1]&&n+r>=5)break;s[1]&&(r=1)}while(++n+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,0===e&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=l.DEFAULT_ATTR_DATA.fg,e.bg=l.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(1===e.length&&0===e.params[0])return this._processSGR0(this._curAttrData),!0;const t=e.length;let i;const s=this._curAttrData;for(let r=0;r=30&&i<=37?(s.fg&=-50331904,s.fg|=16777216|i-30):i>=40&&i<=47?(s.bg&=-50331904,s.bg|=16777216|i-40):i>=90&&i<=97?(s.fg&=-50331904,s.fg|=16777224|i-90):i>=100&&i<=107?(s.bg&=-50331904,s.bg|=16777224|i-100):0===i?this._processSGR0(s):1===i?s.fg|=134217728:3===i?s.bg|=67108864:4===i?(s.fg|=268435456,this._processUnderline(e.hasSubParams(r)?e.getSubParams(r)[0]:1,s)):5===i?s.fg|=536870912:7===i?s.fg|=67108864:8===i?s.fg|=1073741824:9===i?s.fg|=2147483648:2===i?s.bg|=134217728:21===i?this._processUnderline(2,s):22===i?(s.fg&=-134217729,s.bg&=-134217729):23===i?s.bg&=-67108865:24===i?(s.fg&=-268435457,this._processUnderline(0,s)):25===i?s.fg&=-536870913:27===i?s.fg&=-67108865:28===i?s.fg&=-1073741825:29===i?s.fg&=2147483647:39===i?(s.fg&=-67108864,s.fg|=16777215&l.DEFAULT_ATTR_DATA.fg):49===i?(s.bg&=-67108864,s.bg|=16777215&l.DEFAULT_ATTR_DATA.bg):38===i||48===i||58===i?r+=this._extractColor(e,r,s):53===i?s.bg|=1073741824:55===i?s.bg&=-1073741825:59===i?(s.extended=s.extended.clone(),s.extended.underlineColor=-1,s.updateExtended()):100===i?(s.fg&=-67108864,s.fg|=16777215&l.DEFAULT_ATTR_DATA.fg,s.bg&=-67108864,s.bg|=16777215&l.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",i);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${n.C0.ESC}[0n`);break;case 6:const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(6===e.params[0]){const e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${n.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){const t=e.params[0]||1;switch(t){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const i=t%2==1;return this._optionsService.options.cursorBlink=i,!0}setScrollRegion(e){const t=e.params[0]||1;let i;return(e.length<2||(i=e.params[1])>this._bufferService.rows||0===i)&&(i=this._bufferService.rows),i>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=i-1,this._setCursor(0,0)),!0}windowOptions(e){if(!b(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;const t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:2!==t&&this._onRequestWindowsOptionsReport.fire(y.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(y.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${n.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:0!==t&&2!==t||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),0!==t&&1!==t||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:0!==t&&2!==t||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),0!==t&&1!==t||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){const t=[],i=e.split(";");for(;i.length>1;){const e=i.shift(),s=i.shift();if(/^\d+$/.exec(e)){const i=parseInt(e);if(L(i))if("?"===s)t.push({type:0,index:i});else{const e=(0,m.parseColor)(s);e&&t.push({type:1,index:i,color:e})}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){const t=e.split(";");return!(t.length<2)&&(t[1]?this._createHyperlink(t[0],t[1]):!t[0]&&this._finishHyperlink())}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();const i=e.split(":");let s;const r=i.findIndex((e=>e.startsWith("id=")));return-1!==r&&(s=i[r].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:s,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){const i=e.split(";");for(let e=0;e=this._specialColors.length);++e,++t)if("?"===i[e])this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{const s=(0,m.parseColor)(i[e]);s&&this._onColor.fire([{type:1,index:this._specialColors[t],color:s}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;const t=[],i=e.split(";");for(let e=0;e=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=l.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=l.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){const e=new u.CellData;e.content=1<<22|"E".charCodeAt(0),e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${n.C0.ESC}${e}${n.C0.ESC}\\`),!0))('"q'===e?`P1$r${this._curAttrData.isProtected()?1:0}"q`:'"p'===e?'P1$r61;1"p':"r"===e?`P1$r${i.scrollTop+1};${i.scrollBottom+1}r`:"m"===e?"P1$r0m":" q"===e?`P1$r${{block:2,underline:4,bar:6}[s.cursorStyle]-(s.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=E;let k=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(w=e,e=t,t=w),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function L(e){return 0<=e&&e<256}k=s([r(0,v.IBufferService)],k)},844:(e,t)=>{function i(e){for(const t of e)t.dispose();e.length=0}Object.defineProperty(t,"__esModule",{value:!0}),t.getDisposeArrayDisposable=t.disposeArray=t.toDisposable=t.MutableDisposable=t.Disposable=void 0,t.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const e of this._disposables)e.dispose();this._disposables.length=0}register(e){return this._disposables.push(e),e}unregister(e){const t=this._disposables.indexOf(e);-1!==t&&this._disposables.splice(t,1)}},t.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||(null===(t=this._value)||void 0===t||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,null===(e=this._value)||void 0===e||e.dispose(),this._value=void 0}},t.toDisposable=function(e){return{dispose:e}},t.disposeArray=i,t.getDisposeArrayDisposable=function(e){return{dispose:()=>i(e)}}},1505:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class i{constructor(){this._data={}}set(e,t,i){this._data[e]||(this._data[e]={}),this._data[e][t]=i}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=i,t.FourKeyMap=class{constructor(){this._data=new i}set(e,t,s,r,n){this._data.get(e,t)||this._data.set(e,t,new i),this._data.get(e,t).set(s,r,n)}get(e,t,i,s){var r;return null===(r=this._data.get(e,t))||void 0===r?void 0:r.get(i,s)}clear(){this._data.clear()}}},6114:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.getSafariVersion=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.isNode="undefined"==typeof navigator;const i=t.isNode?"node":navigator.userAgent,s=t.isNode?"node":navigator.platform;t.isFirefox=i.includes("Firefox"),t.isLegacyEdge=i.includes("Edge"),t.isSafari=/^((?!chrome|android).)*safari/i.test(i),t.getSafariVersion=function(){if(!t.isSafari)return 0;const e=i.match(/Version\/(\d+)/);return null===e||e.length<2?0:parseInt(e[1])},t.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(s),t.isIpad="iPad"===s,t.isIphone="iPhone"===s,t.isWindows=["Windows","Win16","Win32","WinCE"].includes(s),t.isLinux=s.indexOf("Linux")>=0,t.isChromeOS=/\bCrOS\b/.test(i)},6106:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedList=void 0;let i=0;t.SortedList=class{constructor(e){this._getKey=e,this._array=[]}clear(){this._array.length=0}insert(e){0!==this._array.length?(i=this._search(this._getKey(e)),this._array.splice(i,0,e)):this._array.push(e)}delete(e){if(0===this._array.length)return!1;const t=this._getKey(e);if(void 0===t)return!1;if(i=this._search(t),-1===i)return!1;if(this._getKey(this._array[i])!==t)return!1;do{if(this._array[i]===e)return this._array.splice(i,1),!0}while(++i=this._array.length)&&this._getKey(this._array[i])===e))do{yield this._array[i]}while(++i=this._array.length)&&this._getKey(this._array[i])===e))do{t(this._array[i])}while(++i=t;){let s=t+i>>1;const r=this._getKey(this._array[s]);if(r>e)i=s-1;else{if(!(r0&&this._getKey(this._array[s-1])===e;)s--;return s}t=s+1}}return t}}},7226:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;const s=i(6114);class r{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ir)return s-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(s-t))}ms`),void this._start();s=r}this.clear()}}class n extends r{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){const t=Date.now()+e;return{timeRemaining:()=>Math.max(0,t-Date.now())}}}t.PriorityTaskQueue=n,t.IdleTaskQueue=!s.isNode&&"requestIdleCallback"in window?class extends r{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:n,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},9282:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateWindowsModeWrappedState=void 0;const s=i(643);t.updateWindowsModeWrappedState=function(e){const t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1),i=null==t?void 0:t.get(e.cols-1),r=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);r&&i&&(r.isWrapped=i[s.CHAR_DATA_CODE_INDEX]!==s.NULL_CELL_CODE&&i[s.CHAR_DATA_CODE_INDEX]!==s.WHITESPACE_CELL_CODE)}},3734:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class i{constructor(){this.fg=0,this.bg=0,this.extended=new s}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){const e=new i;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&0!==this.extended.underlineStyle?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return 50331648==(50331648&this.fg)}isBgRGB(){return 50331648==(50331648&this.bg)}isFgPalette(){return 16777216==(50331648&this.fg)||33554432==(50331648&this.fg)}isBgPalette(){return 16777216==(50331648&this.bg)||33554432==(50331648&this.bg)}isFgDefault(){return 0==(50331648&this.fg)}isBgDefault(){return 0==(50331648&this.bg)}isAttributeDefault(){return 0===this.fg&&0===this.bg}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?50331648==(50331648&this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?16777216==(50331648&this.extended.underlineColor)||33554432==(50331648&this.extended.underlineColor):this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?0==(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}}t.AttributeData=i;class s{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new s(this._ext,this._urlId)}isEmpty(){return 0===this.underlineStyle&&0===this._urlId}}t.ExtendedAttrs=s},9092:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;const s=i(6349),r=i(7226),n=i(3734),o=i(8437),a=i(4634),h=i(511),c=i(643),l=i(4863),d=i(7116);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,i){this._hasScrollback=e,this._optionsService=t,this._bufferService=i,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=h.CellData.fromCharData([0,c.NULL_CELL_CHAR,c.NULL_CELL_WIDTH,c.NULL_CELL_CODE]),this._whitespaceCell=h.CellData.fromCharData([0,c.WHITESPACE_CELL_CHAR,c.WHITESPACE_CELL_WIDTH,c.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new r.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new n.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new n.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const e=this.ybase+this.y-this.ydisp;return e>=0&&et.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:i}fillViewportRows(e){if(0===this.lines.length){void 0===e&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new s.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){const i=this.getNullCell(o.DEFAULT_ATTR_DATA);let s=0;const r=this._getCorrectBufferLength(t);if(r>this.lines.maxLength&&(this.lines.maxLength=r),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+n+1?(this.ybase--,n++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,i)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(r0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=r}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),n&&(this.y+=n),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){const e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&"conpty"===e.backend&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){const i=(0,a.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA));if(i.length>0){const s=(0,a.reflowLargerCreateNewLayout)(this.lines,i);(0,a.reflowLargerApplyNewLayout)(this.lines,s.layout),this._reflowLargerAdjustViewport(e,t,s.countRemoved)}}_reflowLargerAdjustViewport(e,t,i){const s=this.getNullCell(o.DEFAULT_ATTR_DATA);let r=i;for(;r-- >0;)0===this.ybase?(this.y>0&&this.y--,this.lines.length=0;n--){let h=this.lines.get(n);if(!h||!h.isWrapped&&h.getTrimmedLength()<=e)continue;const c=[h];for(;h.isWrapped&&n>0;)h=this.lines.get(--n),c.unshift(h);const l=this.ybase+this.y;if(l>=n&&l0&&(s.push({start:n+c.length+r,newLines:v}),r+=v.length),c.push(...v);let p=_.length-1,g=_[p];0===g&&(p--,g=_[p]);let m=c.length-u-1,S=d;for(;m>=0;){const e=Math.min(S,g);if(void 0===c[p])break;if(c[p].copyCellsFrom(c[m],S-e,g-e,e,!0),g-=e,0===g&&(p--,g=_[p]),S-=e,0===S){m--;const e=Math.max(m,0);S=(0,a.getWrappedLineTrimmedLength)(c,e,this._cols)}}for(let t=0;t0;)0===this.ybase?this.y0){const e=[],t=[];for(let e=0;e=0;c--)if(a&&a.start>n+h){for(let e=a.newLines.length-1;e>=0;e--)this.lines.set(c--,a.newLines[e]);c++,e.push({index:n+1,amount:a.newLines.length}),h+=a.newLines.length,a=s[++o]}else this.lines.set(c,t[n--]);let c=0;for(let t=e.length-1;t>=0;t--)e[t].index+=c,this.lines.onInsertEmitter.fire(e[t]),c+=e[t].amount;const l=Math.max(0,i+r-this.lines.maxLength);l>0&&this.lines.onTrimEmitter.fire(l)}}translateBufferLineToString(e,t,i=0,s){const r=this.lines.get(e);return r?r.translateToString(t,i,s):""}getWrappedRangeForLine(e){let t=e,i=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;i+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(null==e&&(e=this.x);!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},8437:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;const s=i(3734),r=i(511),n=i(643),o=i(482);t.DEFAULT_ATTR_DATA=Object.freeze(new s.AttributeData);let a=0;class h{constructor(e,t,i=!1){this.isWrapped=i,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);const s=t||r.CellData.fromCharData([0,n.NULL_CELL_CHAR,n.NULL_CELL_WIDTH,n.NULL_CELL_CODE]);for(let t=0;t>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):i]}set(e,t){this._data[3*e+1]=t[n.CHAR_DATA_ATTR_INDEX],t[n.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[n.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[n.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){const t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):""}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return a=3*e,t.content=this._data[a+0],t.fg=this._data[a+1],t.bg=this._data[a+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodePoint(e,t,i,s,r,n){268435456&r&&(this._extendedAttrs[e]=n),this._data[3*e+0]=t|i<<22,this._data[3*e+1]=s,this._data[3*e+2]=r}addCodepointToCell(e,t){let i=this._data[3*e+0];2097152&i?this._combined[e]+=(0,o.stringFromCodePoint)(t):(2097151&i?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&i)+(0,o.stringFromCodePoint)(t),i&=-2097152,i|=2097152):i=t|1<<22,this._data[3*e+0]=i)}insertCells(e,t,i,n){if((e%=this.length)&&2===this.getWidth(e-1)&&this.setCellFromCodePoint(e-1,0,1,(null==n?void 0:n.fg)||0,(null==n?void 0:n.bg)||0,(null==n?void 0:n.extended)||new s.ExtendedAttrs),t=0;--i)this.setCell(e+t+i,this.loadCell(e+i,s));for(let s=0;sthis.length){if(this._data.buffer.byteLength>=4*i)this._data=new Uint32Array(this._data.buffer,0,i);else{const e=new Uint32Array(i);e.set(this._data),this._data=e}for(let i=this.length;i=e&&delete this._combined[s]}const s=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[i]}}return this.length=e,4*i*2=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,i,s,r){const n=e._data;if(r)for(let r=s-1;r>=0;r--){for(let e=0;e<3;e++)this._data[3*(i+r)+e]=n[3*(t+r)+e];268435456&n[3*(t+r)+2]&&(this._extendedAttrs[i+r]=e._extendedAttrs[t+r])}else for(let r=0;r=t&&(this._combined[r-t+i]=e._combined[r])}}translateToString(e=!1,t=0,i=this.length){e&&(i=Math.min(i,this.getTrimmedLength()));let s="";for(;t>22||1}return s}}t.BufferLine=h},4841:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRangeLength=void 0,t.getRangeLength=function(e,t){if(e.start.y>e.end.y)throw new Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}},4634:(e,t)=>{function i(e,t,i){if(t===e.length-1)return e[t].getTrimmedLength();const s=!e[t].hasContent(i-1)&&1===e[t].getWidth(i-1),r=2===e[t+1].getWidth(0);return s&&r?i-1:i}Object.defineProperty(t,"__esModule",{value:!0}),t.getWrappedLineTrimmedLength=t.reflowSmallerGetNewLineLengths=t.reflowLargerApplyNewLayout=t.reflowLargerCreateNewLayout=t.reflowLargerGetLinesToRemove=void 0,t.reflowLargerGetLinesToRemove=function(e,t,s,r,n){const o=[];for(let a=0;a=a&&r0&&(e>d||0===l[e].getTrimmedLength());e--)v++;v>0&&(o.push(a+l.length-v),o.push(v)),a+=l.length-1}return o},t.reflowLargerCreateNewLayout=function(e,t){const i=[];let s=0,r=t[s],n=0;for(let o=0;oi(e,r,t))).reduce(((e,t)=>e+t));let o=0,a=0,h=0;for(;hc&&(o-=c,a++);const l=2===e[a].getWidth(o-1);l&&o--;const d=l?s-1:s;r.push(d),h+=d}return r},t.getWrappedLineTrimmedLength=i},5295:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferSet=void 0;const s=i(8460),r=i(844),n=i(9092);class o extends r.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this.register(new s.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new n.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new n.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},511:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CellData=void 0;const s=i(482),r=i(643),n=i(3734);class o extends n.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new n.ExtendedAttrs,this.combinedData=""}static fromCharData(e){const t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,s.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[r.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[r.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(2===e[r.CHAR_DATA_CHAR_INDEX].length){const i=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=i&&i<=56319){const s=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=s&&s<=57343?this.content=1024*(i-55296)+s-56320+65536|e[r.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[r.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[r.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[r.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},643:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=256|t.DEFAULT_COLOR<<9,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR="",t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=" ",t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},4863:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Marker=void 0;const s=i(8460),r=i(844);class n{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=n._nextId++,this._onDispose=this.register(new s.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,r.disposeArray)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=n,n._nextId=1},7116:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"␤",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},t.CHARSETS.A={"#":"£"},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},t.CHARSETS.C=t.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},t.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},t.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},t.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},t.CHARSETS.E=t.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},t.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},t.CHARSETS.H=t.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},t.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(e,t)=>{var i,s,r;Object.defineProperty(t,"__esModule",{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL="\0",e.SOH="",e.STX="",e.ETX="",e.EOT="",e.ENQ="",e.ACK="",e.BEL="",e.BS="\b",e.HT="\t",e.LF="\n",e.VT="\v",e.FF="\f",e.CR="\r",e.SO="",e.SI="",e.DLE="",e.DC1="",e.DC2="",e.DC3="",e.DC4="",e.NAK="",e.SYN="",e.ETB="",e.CAN="",e.EM="",e.SUB="",e.ESC="",e.FS="",e.GS="",e.RS="",e.US="",e.SP=" ",e.DEL=""}(i||(t.C0=i={})),function(e){e.PAD="€",e.HOP="",e.BPH="‚",e.NBH="ƒ",e.IND="„",e.NEL="…",e.SSA="†",e.ESA="‡",e.HTS="ˆ",e.HTJ="‰",e.VTS="Š",e.PLD="‹",e.PLU="Œ",e.RI="",e.SS2="Ž",e.SS3="",e.DCS="",e.PU1="‘",e.PU2="’",e.STS="“",e.CCH="”",e.MW="•",e.SPA="–",e.EPA="—",e.SOS="˜",e.SGCI="™",e.SCI="š",e.CSI="›",e.ST="œ",e.OSC="",e.PM="ž",e.APC="Ÿ"}(s||(t.C1=s={})),function(e){e.ST=`${i.ESC}\\`}(r||(t.C1_ESCAPED=r={}))},7399:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateKeyboardEvent=void 0;const s=i(2584),r={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};t.evaluateKeyboardEvent=function(e,t,i,n){const o={type:0,cancel:!1,key:void 0},a=(e.shiftKey?1:0)|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:"UIKeyInputUpArrow"===e.key?o.key=t?s.C0.ESC+"OA":s.C0.ESC+"[A":"UIKeyInputLeftArrow"===e.key?o.key=t?s.C0.ESC+"OD":s.C0.ESC+"[D":"UIKeyInputRightArrow"===e.key?o.key=t?s.C0.ESC+"OC":s.C0.ESC+"[C":"UIKeyInputDownArrow"===e.key&&(o.key=t?s.C0.ESC+"OB":s.C0.ESC+"[B");break;case 8:if(e.altKey){o.key=s.C0.ESC+s.C0.DEL;break}o.key=s.C0.DEL;break;case 9:if(e.shiftKey){o.key=s.C0.ESC+"[Z";break}o.key=s.C0.HT,o.cancel=!0;break;case 13:o.key=e.altKey?s.C0.ESC+s.C0.CR:s.C0.CR,o.cancel=!0;break;case 27:o.key=s.C0.ESC,e.altKey&&(o.key=s.C0.ESC+s.C0.ESC),o.cancel=!0;break;case 37:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"D",o.key===s.C0.ESC+"[1;3D"&&(o.key=s.C0.ESC+(i?"b":"[1;5D"))):o.key=t?s.C0.ESC+"OD":s.C0.ESC+"[D";break;case 39:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"C",o.key===s.C0.ESC+"[1;3C"&&(o.key=s.C0.ESC+(i?"f":"[1;5C"))):o.key=t?s.C0.ESC+"OC":s.C0.ESC+"[C";break;case 38:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"A",i||o.key!==s.C0.ESC+"[1;3A"||(o.key=s.C0.ESC+"[1;5A")):o.key=t?s.C0.ESC+"OA":s.C0.ESC+"[A";break;case 40:if(e.metaKey)break;a?(o.key=s.C0.ESC+"[1;"+(a+1)+"B",i||o.key!==s.C0.ESC+"[1;3B"||(o.key=s.C0.ESC+"[1;5B")):o.key=t?s.C0.ESC+"OB":s.C0.ESC+"[B";break;case 45:e.shiftKey||e.ctrlKey||(o.key=s.C0.ESC+"[2~");break;case 46:o.key=a?s.C0.ESC+"[3;"+(a+1)+"~":s.C0.ESC+"[3~";break;case 36:o.key=a?s.C0.ESC+"[1;"+(a+1)+"H":t?s.C0.ESC+"OH":s.C0.ESC+"[H";break;case 35:o.key=a?s.C0.ESC+"[1;"+(a+1)+"F":t?s.C0.ESC+"OF":s.C0.ESC+"[F";break;case 33:e.shiftKey?o.type=2:e.ctrlKey?o.key=s.C0.ESC+"[5;"+(a+1)+"~":o.key=s.C0.ESC+"[5~";break;case 34:e.shiftKey?o.type=3:e.ctrlKey?o.key=s.C0.ESC+"[6;"+(a+1)+"~":o.key=s.C0.ESC+"[6~";break;case 112:o.key=a?s.C0.ESC+"[1;"+(a+1)+"P":s.C0.ESC+"OP";break;case 113:o.key=a?s.C0.ESC+"[1;"+(a+1)+"Q":s.C0.ESC+"OQ";break;case 114:o.key=a?s.C0.ESC+"[1;"+(a+1)+"R":s.C0.ESC+"OR";break;case 115:o.key=a?s.C0.ESC+"[1;"+(a+1)+"S":s.C0.ESC+"OS";break;case 116:o.key=a?s.C0.ESC+"[15;"+(a+1)+"~":s.C0.ESC+"[15~";break;case 117:o.key=a?s.C0.ESC+"[17;"+(a+1)+"~":s.C0.ESC+"[17~";break;case 118:o.key=a?s.C0.ESC+"[18;"+(a+1)+"~":s.C0.ESC+"[18~";break;case 119:o.key=a?s.C0.ESC+"[19;"+(a+1)+"~":s.C0.ESC+"[19~";break;case 120:o.key=a?s.C0.ESC+"[20;"+(a+1)+"~":s.C0.ESC+"[20~";break;case 121:o.key=a?s.C0.ESC+"[21;"+(a+1)+"~":s.C0.ESC+"[21~";break;case 122:o.key=a?s.C0.ESC+"[23;"+(a+1)+"~":s.C0.ESC+"[23~";break;case 123:o.key=a?s.C0.ESC+"[24;"+(a+1)+"~":s.C0.ESC+"[24~";break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)if(i&&!n||!e.altKey||e.metaKey)!i||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&1===e.key.length?o.key=e.key:e.key&&e.ctrlKey&&("_"===e.key&&(o.key=s.C0.US),"@"===e.key&&(o.key=s.C0.NUL)):65===e.keyCode&&(o.type=1);else{const t=r[e.keyCode],i=null==t?void 0:t[e.shiftKey?1:0];if(i)o.key=s.C0.ESC+i;else if(e.keyCode>=65&&e.keyCode<=90){const t=e.ctrlKey?e.keyCode-64:e.keyCode+32;let i=String.fromCharCode(t);e.shiftKey&&(i=i.toUpperCase()),o.key=s.C0.ESC+i}else if(32===e.keyCode)o.key=s.C0.ESC+(e.ctrlKey?s.C0.NUL:" ");else if("Dead"===e.key&&e.code.startsWith("Key")){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),o.key=s.C0.ESC+t,o.cancel=!0}}else e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):32===e.keyCode?o.key=s.C0.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):56===e.keyCode?o.key=s.C0.DEL:219===e.keyCode?o.key=s.C0.ESC:220===e.keyCode?o.key=s.C0.FS:221===e.keyCode&&(o.key=s.C0.GS)}return o}},482:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=t.utf32ToString=t.stringFromCodePoint=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,i=e.length){let s="";for(let r=t;r65535?(t-=65536,s+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):s+=String.fromCharCode(t)}return s},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){const i=e.length;if(!i)return 0;let s=0,r=0;if(this._interim){const i=e.charCodeAt(r++);56320<=i&&i<=57343?t[s++]=1024*(this._interim-55296)+i-56320+65536:(t[s++]=this._interim,t[s++]=i),this._interim=0}for(let n=r;n=i)return this._interim=r,s;const o=e.charCodeAt(n);56320<=o&&o<=57343?t[s++]=1024*(r-55296)+o-56320+65536:(t[s++]=r,t[s++]=o)}else 65279!==r&&(t[s++]=r)}return s}},t.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){const i=e.length;if(!i)return 0;let s,r,n,o,a=0,h=0,c=0;if(this.interim[0]){let s=!1,r=this.interim[0];r&=192==(224&r)?31:224==(240&r)?15:7;let n,o=0;for(;(n=63&this.interim[++o])&&o<4;)r<<=6,r|=n;const h=192==(224&this.interim[0])?2:224==(240&this.interim[0])?3:4,l=h-o;for(;c=i)return 0;if(n=e[c++],128!=(192&n)){c--,s=!0;break}this.interim[o++]=n,r<<=6,r|=63&n}s||(2===h?r<128?c--:t[a++]=r:3===h?r<2048||r>=55296&&r<=57343||65279===r||(t[a++]=r):r<65536||r>1114111||(t[a++]=r)),this.interim.fill(0)}const l=i-4;let d=c;for(;d=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(h=(31&s)<<6|63&r,h<128){d--;continue}t[a++]=h}else if(224==(240&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(h=(15&s)<<12|(63&r)<<6|63&n,h<2048||h>=55296&&h<=57343||65279===h)continue;t[a++]=h}else if(240==(248&s)){if(d>=i)return this.interim[0]=s,a;if(r=e[d++],128!=(192&r)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,a;if(n=e[d++],128!=(192&n)){d--;continue}if(d>=i)return this.interim[0]=s,this.interim[1]=r,this.interim[2]=n,a;if(o=e[d++],128!=(192&o)){d--;continue}if(h=(7&s)<<18|(63&r)<<12|(63&n)<<6|63&o,h<65536||h>1114111)continue;t[a++]=h}}return a}}},225:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeV6=void 0;const i=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],s=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let r;t.UnicodeV6=class{constructor(){if(this.version="6",!r){r=new Uint8Array(65536),r.fill(1),r[0]=0,r.fill(0,1,32),r.fill(0,127,160),r.fill(2,4352,4448),r[9001]=2,r[9002]=2,r.fill(2,11904,42192),r[12351]=1,r.fill(2,44032,55204),r.fill(2,63744,64256),r.fill(2,65040,65050),r.fill(2,65072,65136),r.fill(2,65280,65377),r.fill(2,65504,65511);for(let e=0;et[r][1])return!1;for(;r>=s;)if(i=s+r>>1,e>t[i][1])s=i+1;else{if(!(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}}},5981:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteBuffer=void 0;const s=i(8460),r=i(844);class n extends r.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new s.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(void 0!==t&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let i;for(this._isSyncWriting=!0;i=this._writeBuffer.shift();){this._action(i);const e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){const i=e||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const e=this._writeBuffer[this._bufferOffset],s=this._action(e,t);if(s){const e=e=>Date.now()-i>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(i,e);return void s.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e)}const r=this._callbacks[this._bufferOffset];if(r&&r(),this._bufferOffset++,this._pendingData-=e.length,Date.now()-i>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=n},5941:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toRgbString=t.parseColor=void 0;const i=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,s=/^[\da-f]+$/;function r(e,t){const i=e.toString(16),s=i.length<2?"0"+i:i;switch(t){case 4:return i[0];case 8:return s;case 12:return(s+s).slice(0,3);default:return s+s}}t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(0===t.indexOf("rgb:")){t=t.slice(4);const e=i.exec(t);if(e){const t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(0===t.indexOf("#")&&(t=t.slice(1),s.exec(t)&&[3,6,9,12].includes(t.length))){const e=t.length/3,i=[0,0,0];for(let s=0;s<3;++s){const r=parseInt(t.slice(e*s,e*s+e),16);i[s]=1===e?r<<4:2===e?r:3===e?r>>4:r>>8}return i}},t.toRgbString=function(e,t=16){const[i,s,n]=e;return`rgb:${r(i,t)}/${r(s,t)}/${r(n,t)}`}},5770:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},6351:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DcsHandler=t.DcsParser=void 0;const s=i(482),r=i(8742),n=i(5770),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,"HOOK",t)}put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._ident,"PUT",(0,s.utf32ToString)(e,t,i))}unhook(e,t=!0){if(this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].unhook(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].unhook(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._ident,"UNHOOK",e);this._active=o,this._ident=0}};const a=new r.Params;a.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data="",this._params=a,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():a,this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,s.utf32ToString)(e,t,i),this._data.length>n.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=a,this._data="",this._hitLimit=!1,e)));return this._params=a,this._data="",this._hitLimit=!1,t}}},2015:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;const s=i(844),r=i(8742),n=i(6242),o=i(6351);class a{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,i,s){this.table[t<<8|e]=i<<4|s}addMany(e,t,i,s){for(let r=0;rt)),i=(e,i)=>t.slice(e,i),s=i(32,127),r=i(0,24);r.push(25),r.push.apply(r,i(28,32));const n=i(0,14);let o;for(o in e.setDefault(1,0),e.addMany(s,0,2,0),n)e.addMany([24,26,153,154],o,3,0),e.addMany(i(128,144),o,3,0),e.addMany(i(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(r,0,3,0),e.addMany(r,1,3,1),e.add(127,1,0,1),e.addMany(r,8,0,8),e.addMany(r,3,3,3),e.add(127,3,0,3),e.addMany(r,4,3,4),e.add(127,4,0,4),e.addMany(r,6,3,6),e.addMany(r,5,3,5),e.add(127,5,0,5),e.addMany(r,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(s,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(i(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(s,7,0,7),e.addMany(r,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(i(64,127),3,7,0),e.addMany(i(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(i(48,60),4,8,4),e.addMany(i(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(i(32,64),6,0,6),e.add(127,6,0,6),e.addMany(i(64,127),6,0,0),e.addMany(i(32,48),3,9,5),e.addMany(i(32,48),5,9,5),e.addMany(i(48,64),5,0,6),e.addMany(i(64,127),5,7,0),e.addMany(i(32,48),4,9,5),e.addMany(i(32,48),1,9,2),e.addMany(i(32,48),2,9,2),e.addMany(i(48,127),2,10,0),e.addMany(i(48,80),1,10,0),e.addMany(i(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(i(96,127),1,10,0),e.add(80,1,11,9),e.addMany(r,9,0,9),e.add(127,9,0,9),e.addMany(i(28,32),9,0,9),e.addMany(i(32,48),9,9,12),e.addMany(i(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(r,11,0,11),e.addMany(i(32,128),11,0,11),e.addMany(i(28,32),11,0,11),e.addMany(r,10,0,10),e.add(127,10,0,10),e.addMany(i(28,32),10,0,10),e.addMany(i(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(i(32,48),10,9,12),e.addMany(r,12,0,12),e.add(127,12,0,12),e.addMany(i(28,32),12,0,12),e.addMany(i(32,48),12,9,12),e.addMany(i(48,64),12,0,11),e.addMany(i(64,127),12,12,13),e.addMany(i(64,127),10,12,13),e.addMany(i(64,127),9,12,13),e.addMany(r,13,13,13),e.addMany(s,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(h,0,2,0),e.add(h,8,5,8),e.add(h,6,0,6),e.add(h,11,0,11),e.add(h,13,13,13),e}();class c extends s.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new r.Params,this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,this._printHandlerFb=(e,t,i)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,s.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new n.OscParser),this._dcsParser=this.register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(e,t=[64,126]){let i=0;if(e.prefix){if(e.prefix.length>1)throw new Error("only one byte as prefix supported");if(i=e.prefix.charCodeAt(0),i&&60>i||i>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(e.intermediates){if(e.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let t=0;ts||s>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");i<<=8,i|=s}}if(1!==e.final.length)throw new Error("final must be a single byte");const s=e.final.charCodeAt(0);if(t[0]>s||s>t[1])throw new Error(`final must be in range ${t[0]} .. ${t[1]}`);return i<<=8,i|=s,i}identToString(e){const t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join("")}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){const i=this._identifier(e,[48,126]);void 0===this._escHandlers[i]&&(this._escHandlers[i]=[]);const s=this._escHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){const i=this._identifier(e);void 0===this._csiHandlers[i]&&(this._csiHandlers[i]=[]);const s=this._csiHandlers[i];return s.push(t),{dispose:()=>{const e=s.indexOf(t);-1!==e&&s.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0,0!==this._parseStack.state&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,i,s,r){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=i,this._parseStack.transition=s,this._parseStack.chunkPos=r}parse(e,t,i){let s,r=0,n=0,o=0;if(this._parseStack.state)if(2===this._parseStack.state)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(void 0===i||1===this._parseStack.state)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const t=this._parseStack.handlers;let n=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](this._params),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 4:if(!1===i&&n>-1)for(;n>=0&&(s=t[n](),!0!==s);n--)if(s instanceof Promise)return this._parseStack.handlerPos=n,s;this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],s=this._dcsParser.unhook(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],s=this._oscParser.end(24!==r&&26!==r,i),s)return s;27===r&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingCodepoint=0,this.currentState=15&this._parseStack.transition}for(let i=o;i>4){case 2:for(let s=i+1;;++s){if(s>=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=t||(r=e[s])<32||r>126&&r=0&&(s=o[a](this._params),!0!==s);a--)if(s instanceof Promise)return this._preserveStack(3,o,a,n,i),s;a<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingCodepoint=0;break;case 8:do{switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}}while(++i47&&r<60);i--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:const c=this._escHandlers[this._collect<<8|r];let l=c?c.length-1:-1;for(;l>=0&&(s=c[l](),!0!==s);l--)if(s instanceof Promise)return this._preserveStack(4,c,l,n,i),s;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingCodepoint=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let s=i+1;;++s)if(s>=t||24===(r=e[s])||26===r||27===r||r>127&&r=t||(r=e[s])<32||r>127&&r{Object.defineProperty(t,"__esModule",{value:!0}),t.OscHandler=t.OscParser=void 0;const s=i(5770),r=i(482),n=[];t.OscParser=class{constructor(){this._state=0,this._active=n,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){void 0===this._handlers[e]&&(this._handlers[e]=[]);const i=this._handlers[e];return i.push(t),{dispose:()=>{const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=n}reset(){if(2===this._state)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=n,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||n,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,"START")}_put(e,t,i){if(this._active.length)for(let s=this._active.length-1;s>=0;s--)this._active[s].put(e,t,i);else this._handlerFb(this._id,"PUT",(0,r.utf32ToString)(e,t,i))}start(){this.reset(),this._state=1}put(e,t,i){if(3!==this._state){if(1===this._state)for(;t0&&this._put(e,t,i)}}end(e,t=!0){if(0!==this._state){if(3!==this._state)if(1===this._state&&this._start(),this._active.length){let i=!1,s=this._active.length-1,r=!1;if(this._stack.paused&&(s=this._stack.loopPosition-1,i=t,r=this._stack.fallThrough,this._stack.paused=!1),!r&&!1===i){for(;s>=0&&(i=this._active[s].end(e),!0!==i);s--)if(i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!1,i;s--}for(;s>=0;s--)if(i=this._active[s].end(!1),i instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=s,this._stack.fallThrough=!0,i}else this._handlerFb(this._id,"END",e);this._active=n,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(e,t,i){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,i),this._data.length>s.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data="",this._hitLimit=!1,e)));return this._data="",this._hitLimit=!1,t}}},8742:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Params=void 0;const i=2147483647;class s{static fromArray(e){const t=new s;if(!e.length)return t;for(let i=Array.isArray(e[0])?1:0;i256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const e=new s(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){const e=[];for(let t=0;t>8,s=255&this._subParamsIdx[t];s-i>0&&e.push(Array.prototype.slice.call(this._subParams,i,s))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>i?i:e}}addSubParam(e){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=e>i?i:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){const t=this._subParamsIdx[e]>>8,i=255&this._subParamsIdx[e];return i-t>0?this._subParams.subarray(t,i):null}getSubParamsAll(){const e={};for(let t=0;t>8,s=255&this._subParamsIdx[t];s-i>0&&(e[t]=this._subParams.slice(i,s))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const s=this._digitIsSub?this._subParams:this.params,r=s[t-1];s[t-1]=~r?Math.min(10*r+e,i):e}}t.Params=s},5741:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){const i={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(i),t.dispose=()=>this._wrappedAddonDispose(i),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferApiView=void 0;const s=i(3785),r=i(511);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){const t=this._buffer.lines.get(e);if(t)return new s.BufferLineApiView(t)}getNullCell(){return new r.CellData}}},3785:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLineApiView=void 0;const s=i(511);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new s.CellData)}translateToString(e,t,i){return this._line.translateToString(e,t,i)}}},8285:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferNamespaceApi=void 0;const s=i(8771),r=i(8460),n=i(844);class o extends n.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this.register(new r.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new s.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new s.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},7975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,i)=>t(e,i.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},7090:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},744:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;const n=i(8460),o=i(844),a=i(5295),h=i(2585);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let c=t.BufferService=class extends o.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this.register(new n.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new n.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this.register(new a.BufferSet(e,this))}resize(e,t){this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){const i=this.buffer;let s;s=this._cachedBlankLine,s&&s.length===this.cols&&s.getFg(0)===e.fg&&s.getBg(0)===e.bg||(s=i.getBlankLine(e,t),this._cachedBlankLine=s),s.isWrapped=t;const r=i.ybase+i.scrollTop,n=i.ybase+i.scrollBottom;if(0===i.scrollTop){const e=i.lines.isFull;n===i.lines.length-1?e?i.lines.recycle().copyFrom(s):i.lines.push(s.clone()):i.lines.splice(n+1,0,s.clone()),e?this.isUserScrolling&&(i.ydisp=Math.max(i.ydisp-1,0)):(i.ybase++,this.isUserScrolling||i.ydisp++)}else{const e=n-r+1;i.lines.shiftElements(r+1,e-1,-1),i.lines.set(n,s.clone())}this.isUserScrolling||(i.ydisp=i.ybase),this._onScroll.fire(i.ydisp)}scrollLines(e,t,i){const s=this.buffer;if(e<0){if(0===s.ydisp)return;this.isUserScrolling=!0}else e+s.ydisp>=s.ybase&&(this.isUserScrolling=!1);const r=s.ydisp;s.ydisp=Math.max(Math.min(s.ydisp+e,s.ybase),0),r!==s.ydisp&&(t||this._onScroll.fire(s.ydisp))}};t.BufferService=c=s([r(0,h.IOptionsService)],c)},7994:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},1753:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreMouseService=void 0;const n=i(2585),o=i(8460),a=i(844),h={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>4!==e.button&&1===e.action&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>32!==e.action},DRAG:{events:23,restrict:e=>32!==e.action||3!==e.button},ANY:{events:31,restrict:e=>!0}};function c(e,t){let i=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return 4===e.button?(i|=64,i|=e.action):(i|=3&e.button,4&e.button&&(i|=64),8&e.button&&(i|=128),32===e.action?i|=32:0!==e.action||t||(i|=3)),i}const l=String.fromCharCode,d={DEFAULT:e=>{const t=[c(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?"":`${l(t[0])}${l(t[1])}${l(t[2])}`},SGR:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${c(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{const t=0===e.action&&4!==e.button?"m":"M";return`[<${c(e,!0)};${e.x};${e.y}${t}`}};let _=t.CoreMouseService=class extends a.Disposable{constructor(e,t){super(),this._bufferService=e,this._coreService=t,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new o.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const e of Object.keys(h))this.addProtocol(e,h[e]);for(const e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return 0!==this._protocols[this._activeProtocol].events}set activeProtocol(e){if(!this._protocols[e])throw new Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw new Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows)return!1;if(4===e.button&&32===e.action)return!1;if(3===e.button&&32!==e.action)return!1;if(4!==e.button&&(2===e.action||3===e.action))return!1;if(e.col++,e.row++,32===e.action&&this._lastEvent&&this._equalEvents(this._lastEvent,e,"SGR_PIXELS"===this._activeEncoding))return!1;if(!this._protocols[this._activeProtocol].restrict(e))return!1;const t=this._encodings[this._activeEncoding](e);return t&&("DEFAULT"===this._activeEncoding?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,i){if(i){if(e.x!==t.x)return!1;if(e.y!==t.y)return!1}else{if(e.col!==t.col)return!1;if(e.row!==t.row)return!1}return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=_=s([r(0,n.IBufferService),r(1,n.ICoreService)],_)},6975:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreService=void 0;const n=i(1439),o=i(8460),a=i(844),h=i(2585),c=Object.freeze({insertMode:!1}),l=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let d=t.CoreService=class extends a.Disposable{constructor(e,t,i){super(),this._bufferService=e,this._logService=t,this._optionsService=i,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new o.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new o.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new o.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new o.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,n.clone)(c),this.decPrivateModes=(0,n.clone)(l)}reset(){this.modes=(0,n.clone)(c),this.decPrivateModes=(0,n.clone)(l)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;const i=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&i.ybase!==i.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`,(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`,(()=>e.split("").map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d=s([r(0,h.IBufferService),r(1,h.ILogService),r(2,h.IOptionsService)],d)},9074:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DecorationService=void 0;const s=i(8055),r=i(8460),n=i(844),o=i(6106);let a=0,h=0;class c extends n.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new o.SortedList((e=>null==e?void 0:e.marker.line)),this._onDecorationRegistered=this.register(new r.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new r.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,n.toDisposable)((()=>this.reset())))}registerDecoration(e){if(e.marker.isDisposed)return;const t=new l(e);if(t){const e=t.marker.onDispose((()=>t.dispose()));t.onDispose((()=>{t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())})),this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(const e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,i){var s,r,n;let o=0,a=0;for(const h of this._decorations.getKeyIterator(t))o=null!==(s=h.options.x)&&void 0!==s?s:0,a=o+(null!==(r=h.options.width)&&void 0!==r?r:1),e>=o&&e{var r,n,o;a=null!==(r=t.options.x)&&void 0!==r?r:0,h=a+(null!==(n=t.options.width)&&void 0!==n?n:1),e>=a&&e{Object.defineProperty(t,"__esModule",{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;const s=i(2585),r=i(8343);class n{constructor(...e){this._entries=new Map;for(const[t,i]of e)this.set(t,i)}set(e,t){const i=this._entries.get(e);return this._entries.set(e,t),i}forEach(e){for(const[t,i]of this._entries.entries())e(t,i)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=n,t.InstantiationService=class{constructor(){this._services=new n,this._services.set(s.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){const i=(0,r.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),s=[];for(const t of i){const i=this._services.get(t.id);if(!i)throw new Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id}.`);s.push(i)}const n=i.length>0?i[0].index:t.length;if(t.length!==n)throw new Error(`[createInstance] First service dependency of ${e.name} at position ${n+1} conflicts with ${t.length} static arguments`);return new e(...[...t,...s])}}},7866:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.traceCall=t.setTraceLogger=t.LogService=void 0;const n=i(844),o=i(2585),a={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF};let h,c=t.LogService=class extends n.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),h=this}_updateLogLevel(){this._logLevel=a[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;tJSON.stringify(e))).join(", ")})`);const t=s.apply(this,e);return h.trace(`GlyphRenderer#${s.name} return`,t),t}}},7302:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;const s=i(8460),r=i(844),n=i(6114);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rightClickSelectsWord:n.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const o=["normal","bold","100","200","300","400","500","600","700","800","900"];class a extends r.Disposable{constructor(e){super(),this._onOptionChange=this.register(new s.EventEmitter),this.onOptionChange=this._onOptionChange.event;const i=Object.assign({},t.DEFAULT_OPTIONS);for(const t in e)if(t in i)try{const s=e[t];i[t]=this._sanitizeAndValidateOption(t,s)}catch(e){console.error(e)}this.rawOptions=i,this.options=Object.assign({},i),this._setupOptions()}onSpecificOptionChange(e,t){return this.onOptionChange((i=>{i===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((i=>{-1!==e.indexOf(i)&&t()}))}_setupOptions(){const e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);return this.rawOptions[e]},i=(e,i)=>{if(!(e in t.DEFAULT_OPTIONS))throw new Error(`No option with key "${e}"`);i=this._sanitizeAndValidateOption(e,i),this.rawOptions[e]!==i&&(this.rawOptions[e]=i,this._onOptionChange.fire(e))};for(const t in this.rawOptions){const s={get:e.bind(this,t),set:i.bind(this,t)};Object.defineProperty(this.options,t,s)}}_sanitizeAndValidateOption(e,i){switch(e){case"cursorStyle":if(i||(i=t.DEFAULT_OPTIONS[e]),!function(e){return"block"===e||"underline"===e||"bar"===e}(i))throw new Error(`"${i}" is not a valid value for ${e}`);break;case"wordSeparator":i||(i=t.DEFAULT_OPTIONS[e]);break;case"fontWeight":case"fontWeightBold":if("number"==typeof i&&1<=i&&i<=1e3)break;i=o.includes(i)?i:t.DEFAULT_OPTIONS[e];break;case"cursorWidth":i=Math.floor(i);case"lineHeight":case"tabStopWidth":if(i<1)throw new Error(`${e} cannot be less than 1, value: ${i}`);break;case"minimumContrastRatio":i=Math.max(1,Math.min(21,Math.round(10*i)/10));break;case"scrollback":if((i=Math.min(i,4294967295))<0)throw new Error(`${e} cannot be less than 0, value: ${i}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(i<=0)throw new Error(`${e} cannot be less than or equal to 0, value: ${i}`);break;case"rows":case"cols":if(!i&&0!==i)throw new Error(`${e} must be numeric, value: ${i}`);break;case"windowsPty":i=null!=i?i:{}}return i}}t.OptionsService=a},2660:function(e,t,i){var s=this&&this.__decorate||function(e,t,i,s){var r,n=arguments.length,o=n<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,i):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,i,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(n<3?r(o):n>3?r(t,i,o):r(t,i))||o);return n>3&&o&&Object.defineProperty(t,i,o),o},r=this&&this.__param||function(e,t){return function(i,s){t(i,s,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkService=void 0;const n=i(2585);let o=t.OscLinkService=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){const t=this._bufferService.buffer;if(void 0===e.id){const i=t.addMarker(t.ybase+t.y),s={data:e,id:this._nextId++,lines:[i]};return i.onDispose((()=>this._removeMarkerFromLink(s,i))),this._dataByLinkId.set(s.id,s),s.id}const i=e,s=this._getEntryIdKey(i),r=this._entriesWithId.get(s);if(r)return this.addLineToLink(r.id,t.ybase+t.y),r.id;const n=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(i),data:i,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(o,n))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){const i=this._dataByLinkId.get(e);if(i&&i.lines.every((e=>e.line!==t))){const e=this._bufferService.buffer.addMarker(t);i.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(i,e)))}}getLinkData(e){var t;return null===(t=this._dataByLinkId.get(e))||void 0===t?void 0:t.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){const i=e.lines.indexOf(t);-1!==i&&(e.lines.splice(i,1),0===e.lines.length&&(void 0!==e.data.id&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o=s([r(0,n.IBufferService)],o)},8343:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createDecorator=t.getServiceDependencies=t.serviceRegistry=void 0;const i="di$target",s="di$dependencies";t.serviceRegistry=new Map,t.getServiceDependencies=function(e){return e[s]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);const r=function(e,t,n){if(3!==arguments.length)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");!function(e,t,r){t[i]===t?t[s].push({id:e,index:r}):(t[s]=[{id:e,index:r}],t[i]=t)}(r,e,n)};return r.toString=()=>e,t.serviceRegistry.set(e,r),r}},2585:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;const s=i(8343);var r;t.IBufferService=(0,s.createDecorator)("BufferService"),t.ICoreMouseService=(0,s.createDecorator)("CoreMouseService"),t.ICoreService=(0,s.createDecorator)("CoreService"),t.ICharsetService=(0,s.createDecorator)("CharsetService"),t.IInstantiationService=(0,s.createDecorator)("InstantiationService"),function(e){e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.OFF=5]="OFF"}(r||(t.LogLevelEnum=r={})),t.ILogService=(0,s.createDecorator)("LogService"),t.IOptionsService=(0,s.createDecorator)("OptionsService"),t.IOscLinkService=(0,s.createDecorator)("OscLinkService"),t.IUnicodeService=(0,s.createDecorator)("UnicodeService"),t.IDecorationService=(0,s.createDecorator)("DecorationService")},1480:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeService=void 0;const s=i(8460),r=i(225);t.UnicodeService=class{constructor(){this._providers=Object.create(null),this._active="",this._onChange=new s.EventEmitter,this.onChange=this._onChange.event;const e=new r.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw new Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0;const i=e.length;for(let s=0;s=i)return t+this.wcwidth(r);const n=e.charCodeAt(s);56320<=n&&n<=57343?r=1024*(r-55296)+n-56320+65536:t+=this.wcwidth(n)}t+=this.wcwidth(r)}return t}}}},t={};function i(s){var r=t[s];if(void 0!==r)return r.exports;var n=t[s]={exports:{}};return e[s].call(n.exports,n,n.exports,i),n.exports}var s={};return(()=>{var e=s;Object.defineProperty(e,"__esModule",{value:!0}),e.Terminal=void 0;const t=i(9042),r=i(3236),n=i(844),o=i(5741),a=i(8285),h=i(7975),c=i(7090),l=["cols","rows"];class d extends n.Disposable{constructor(e){super(),this._core=this.register(new r.Terminal(e)),this._addonManager=this.register(new o.AddonManager),this._publicOptions=Object.assign({},this._core.options);const t=e=>this._core.options[e],i=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(const e in this._core.options){const s={get:t.bind(this,e),set:i.bind(this,e)};Object.defineProperty(this._publicOptions,e,s)}}_checkReadonlyOptions(e){if(l.includes(e))throw new Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new h.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new c.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new a.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const e=this._core.coreService.decPrivateModes;let t="none";switch(this._core.coreMouseService.activeProtocol){case"X10":t="x10";break;case"VT200":t="vt200";break;case"DRAG":t="drag";break;case"ANY":t="any"}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(const t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){var t,i,s;return this._checkProposedApi(),this._verifyPositiveIntegers(null!==(t=e.x)&&void 0!==t?t:0,null!==(i=e.width)&&void 0!==i?i:0,null!==(s=e.height)&&void 0!==s?s:0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,i){this._verifyIntegers(e,t,i),this._core.select(e,t,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write("\r\n",t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return t}_verifyIntegers(...e){for(const t of e)if(t===1/0||isNaN(t)||t%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...e){for(const t of e)if(t&&(t===1/0||isNaN(t)||t%1!=0||t<0))throw new Error("This API only accepts positive integers")}}e.Terminal=d})(),s})())); -//# sourceMappingURL=xterm.js.map \ No newline at end of file +!(function (e, t) { + if ("object" == typeof exports && "object" == typeof module) + module.exports = t(); + else if ("function" == typeof define && define.amd) define([], t); + else { + var i = t(); + for (var s in i) ("object" == typeof exports ? exports : e)[s] = i[s]; + } +})(self, () => + (() => { + "use strict"; + var e = { + 4567: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.AccessibilityManager = void 0)); + const n = i(9042), + o = i(6114), + a = i(9924), + h = i(844), + c = i(5596), + l = i(4725), + d = i(3656); + let _ = (t.AccessibilityManager = class extends h.Disposable { + constructor(e, t) { + (super(), + (this._terminal = e), + (this._renderService = t), + (this._liveRegionLineCount = 0), + (this._charsToConsume = []), + (this._charsToAnnounce = ""), + (this._accessibilityContainer = document.createElement("div")), + this._accessibilityContainer.classList.add( + "xterm-accessibility", + ), + (this._rowContainer = document.createElement("div")), + this._rowContainer.setAttribute("role", "list"), + this._rowContainer.classList.add("xterm-accessibility-tree"), + (this._rowElements = [])); + for (let e = 0; e < this._terminal.rows; e++) + ((this._rowElements[e] = this._createAccessibilityTreeNode()), + this._rowContainer.appendChild(this._rowElements[e])); + if ( + ((this._topBoundaryFocusListener = (e) => + this._handleBoundaryFocus(e, 0)), + (this._bottomBoundaryFocusListener = (e) => + this._handleBoundaryFocus(e, 1)), + this._rowElements[0].addEventListener( + "focus", + this._topBoundaryFocusListener, + ), + this._rowElements[ + this._rowElements.length - 1 + ].addEventListener("focus", this._bottomBoundaryFocusListener), + this._refreshRowsDimensions(), + this._accessibilityContainer.appendChild(this._rowContainer), + (this._liveRegion = document.createElement("div")), + this._liveRegion.classList.add("live-region"), + this._liveRegion.setAttribute("aria-live", "assertive"), + this._accessibilityContainer.appendChild(this._liveRegion), + (this._liveRegionDebouncer = this.register( + new a.TimeBasedDebouncer(this._renderRows.bind(this)), + )), + !this._terminal.element) + ) + throw new Error( + "Cannot enable accessibility before Terminal.open", + ); + (this._terminal.element.insertAdjacentElement( + "afterbegin", + this._accessibilityContainer, + ), + this.register( + this._terminal.onResize((e) => this._handleResize(e.rows)), + ), + this.register( + this._terminal.onRender((e) => + this._refreshRows(e.start, e.end), + ), + ), + this.register( + this._terminal.onScroll(() => this._refreshRows()), + ), + this.register( + this._terminal.onA11yChar((e) => this._handleChar(e)), + ), + this.register( + this._terminal.onLineFeed(() => this._handleChar("\n")), + ), + this.register( + this._terminal.onA11yTab((e) => this._handleTab(e)), + ), + this.register( + this._terminal.onKey((e) => this._handleKey(e.key)), + ), + this.register( + this._terminal.onBlur(() => this._clearLiveRegion()), + ), + this.register( + this._renderService.onDimensionsChange(() => + this._refreshRowsDimensions(), + ), + ), + (this._screenDprMonitor = new c.ScreenDprMonitor(window)), + this.register(this._screenDprMonitor), + this._screenDprMonitor.setListener(() => + this._refreshRowsDimensions(), + ), + this.register( + (0, d.addDisposableDomListener)(window, "resize", () => + this._refreshRowsDimensions(), + ), + ), + this._refreshRows(), + this.register( + (0, h.toDisposable)(() => { + (this._accessibilityContainer.remove(), + (this._rowElements.length = 0)); + }), + )); + } + _handleTab(e) { + for (let t = 0; t < e; t++) this._handleChar(" "); + } + _handleChar(e) { + this._liveRegionLineCount < 21 && + (this._charsToConsume.length > 0 + ? this._charsToConsume.shift() !== e && + (this._charsToAnnounce += e) + : (this._charsToAnnounce += e), + "\n" === e && + (this._liveRegionLineCount++, + 21 === this._liveRegionLineCount && + (this._liveRegion.textContent += n.tooMuchOutput)), + o.isMac && + this._liveRegion.textContent && + this._liveRegion.textContent.length > 0 && + !this._liveRegion.parentNode && + setTimeout(() => { + this._accessibilityContainer.appendChild(this._liveRegion); + }, 0)); + } + _clearLiveRegion() { + ((this._liveRegion.textContent = ""), + (this._liveRegionLineCount = 0), + o.isMac && this._liveRegion.remove()); + } + _handleKey(e) { + (this._clearLiveRegion(), + /\p{Control}/u.test(e) || this._charsToConsume.push(e)); + } + _refreshRows(e, t) { + this._liveRegionDebouncer.refresh(e, t, this._terminal.rows); + } + _renderRows(e, t) { + const i = this._terminal.buffer, + s = i.lines.length.toString(); + for (let r = e; r <= t; r++) { + const e = i.translateBufferLineToString(i.ydisp + r, !0), + t = (i.ydisp + r + 1).toString(), + n = this._rowElements[r]; + n && + (0 === e.length ? (n.innerText = " ") : (n.textContent = e), + n.setAttribute("aria-posinset", t), + n.setAttribute("aria-setsize", s)); + } + this._announceCharacters(); + } + _announceCharacters() { + 0 !== this._charsToAnnounce.length && + ((this._liveRegion.textContent += this._charsToAnnounce), + (this._charsToAnnounce = "")); + } + _handleBoundaryFocus(e, t) { + const i = e.target, + s = + this._rowElements[0 === t ? 1 : this._rowElements.length - 2]; + if ( + i.getAttribute("aria-posinset") === + (0 === t ? "1" : `${this._terminal.buffer.lines.length}`) + ) + return; + if (e.relatedTarget !== s) return; + let r, n; + if ( + (0 === t + ? ((r = i), + (n = this._rowElements.pop()), + this._rowContainer.removeChild(n)) + : ((r = this._rowElements.shift()), + (n = i), + this._rowContainer.removeChild(r)), + r.removeEventListener("focus", this._topBoundaryFocusListener), + n.removeEventListener( + "focus", + this._bottomBoundaryFocusListener, + ), + 0 === t) + ) { + const e = this._createAccessibilityTreeNode(); + (this._rowElements.unshift(e), + this._rowContainer.insertAdjacentElement("afterbegin", e)); + } else { + const e = this._createAccessibilityTreeNode(); + (this._rowElements.push(e), this._rowContainer.appendChild(e)); + } + (this._rowElements[0].addEventListener( + "focus", + this._topBoundaryFocusListener, + ), + this._rowElements[ + this._rowElements.length - 1 + ].addEventListener("focus", this._bottomBoundaryFocusListener), + this._terminal.scrollLines(0 === t ? -1 : 1), + this._rowElements[ + 0 === t ? 1 : this._rowElements.length - 2 + ].focus(), + e.preventDefault(), + e.stopImmediatePropagation()); + } + _handleResize(e) { + this._rowElements[ + this._rowElements.length - 1 + ].removeEventListener("focus", this._bottomBoundaryFocusListener); + for ( + let e = this._rowContainer.children.length; + e < this._terminal.rows; + e++ + ) + ((this._rowElements[e] = this._createAccessibilityTreeNode()), + this._rowContainer.appendChild(this._rowElements[e])); + for (; this._rowElements.length > e; ) + this._rowContainer.removeChild(this._rowElements.pop()); + (this._rowElements[this._rowElements.length - 1].addEventListener( + "focus", + this._bottomBoundaryFocusListener, + ), + this._refreshRowsDimensions()); + } + _createAccessibilityTreeNode() { + const e = document.createElement("div"); + return ( + e.setAttribute("role", "listitem"), + (e.tabIndex = -1), + this._refreshRowDimensions(e), + e + ); + } + _refreshRowsDimensions() { + if (this._renderService.dimensions.css.cell.height) { + ((this._accessibilityContainer.style.width = `${this._renderService.dimensions.css.canvas.width}px`), + this._rowElements.length !== this._terminal.rows && + this._handleResize(this._terminal.rows)); + for (let e = 0; e < this._terminal.rows; e++) + this._refreshRowDimensions(this._rowElements[e]); + } + } + _refreshRowDimensions(e) { + e.style.height = `${this._renderService.dimensions.css.cell.height}px`; + } + }); + t.AccessibilityManager = _ = s([r(1, l.IRenderService)], _); + }, + 3614: (e, t) => { + function i(e) { + return e.replace(/\r?\n/g, "\r"); + } + function s(e, t) { + return t ? "[200~" + e + "[201~" : e; + } + function r(e, t, r, n) { + ((e = s( + (e = i(e)), + r.decPrivateModes.bracketedPasteMode && + !0 !== n.rawOptions.ignoreBracketedPasteMode, + )), + r.triggerDataEvent(e, !0), + (t.value = "")); + } + function n(e, t, i) { + const s = i.getBoundingClientRect(), + r = e.clientX - s.left - 10, + n = e.clientY - s.top - 10; + ((t.style.width = "20px"), + (t.style.height = "20px"), + (t.style.left = `${r}px`), + (t.style.top = `${n}px`), + (t.style.zIndex = "1000"), + t.focus()); + } + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.rightClickHandler = + t.moveTextAreaUnderMouseCursor = + t.paste = + t.handlePasteEvent = + t.copyHandler = + t.bracketTextForPaste = + t.prepareTextForTerminal = + void 0), + (t.prepareTextForTerminal = i), + (t.bracketTextForPaste = s), + (t.copyHandler = function (e, t) { + (e.clipboardData && + e.clipboardData.setData("text/plain", t.selectionText), + e.preventDefault()); + }), + (t.handlePasteEvent = function (e, t, i, s) { + (e.stopPropagation(), + e.clipboardData && + r(e.clipboardData.getData("text/plain"), t, i, s)); + }), + (t.paste = r), + (t.moveTextAreaUnderMouseCursor = n), + (t.rightClickHandler = function (e, t, i, s, r) { + (n(e, t, i), + r && s.rightClickSelect(e), + (t.value = s.selectionText), + t.select()); + })); + }, + 7239: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.ColorContrastCache = void 0)); + const s = i(1505); + t.ColorContrastCache = class { + constructor() { + ((this._color = new s.TwoKeyMap()), + (this._css = new s.TwoKeyMap())); + } + setCss(e, t, i) { + this._css.set(e, t, i); + } + getCss(e, t) { + return this._css.get(e, t); + } + setColor(e, t, i) { + this._color.set(e, t, i); + } + getColor(e, t) { + return this._color.get(e, t); + } + clear() { + (this._color.clear(), this._css.clear()); + } + }; + }, + 3656: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.addDisposableDomListener = void 0), + (t.addDisposableDomListener = function (e, t, i, s) { + e.addEventListener(t, i, s); + let r = !1; + return { + dispose: () => { + r || ((r = !0), e.removeEventListener(t, i, s)); + }, + }; + })); + }, + 6465: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.Linkifier2 = void 0)); + const n = i(3656), + o = i(8460), + a = i(844), + h = i(2585); + let c = (t.Linkifier2 = class extends a.Disposable { + get currentLink() { + return this._currentLink; + } + constructor(e) { + (super(), + (this._bufferService = e), + (this._linkProviders = []), + (this._linkCacheDisposables = []), + (this._isMouseOut = !0), + (this._wasResized = !1), + (this._activeLine = -1), + (this._onShowLinkUnderline = this.register( + new o.EventEmitter(), + )), + (this.onShowLinkUnderline = this._onShowLinkUnderline.event), + (this._onHideLinkUnderline = this.register( + new o.EventEmitter(), + )), + (this.onHideLinkUnderline = this._onHideLinkUnderline.event), + this.register( + (0, a.getDisposeArrayDisposable)(this._linkCacheDisposables), + ), + this.register( + (0, a.toDisposable)(() => { + this._lastMouseEvent = void 0; + }), + ), + this.register( + this._bufferService.onResize(() => { + (this._clearCurrentLink(), (this._wasResized = !0)); + }), + )); + } + registerLinkProvider(e) { + return ( + this._linkProviders.push(e), + { + dispose: () => { + const t = this._linkProviders.indexOf(e); + -1 !== t && this._linkProviders.splice(t, 1); + }, + } + ); + } + attachToDom(e, t, i) { + ((this._element = e), + (this._mouseService = t), + (this._renderService = i), + this.register( + (0, n.addDisposableDomListener)( + this._element, + "mouseleave", + () => { + ((this._isMouseOut = !0), this._clearCurrentLink()); + }, + ), + ), + this.register( + (0, n.addDisposableDomListener)( + this._element, + "mousemove", + this._handleMouseMove.bind(this), + ), + ), + this.register( + (0, n.addDisposableDomListener)( + this._element, + "mousedown", + this._handleMouseDown.bind(this), + ), + ), + this.register( + (0, n.addDisposableDomListener)( + this._element, + "mouseup", + this._handleMouseUp.bind(this), + ), + )); + } + _handleMouseMove(e) { + if ( + ((this._lastMouseEvent = e), + !this._element || !this._mouseService) + ) + return; + const t = this._positionFromMouseEvent( + e, + this._element, + this._mouseService, + ); + if (!t) return; + this._isMouseOut = !1; + const i = e.composedPath(); + for (let e = 0; e < i.length; e++) { + const t = i[e]; + if (t.classList.contains("xterm")) break; + if (t.classList.contains("xterm-hover")) return; + } + (this._lastBufferCell && + t.x === this._lastBufferCell.x && + t.y === this._lastBufferCell.y) || + (this._handleHover(t), (this._lastBufferCell = t)); + } + _handleHover(e) { + if (this._activeLine !== e.y || this._wasResized) + return ( + this._clearCurrentLink(), + this._askForLink(e, !1), + void (this._wasResized = !1) + ); + (this._currentLink && + this._linkAtPosition(this._currentLink.link, e)) || + (this._clearCurrentLink(), this._askForLink(e, !0)); + } + _askForLink(e, t) { + var i, s; + (this._activeProviderReplies && t) || + (null === (i = this._activeProviderReplies) || + void 0 === i || + i.forEach((e) => { + null == e || + e.forEach((e) => { + e.link.dispose && e.link.dispose(); + }); + }), + (this._activeProviderReplies = new Map()), + (this._activeLine = e.y)); + let r = !1; + for (const [i, n] of this._linkProviders.entries()) + t + ? (null === (s = this._activeProviderReplies) || void 0 === s + ? void 0 + : s.get(i)) && + (r = this._checkLinkProviderResult(i, e, r)) + : n.provideLinks(e.y, (t) => { + var s, n; + if (this._isMouseOut) return; + const o = + null == t ? void 0 : t.map((e) => ({ link: e })); + (null === (s = this._activeProviderReplies) || + void 0 === s || + s.set(i, o), + (r = this._checkLinkProviderResult(i, e, r)), + (null === (n = this._activeProviderReplies) || + void 0 === n + ? void 0 + : n.size) === this._linkProviders.length && + this._removeIntersectingLinks( + e.y, + this._activeProviderReplies, + )); + }); + } + _removeIntersectingLinks(e, t) { + const i = new Set(); + for (let s = 0; s < t.size; s++) { + const r = t.get(s); + if (r) + for (let t = 0; t < r.length; t++) { + const s = r[t], + n = s.link.range.start.y < e ? 0 : s.link.range.start.x, + o = + s.link.range.end.y > e + ? this._bufferService.cols + : s.link.range.end.x; + for (let e = n; e <= o; e++) { + if (i.has(e)) { + r.splice(t--, 1); + break; + } + i.add(e); + } + } + } + } + _checkLinkProviderResult(e, t, i) { + var s; + if (!this._activeProviderReplies) return i; + const r = this._activeProviderReplies.get(e); + let n = !1; + for (let t = 0; t < e; t++) + (this._activeProviderReplies.has(t) && + !this._activeProviderReplies.get(t)) || + (n = !0); + if (!n && r) { + const e = r.find((e) => this._linkAtPosition(e.link, t)); + e && ((i = !0), this._handleNewLink(e)); + } + if ( + this._activeProviderReplies.size === + this._linkProviders.length && + !i + ) + for (let e = 0; e < this._activeProviderReplies.size; e++) { + const r = + null === (s = this._activeProviderReplies.get(e)) || + void 0 === s + ? void 0 + : s.find((e) => this._linkAtPosition(e.link, t)); + if (r) { + ((i = !0), this._handleNewLink(r)); + break; + } + } + return i; + } + _handleMouseDown() { + this._mouseDownLink = this._currentLink; + } + _handleMouseUp(e) { + if (!this._element || !this._mouseService || !this._currentLink) + return; + const t = this._positionFromMouseEvent( + e, + this._element, + this._mouseService, + ); + t && + this._mouseDownLink === this._currentLink && + this._linkAtPosition(this._currentLink.link, t) && + this._currentLink.link.activate(e, this._currentLink.link.text); + } + _clearCurrentLink(e, t) { + this._element && + this._currentLink && + this._lastMouseEvent && + (!e || + !t || + (this._currentLink.link.range.start.y >= e && + this._currentLink.link.range.end.y <= t)) && + (this._linkLeave( + this._element, + this._currentLink.link, + this._lastMouseEvent, + ), + (this._currentLink = void 0), + (0, a.disposeArray)(this._linkCacheDisposables)); + } + _handleNewLink(e) { + if ( + !this._element || + !this._lastMouseEvent || + !this._mouseService + ) + return; + const t = this._positionFromMouseEvent( + this._lastMouseEvent, + this._element, + this._mouseService, + ); + t && + this._linkAtPosition(e.link, t) && + ((this._currentLink = e), + (this._currentLink.state = { + decorations: { + underline: + void 0 === e.link.decorations || + e.link.decorations.underline, + pointerCursor: + void 0 === e.link.decorations || + e.link.decorations.pointerCursor, + }, + isHovered: !0, + }), + this._linkHover(this._element, e.link, this._lastMouseEvent), + (e.link.decorations = {}), + Object.defineProperties(e.link.decorations, { + pointerCursor: { + get: () => { + var e, t; + return null === + (t = + null === (e = this._currentLink) || void 0 === e + ? void 0 + : e.state) || void 0 === t + ? void 0 + : t.decorations.pointerCursor; + }, + set: (e) => { + var t, i; + (null === (t = this._currentLink) || void 0 === t + ? void 0 + : t.state) && + this._currentLink.state.decorations.pointerCursor !== + e && + ((this._currentLink.state.decorations.pointerCursor = + e), + this._currentLink.state.isHovered && + (null === (i = this._element) || + void 0 === i || + i.classList.toggle("xterm-cursor-pointer", e))); + }, + }, + underline: { + get: () => { + var e, t; + return null === + (t = + null === (e = this._currentLink) || void 0 === e + ? void 0 + : e.state) || void 0 === t + ? void 0 + : t.decorations.underline; + }, + set: (t) => { + var i, s, r; + (null === (i = this._currentLink) || void 0 === i + ? void 0 + : i.state) && + (null === + (r = + null === (s = this._currentLink) || void 0 === s + ? void 0 + : s.state) || void 0 === r + ? void 0 + : r.decorations.underline) !== t && + ((this._currentLink.state.decorations.underline = t), + this._currentLink.state.isHovered && + this._fireUnderlineEvent(e.link, t)); + }, + }, + }), + this._renderService && + this._linkCacheDisposables.push( + this._renderService.onRenderedViewportChange((e) => { + if (!this._currentLink) return; + const t = + 0 === e.start + ? 0 + : e.start + 1 + this._bufferService.buffer.ydisp, + i = this._bufferService.buffer.ydisp + 1 + e.end; + if ( + this._currentLink.link.range.start.y >= t && + this._currentLink.link.range.end.y <= i && + (this._clearCurrentLink(t, i), + this._lastMouseEvent && this._element) + ) { + const e = this._positionFromMouseEvent( + this._lastMouseEvent, + this._element, + this._mouseService, + ); + e && this._askForLink(e, !1); + } + }), + )); + } + _linkHover(e, t, i) { + var s; + ((null === (s = this._currentLink) || void 0 === s + ? void 0 + : s.state) && + ((this._currentLink.state.isHovered = !0), + this._currentLink.state.decorations.underline && + this._fireUnderlineEvent(t, !0), + this._currentLink.state.decorations.pointerCursor && + e.classList.add("xterm-cursor-pointer")), + t.hover && t.hover(i, t.text)); + } + _fireUnderlineEvent(e, t) { + const i = e.range, + s = this._bufferService.buffer.ydisp, + r = this._createLinkUnderlineEvent( + i.start.x - 1, + i.start.y - s - 1, + i.end.x, + i.end.y - s - 1, + void 0, + ); + (t ? this._onShowLinkUnderline : this._onHideLinkUnderline).fire( + r, + ); + } + _linkLeave(e, t, i) { + var s; + ((null === (s = this._currentLink) || void 0 === s + ? void 0 + : s.state) && + ((this._currentLink.state.isHovered = !1), + this._currentLink.state.decorations.underline && + this._fireUnderlineEvent(t, !1), + this._currentLink.state.decorations.pointerCursor && + e.classList.remove("xterm-cursor-pointer")), + t.leave && t.leave(i, t.text)); + } + _linkAtPosition(e, t) { + const i = + e.range.start.y * this._bufferService.cols + e.range.start.x, + s = e.range.end.y * this._bufferService.cols + e.range.end.x, + r = t.y * this._bufferService.cols + t.x; + return i <= r && r <= s; + } + _positionFromMouseEvent(e, t, i) { + const s = i.getCoords( + e, + t, + this._bufferService.cols, + this._bufferService.rows, + ); + if (s) + return { x: s[0], y: s[1] + this._bufferService.buffer.ydisp }; + } + _createLinkUnderlineEvent(e, t, i, s, r) { + return { + x1: e, + y1: t, + x2: i, + y2: s, + cols: this._bufferService.cols, + fg: r, + }; + } + }); + t.Linkifier2 = c = s([r(0, h.IBufferService)], c); + }, + 9042: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.tooMuchOutput = t.promptLabel = void 0), + (t.promptLabel = "Terminal input"), + (t.tooMuchOutput = + "Too much output to announce, navigate to rows manually to read")); + }, + 3730: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.OscLinkProvider = void 0)); + const n = i(511), + o = i(2585); + let a = (t.OscLinkProvider = class { + constructor(e, t, i) { + ((this._bufferService = e), + (this._optionsService = t), + (this._oscLinkService = i)); + } + provideLinks(e, t) { + var i; + const s = this._bufferService.buffer.lines.get(e - 1); + if (!s) return void t(void 0); + const r = [], + o = this._optionsService.rawOptions.linkHandler, + a = new n.CellData(), + c = s.getTrimmedLength(); + let l = -1, + d = -1, + _ = !1; + for (let t = 0; t < c; t++) + if (-1 !== d || s.hasContent(t)) { + if ( + (s.loadCell(t, a), a.hasExtendedAttrs() && a.extended.urlId) + ) { + if (-1 === d) { + ((d = t), (l = a.extended.urlId)); + continue; + } + _ = a.extended.urlId !== l; + } else -1 !== d && (_ = !0); + if (_ || (-1 !== d && t === c - 1)) { + const s = + null === (i = this._oscLinkService.getLinkData(l)) || + void 0 === i + ? void 0 + : i.uri; + if (s) { + const i = { + start: { x: d + 1, y: e }, + end: { x: t + (_ || t !== c - 1 ? 0 : 1), y: e }, + }; + let n = !1; + if (!(null == o ? void 0 : o.allowNonHttpProtocols)) + try { + const e = new URL(s); + ["http:", "https:"].includes(e.protocol) || (n = !0); + } catch (e) { + n = !0; + } + n || + r.push({ + text: s, + range: i, + activate: (e, t) => + o ? o.activate(e, t, i) : h(0, t), + hover: (e, t) => { + var s; + return null === + (s = null == o ? void 0 : o.hover) || void 0 === s + ? void 0 + : s.call(o, e, t, i); + }, + leave: (e, t) => { + var s; + return null === + (s = null == o ? void 0 : o.leave) || void 0 === s + ? void 0 + : s.call(o, e, t, i); + }, + }); + } + ((_ = !1), + a.hasExtendedAttrs() && a.extended.urlId + ? ((d = t), (l = a.extended.urlId)) + : ((d = -1), (l = -1))); + } + } + t(r); + } + }); + function h(e, t) { + if ( + confirm( + `Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`, + ) + ) { + const e = window.open(); + if (e) { + try { + e.opener = null; + } catch (e) {} + e.location.href = t; + } else + console.warn( + "Opening link blocked as opener could not be cleared", + ); + } + } + t.OscLinkProvider = a = s( + [ + r(0, o.IBufferService), + r(1, o.IOptionsService), + r(2, o.IOscLinkService), + ], + a, + ); + }, + 6193: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.RenderDebouncer = void 0), + (t.RenderDebouncer = class { + constructor(e, t) { + ((this._parentWindow = e), + (this._renderCallback = t), + (this._refreshCallbacks = [])); + } + dispose() { + this._animationFrame && + (this._parentWindow.cancelAnimationFrame( + this._animationFrame, + ), + (this._animationFrame = void 0)); + } + addRefreshCallback(e) { + return ( + this._refreshCallbacks.push(e), + this._animationFrame || + (this._animationFrame = + this._parentWindow.requestAnimationFrame(() => + this._innerRefresh(), + )), + this._animationFrame + ); + } + refresh(e, t, i) { + ((this._rowCount = i), + (e = void 0 !== e ? e : 0), + (t = void 0 !== t ? t : this._rowCount - 1), + (this._rowStart = + void 0 !== this._rowStart + ? Math.min(this._rowStart, e) + : e), + (this._rowEnd = + void 0 !== this._rowEnd ? Math.max(this._rowEnd, t) : t), + this._animationFrame || + (this._animationFrame = + this._parentWindow.requestAnimationFrame(() => + this._innerRefresh(), + ))); + } + _innerRefresh() { + if ( + ((this._animationFrame = void 0), + void 0 === this._rowStart || + void 0 === this._rowEnd || + void 0 === this._rowCount) + ) + return void this._runRefreshCallbacks(); + const e = Math.max(this._rowStart, 0), + t = Math.min(this._rowEnd, this._rowCount - 1); + ((this._rowStart = void 0), + (this._rowEnd = void 0), + this._renderCallback(e, t), + this._runRefreshCallbacks()); + } + _runRefreshCallbacks() { + for (const e of this._refreshCallbacks) e(0); + this._refreshCallbacks = []; + } + })); + }, + 5596: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.ScreenDprMonitor = void 0)); + const s = i(844); + class r extends s.Disposable { + constructor(e) { + (super(), + (this._parentWindow = e), + (this._currentDevicePixelRatio = + this._parentWindow.devicePixelRatio), + this.register( + (0, s.toDisposable)(() => { + this.clearListener(); + }), + )); + } + setListener(e) { + (this._listener && this.clearListener(), + (this._listener = e), + (this._outerListener = () => { + this._listener && + (this._listener( + this._parentWindow.devicePixelRatio, + this._currentDevicePixelRatio, + ), + this._updateDpr()); + }), + this._updateDpr()); + } + _updateDpr() { + var e; + this._outerListener && + (null === (e = this._resolutionMediaMatchList) || + void 0 === e || + e.removeListener(this._outerListener), + (this._currentDevicePixelRatio = + this._parentWindow.devicePixelRatio), + (this._resolutionMediaMatchList = this._parentWindow.matchMedia( + `screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`, + )), + this._resolutionMediaMatchList.addListener( + this._outerListener, + )); + } + clearListener() { + this._resolutionMediaMatchList && + this._listener && + this._outerListener && + (this._resolutionMediaMatchList.removeListener( + this._outerListener, + ), + (this._resolutionMediaMatchList = void 0), + (this._listener = void 0), + (this._outerListener = void 0)); + } + } + t.ScreenDprMonitor = r; + }, + 3236: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.Terminal = void 0)); + const s = i(3614), + r = i(3656), + n = i(6465), + o = i(9042), + a = i(3730), + h = i(1680), + c = i(3107), + l = i(5744), + d = i(2950), + _ = i(1296), + u = i(428), + f = i(4269), + v = i(5114), + p = i(8934), + g = i(3230), + m = i(9312), + S = i(4725), + C = i(6731), + b = i(8055), + y = i(8969), + w = i(8460), + E = i(844), + k = i(6114), + L = i(8437), + D = i(2584), + R = i(7399), + x = i(5941), + A = i(9074), + B = i(2585), + T = i(5435), + M = i(4567), + O = "undefined" != typeof window ? window.document : null; + class P extends y.CoreTerminal { + get onFocus() { + return this._onFocus.event; + } + get onBlur() { + return this._onBlur.event; + } + get onA11yChar() { + return this._onA11yCharEmitter.event; + } + get onA11yTab() { + return this._onA11yTabEmitter.event; + } + get onWillOpen() { + return this._onWillOpen.event; + } + constructor(e = {}) { + (super(e), + (this.browser = k), + (this._keyDownHandled = !1), + (this._keyDownSeen = !1), + (this._keyPressHandled = !1), + (this._unprocessedDeadKey = !1), + (this._accessibilityManager = this.register( + new E.MutableDisposable(), + )), + (this._onCursorMove = this.register(new w.EventEmitter())), + (this.onCursorMove = this._onCursorMove.event), + (this._onKey = this.register(new w.EventEmitter())), + (this.onKey = this._onKey.event), + (this._onRender = this.register(new w.EventEmitter())), + (this.onRender = this._onRender.event), + (this._onSelectionChange = this.register(new w.EventEmitter())), + (this.onSelectionChange = this._onSelectionChange.event), + (this._onTitleChange = this.register(new w.EventEmitter())), + (this.onTitleChange = this._onTitleChange.event), + (this._onBell = this.register(new w.EventEmitter())), + (this.onBell = this._onBell.event), + (this._onFocus = this.register(new w.EventEmitter())), + (this._onBlur = this.register(new w.EventEmitter())), + (this._onA11yCharEmitter = this.register(new w.EventEmitter())), + (this._onA11yTabEmitter = this.register(new w.EventEmitter())), + (this._onWillOpen = this.register(new w.EventEmitter())), + this._setup(), + (this.linkifier2 = this.register( + this._instantiationService.createInstance(n.Linkifier2), + )), + this.linkifier2.registerLinkProvider( + this._instantiationService.createInstance(a.OscLinkProvider), + ), + (this._decorationService = + this._instantiationService.createInstance( + A.DecorationService, + )), + this._instantiationService.setService( + B.IDecorationService, + this._decorationService, + ), + this.register( + this._inputHandler.onRequestBell(() => this._onBell.fire()), + ), + this.register( + this._inputHandler.onRequestRefreshRows((e, t) => + this.refresh(e, t), + ), + ), + this.register( + this._inputHandler.onRequestSendFocus(() => + this._reportFocus(), + ), + ), + this.register( + this._inputHandler.onRequestReset(() => this.reset()), + ), + this.register( + this._inputHandler.onRequestWindowsOptionsReport((e) => + this._reportWindowsOptions(e), + ), + ), + this.register( + this._inputHandler.onColor((e) => this._handleColorEvent(e)), + ), + this.register( + (0, w.forwardEvent)( + this._inputHandler.onCursorMove, + this._onCursorMove, + ), + ), + this.register( + (0, w.forwardEvent)( + this._inputHandler.onTitleChange, + this._onTitleChange, + ), + ), + this.register( + (0, w.forwardEvent)( + this._inputHandler.onA11yChar, + this._onA11yCharEmitter, + ), + ), + this.register( + (0, w.forwardEvent)( + this._inputHandler.onA11yTab, + this._onA11yTabEmitter, + ), + ), + this.register( + this._bufferService.onResize((e) => + this._afterResize(e.cols, e.rows), + ), + ), + this.register( + (0, E.toDisposable)(() => { + var e, t; + ((this._customKeyEventHandler = void 0), + null === + (t = + null === (e = this.element) || void 0 === e + ? void 0 + : e.parentNode) || + void 0 === t || + t.removeChild(this.element)); + }), + )); + } + _handleColorEvent(e) { + if (this._themeService) + for (const t of e) { + let e, + i = ""; + switch (t.index) { + case 256: + ((e = "foreground"), (i = "10")); + break; + case 257: + ((e = "background"), (i = "11")); + break; + case 258: + ((e = "cursor"), (i = "12")); + break; + default: + ((e = "ansi"), (i = "4;" + t.index)); + } + switch (t.type) { + case 0: + const s = b.color.toColorRGB( + "ansi" === e + ? this._themeService.colors.ansi[t.index] + : this._themeService.colors[e], + ); + this.coreService.triggerDataEvent( + `${D.C0.ESC}]${i};${(0, x.toRgbString)(s)}${D.C1_ESCAPED.ST}`, + ); + break; + case 1: + if ("ansi" === e) + this._themeService.modifyColors( + (e) => (e.ansi[t.index] = b.rgba.toColor(...t.color)), + ); + else { + const i = e; + this._themeService.modifyColors( + (e) => (e[i] = b.rgba.toColor(...t.color)), + ); + } + break; + case 2: + this._themeService.restoreColor(t.index); + } + } + } + _setup() { + (super._setup(), (this._customKeyEventHandler = void 0)); + } + get buffer() { + return this.buffers.active; + } + focus() { + this.textarea && this.textarea.focus({ preventScroll: !0 }); + } + _handleScreenReaderModeOptionChange(e) { + e + ? !this._accessibilityManager.value && + this._renderService && + (this._accessibilityManager.value = + this._instantiationService.createInstance( + M.AccessibilityManager, + this, + )) + : this._accessibilityManager.clear(); + } + _handleTextAreaFocus(e) { + (this.coreService.decPrivateModes.sendFocus && + this.coreService.triggerDataEvent(D.C0.ESC + "[I"), + this.updateCursorStyle(e), + this.element.classList.add("focus"), + this._showCursor(), + this._onFocus.fire()); + } + blur() { + var e; + return null === (e = this.textarea) || void 0 === e + ? void 0 + : e.blur(); + } + _handleTextAreaBlur() { + ((this.textarea.value = ""), + this.refresh(this.buffer.y, this.buffer.y), + this.coreService.decPrivateModes.sendFocus && + this.coreService.triggerDataEvent(D.C0.ESC + "[O"), + this.element.classList.remove("focus"), + this._onBlur.fire()); + } + _syncTextArea() { + if ( + !this.textarea || + !this.buffer.isCursorInViewport || + this._compositionHelper.isComposing || + !this._renderService + ) + return; + const e = this.buffer.ybase + this.buffer.y, + t = this.buffer.lines.get(e); + if (!t) return; + const i = Math.min(this.buffer.x, this.cols - 1), + s = this._renderService.dimensions.css.cell.height, + r = t.getWidth(i), + n = this._renderService.dimensions.css.cell.width * r, + o = + this.buffer.y * + this._renderService.dimensions.css.cell.height, + a = i * this._renderService.dimensions.css.cell.width; + ((this.textarea.style.left = a + "px"), + (this.textarea.style.top = o + "px"), + (this.textarea.style.width = n + "px"), + (this.textarea.style.height = s + "px"), + (this.textarea.style.lineHeight = s + "px"), + (this.textarea.style.zIndex = "-5")); + } + _initGlobal() { + (this._bindKeys(), + this.register( + (0, r.addDisposableDomListener)(this.element, "copy", (e) => { + this.hasSelection() && + (0, s.copyHandler)(e, this._selectionService); + }), + )); + const e = (e) => + (0, s.handlePasteEvent)( + e, + this.textarea, + this.coreService, + this.optionsService, + ); + (this.register( + (0, r.addDisposableDomListener)(this.textarea, "paste", e), + ), + this.register( + (0, r.addDisposableDomListener)(this.element, "paste", e), + ), + k.isFirefox + ? this.register( + (0, r.addDisposableDomListener)( + this.element, + "mousedown", + (e) => { + 2 === e.button && + (0, s.rightClickHandler)( + e, + this.textarea, + this.screenElement, + this._selectionService, + this.options.rightClickSelectsWord, + ); + }, + ), + ) + : this.register( + (0, r.addDisposableDomListener)( + this.element, + "contextmenu", + (e) => { + (0, s.rightClickHandler)( + e, + this.textarea, + this.screenElement, + this._selectionService, + this.options.rightClickSelectsWord, + ); + }, + ), + ), + k.isLinux && + this.register( + (0, r.addDisposableDomListener)( + this.element, + "auxclick", + (e) => { + 1 === e.button && + (0, s.moveTextAreaUnderMouseCursor)( + e, + this.textarea, + this.screenElement, + ); + }, + ), + )); + } + _bindKeys() { + (this.register( + (0, r.addDisposableDomListener)( + this.textarea, + "keyup", + (e) => this._keyUp(e), + !0, + ), + ), + this.register( + (0, r.addDisposableDomListener)( + this.textarea, + "keydown", + (e) => this._keyDown(e), + !0, + ), + ), + this.register( + (0, r.addDisposableDomListener)( + this.textarea, + "keypress", + (e) => this._keyPress(e), + !0, + ), + ), + this.register( + (0, r.addDisposableDomListener)( + this.textarea, + "compositionstart", + () => this._compositionHelper.compositionstart(), + ), + ), + this.register( + (0, r.addDisposableDomListener)( + this.textarea, + "compositionupdate", + (e) => this._compositionHelper.compositionupdate(e), + ), + ), + this.register( + (0, r.addDisposableDomListener)( + this.textarea, + "compositionend", + () => this._compositionHelper.compositionend(), + ), + ), + this.register( + (0, r.addDisposableDomListener)( + this.textarea, + "input", + (e) => this._inputEvent(e), + !0, + ), + ), + this.register( + this.onRender(() => + this._compositionHelper.updateCompositionElements(), + ), + )); + } + open(e) { + var t; + if (!e) throw new Error("Terminal requires a parent element."); + (e.isConnected || + this._logService.debug( + "Terminal.open was called on an element that was not attached to the DOM", + ), + (this._document = e.ownerDocument), + (this.element = this._document.createElement("div")), + (this.element.dir = "ltr"), + this.element.classList.add("terminal"), + this.element.classList.add("xterm"), + e.appendChild(this.element)); + const i = O.createDocumentFragment(); + ((this._viewportElement = O.createElement("div")), + this._viewportElement.classList.add("xterm-viewport"), + i.appendChild(this._viewportElement), + (this._viewportScrollArea = O.createElement("div")), + this._viewportScrollArea.classList.add("xterm-scroll-area"), + this._viewportElement.appendChild(this._viewportScrollArea), + (this.screenElement = O.createElement("div")), + this.screenElement.classList.add("xterm-screen"), + (this._helperContainer = O.createElement("div")), + this._helperContainer.classList.add("xterm-helpers"), + this.screenElement.appendChild(this._helperContainer), + i.appendChild(this.screenElement), + (this.textarea = O.createElement("textarea")), + this.textarea.classList.add("xterm-helper-textarea"), + this.textarea.setAttribute("aria-label", o.promptLabel), + k.isChromeOS || + this.textarea.setAttribute("aria-multiline", "false"), + this.textarea.setAttribute("autocorrect", "off"), + this.textarea.setAttribute("autocapitalize", "off"), + this.textarea.setAttribute("spellcheck", "false"), + (this.textarea.tabIndex = 0), + (this._coreBrowserService = + this._instantiationService.createInstance( + v.CoreBrowserService, + this.textarea, + null !== (t = this._document.defaultView) && void 0 !== t + ? t + : window, + )), + this._instantiationService.setService( + S.ICoreBrowserService, + this._coreBrowserService, + ), + this.register( + (0, r.addDisposableDomListener)(this.textarea, "focus", (e) => + this._handleTextAreaFocus(e), + ), + ), + this.register( + (0, r.addDisposableDomListener)(this.textarea, "blur", () => + this._handleTextAreaBlur(), + ), + ), + this._helperContainer.appendChild(this.textarea), + (this._charSizeService = + this._instantiationService.createInstance( + u.CharSizeService, + this._document, + this._helperContainer, + )), + this._instantiationService.setService( + S.ICharSizeService, + this._charSizeService, + ), + (this._themeService = this._instantiationService.createInstance( + C.ThemeService, + )), + this._instantiationService.setService( + S.IThemeService, + this._themeService, + ), + (this._characterJoinerService = + this._instantiationService.createInstance( + f.CharacterJoinerService, + )), + this._instantiationService.setService( + S.ICharacterJoinerService, + this._characterJoinerService, + ), + (this._renderService = this.register( + this._instantiationService.createInstance( + g.RenderService, + this.rows, + this.screenElement, + ), + )), + this._instantiationService.setService( + S.IRenderService, + this._renderService, + ), + this.register( + this._renderService.onRenderedViewportChange((e) => + this._onRender.fire(e), + ), + ), + this.onResize((e) => + this._renderService.resize(e.cols, e.rows), + ), + (this._compositionView = O.createElement("div")), + this._compositionView.classList.add("composition-view"), + (this._compositionHelper = + this._instantiationService.createInstance( + d.CompositionHelper, + this.textarea, + this._compositionView, + )), + this._helperContainer.appendChild(this._compositionView), + this.element.appendChild(i)); + try { + this._onWillOpen.fire(this.element); + } catch (e) {} + (this._renderService.hasRenderer() || + this._renderService.setRenderer(this._createRenderer()), + (this._mouseService = this._instantiationService.createInstance( + p.MouseService, + )), + this._instantiationService.setService( + S.IMouseService, + this._mouseService, + ), + (this.viewport = this._instantiationService.createInstance( + h.Viewport, + this._viewportElement, + this._viewportScrollArea, + )), + this.viewport.onRequestScrollLines((e) => + this.scrollLines(e.amount, e.suppressScrollEvent, 1), + ), + this.register( + this._inputHandler.onRequestSyncScrollBar(() => + this.viewport.syncScrollArea(), + ), + ), + this.register(this.viewport), + this.register( + this.onCursorMove(() => { + (this._renderService.handleCursorMove(), + this._syncTextArea()); + }), + ), + this.register( + this.onResize(() => + this._renderService.handleResize(this.cols, this.rows), + ), + ), + this.register( + this.onBlur(() => this._renderService.handleBlur()), + ), + this.register( + this.onFocus(() => this._renderService.handleFocus()), + ), + this.register( + this._renderService.onDimensionsChange(() => + this.viewport.syncScrollArea(), + ), + ), + (this._selectionService = this.register( + this._instantiationService.createInstance( + m.SelectionService, + this.element, + this.screenElement, + this.linkifier2, + ), + )), + this._instantiationService.setService( + S.ISelectionService, + this._selectionService, + ), + this.register( + this._selectionService.onRequestScrollLines((e) => + this.scrollLines(e.amount, e.suppressScrollEvent), + ), + ), + this.register( + this._selectionService.onSelectionChange(() => + this._onSelectionChange.fire(), + ), + ), + this.register( + this._selectionService.onRequestRedraw((e) => + this._renderService.handleSelectionChanged( + e.start, + e.end, + e.columnSelectMode, + ), + ), + ), + this.register( + this._selectionService.onLinuxMouseSelection((e) => { + ((this.textarea.value = e), + this.textarea.focus(), + this.textarea.select()); + }), + ), + this.register( + this._onScroll.event((e) => { + (this.viewport.syncScrollArea(), + this._selectionService.refresh()); + }), + ), + this.register( + (0, r.addDisposableDomListener)( + this._viewportElement, + "scroll", + () => this._selectionService.refresh(), + ), + ), + this.linkifier2.attachToDom( + this.screenElement, + this._mouseService, + this._renderService, + ), + this.register( + this._instantiationService.createInstance( + c.BufferDecorationRenderer, + this.screenElement, + ), + ), + this.register( + (0, r.addDisposableDomListener)( + this.element, + "mousedown", + (e) => this._selectionService.handleMouseDown(e), + ), + ), + this.coreMouseService.areMouseEventsActive + ? (this._selectionService.disable(), + this.element.classList.add("enable-mouse-events")) + : this._selectionService.enable(), + this.options.screenReaderMode && + (this._accessibilityManager.value = + this._instantiationService.createInstance( + M.AccessibilityManager, + this, + )), + this.register( + this.optionsService.onSpecificOptionChange( + "screenReaderMode", + (e) => this._handleScreenReaderModeOptionChange(e), + ), + ), + this.options.overviewRulerWidth && + (this._overviewRulerRenderer = this.register( + this._instantiationService.createInstance( + l.OverviewRulerRenderer, + this._viewportElement, + this.screenElement, + ), + )), + this.optionsService.onSpecificOptionChange( + "overviewRulerWidth", + (e) => { + !this._overviewRulerRenderer && + e && + this._viewportElement && + this.screenElement && + (this._overviewRulerRenderer = this.register( + this._instantiationService.createInstance( + l.OverviewRulerRenderer, + this._viewportElement, + this.screenElement, + ), + )); + }, + ), + this._charSizeService.measure(), + this.refresh(0, this.rows - 1), + this._initGlobal(), + this.bindMouse()); + } + _createRenderer() { + return this._instantiationService.createInstance( + _.DomRenderer, + this.element, + this.screenElement, + this._viewportElement, + this.linkifier2, + ); + } + bindMouse() { + const e = this, + t = this.element; + function i(t) { + const i = e._mouseService.getMouseReportCoords( + t, + e.screenElement, + ); + if (!i) return !1; + let s, r; + switch (t.overrideType || t.type) { + case "mousemove": + ((r = 32), + void 0 === t.buttons + ? ((s = 3), + void 0 !== t.button && + (s = t.button < 3 ? t.button : 3)) + : (s = + 1 & t.buttons + ? 0 + : 4 & t.buttons + ? 1 + : 2 & t.buttons + ? 2 + : 3)); + break; + case "mouseup": + ((r = 0), (s = t.button < 3 ? t.button : 3)); + break; + case "mousedown": + ((r = 1), (s = t.button < 3 ? t.button : 3)); + break; + case "wheel": + if (0 === e.viewport.getLinesScrolled(t)) return !1; + ((r = t.deltaY < 0 ? 0 : 1), (s = 4)); + break; + default: + return !1; + } + return ( + !(void 0 === r || void 0 === s || s > 4) && + e.coreMouseService.triggerMouseEvent({ + col: i.col, + row: i.row, + x: i.x, + y: i.y, + button: s, + action: r, + ctrl: t.ctrlKey, + alt: t.altKey, + shift: t.shiftKey, + }) + ); + } + const s = { + mouseup: null, + wheel: null, + mousedrag: null, + mousemove: null, + }, + n = { + mouseup: (e) => ( + i(e), + e.buttons || + (this._document.removeEventListener("mouseup", s.mouseup), + s.mousedrag && + this._document.removeEventListener( + "mousemove", + s.mousedrag, + )), + this.cancel(e) + ), + wheel: (e) => (i(e), this.cancel(e, !0)), + mousedrag: (e) => { + e.buttons && i(e); + }, + mousemove: (e) => { + e.buttons || i(e); + }, + }; + (this.register( + this.coreMouseService.onProtocolChange((e) => { + (e + ? ("debug" === this.optionsService.rawOptions.logLevel && + this._logService.debug( + "Binding to mouse events:", + this.coreMouseService.explainEvents(e), + ), + this.element.classList.add("enable-mouse-events"), + this._selectionService.disable()) + : (this._logService.debug("Unbinding from mouse events."), + this.element.classList.remove("enable-mouse-events"), + this._selectionService.enable()), + 8 & e + ? s.mousemove || + (t.addEventListener("mousemove", n.mousemove), + (s.mousemove = n.mousemove)) + : (t.removeEventListener("mousemove", s.mousemove), + (s.mousemove = null)), + 16 & e + ? s.wheel || + (t.addEventListener("wheel", n.wheel, { passive: !1 }), + (s.wheel = n.wheel)) + : (t.removeEventListener("wheel", s.wheel), + (s.wheel = null)), + 2 & e + ? s.mouseup || + (t.addEventListener("mouseup", n.mouseup), + (s.mouseup = n.mouseup)) + : (this._document.removeEventListener( + "mouseup", + s.mouseup, + ), + t.removeEventListener("mouseup", s.mouseup), + (s.mouseup = null)), + 4 & e + ? s.mousedrag || (s.mousedrag = n.mousedrag) + : (this._document.removeEventListener( + "mousemove", + s.mousedrag, + ), + (s.mousedrag = null))); + }), + ), + (this.coreMouseService.activeProtocol = + this.coreMouseService.activeProtocol), + this.register( + (0, r.addDisposableDomListener)(t, "mousedown", (e) => { + if ( + (e.preventDefault(), + this.focus(), + this.coreMouseService.areMouseEventsActive && + !this._selectionService.shouldForceSelection(e)) + ) + return ( + i(e), + s.mouseup && + this._document.addEventListener("mouseup", s.mouseup), + s.mousedrag && + this._document.addEventListener( + "mousemove", + s.mousedrag, + ), + this.cancel(e) + ); + }), + ), + this.register( + (0, r.addDisposableDomListener)( + t, + "wheel", + (e) => { + if (!s.wheel) { + if (!this.buffer.hasScrollback) { + const t = this.viewport.getLinesScrolled(e); + if (0 === t) return; + const i = + D.C0.ESC + + (this.coreService.decPrivateModes + .applicationCursorKeys + ? "O" + : "[") + + (e.deltaY < 0 ? "A" : "B"); + let s = ""; + for (let e = 0; e < Math.abs(t); e++) s += i; + return ( + this.coreService.triggerDataEvent(s, !0), + this.cancel(e, !0) + ); + } + return this.viewport.handleWheel(e) + ? this.cancel(e) + : void 0; + } + }, + { passive: !1 }, + ), + ), + this.register( + (0, r.addDisposableDomListener)( + t, + "touchstart", + (e) => { + if (!this.coreMouseService.areMouseEventsActive) + return ( + this.viewport.handleTouchStart(e), + this.cancel(e) + ); + }, + { passive: !0 }, + ), + ), + this.register( + (0, r.addDisposableDomListener)( + t, + "touchmove", + (e) => { + if (!this.coreMouseService.areMouseEventsActive) + return this.viewport.handleTouchMove(e) + ? void 0 + : this.cancel(e); + }, + { passive: !1 }, + ), + )); + } + refresh(e, t) { + var i; + null === (i = this._renderService) || + void 0 === i || + i.refreshRows(e, t); + } + updateCursorStyle(e) { + var t; + ( + null === (t = this._selectionService) || void 0 === t + ? void 0 + : t.shouldColumnSelect(e) + ) + ? this.element.classList.add("column-select") + : this.element.classList.remove("column-select"); + } + _showCursor() { + this.coreService.isCursorInitialized || + ((this.coreService.isCursorInitialized = !0), + this.refresh(this.buffer.y, this.buffer.y)); + } + scrollLines(e, t, i = 0) { + var s; + 1 === i + ? (super.scrollLines(e, t, i), this.refresh(0, this.rows - 1)) + : null === (s = this.viewport) || + void 0 === s || + s.scrollLines(e); + } + paste(e) { + (0, s.paste)( + e, + this.textarea, + this.coreService, + this.optionsService, + ); + } + attachCustomKeyEventHandler(e) { + this._customKeyEventHandler = e; + } + registerLinkProvider(e) { + return this.linkifier2.registerLinkProvider(e); + } + registerCharacterJoiner(e) { + if (!this._characterJoinerService) + throw new Error("Terminal must be opened first"); + const t = this._characterJoinerService.register(e); + return (this.refresh(0, this.rows - 1), t); + } + deregisterCharacterJoiner(e) { + if (!this._characterJoinerService) + throw new Error("Terminal must be opened first"); + this._characterJoinerService.deregister(e) && + this.refresh(0, this.rows - 1); + } + get markers() { + return this.buffer.markers; + } + registerMarker(e) { + return this.buffer.addMarker( + this.buffer.ybase + this.buffer.y + e, + ); + } + registerDecoration(e) { + return this._decorationService.registerDecoration(e); + } + hasSelection() { + return ( + !!this._selectionService && this._selectionService.hasSelection + ); + } + select(e, t, i) { + this._selectionService.setSelection(e, t, i); + } + getSelection() { + return this._selectionService + ? this._selectionService.selectionText + : ""; + } + getSelectionPosition() { + if (this._selectionService && this._selectionService.hasSelection) + return { + start: { + x: this._selectionService.selectionStart[0], + y: this._selectionService.selectionStart[1], + }, + end: { + x: this._selectionService.selectionEnd[0], + y: this._selectionService.selectionEnd[1], + }, + }; + } + clearSelection() { + var e; + null === (e = this._selectionService) || + void 0 === e || + e.clearSelection(); + } + selectAll() { + var e; + null === (e = this._selectionService) || + void 0 === e || + e.selectAll(); + } + selectLines(e, t) { + var i; + null === (i = this._selectionService) || + void 0 === i || + i.selectLines(e, t); + } + _keyDown(e) { + if ( + ((this._keyDownHandled = !1), + (this._keyDownSeen = !0), + this._customKeyEventHandler && + !1 === this._customKeyEventHandler(e)) + ) + return !1; + const t = + this.browser.isMac && this.options.macOptionIsMeta && e.altKey; + if (!t && !this._compositionHelper.keydown(e)) + return ( + this.options.scrollOnUserInput && + this.buffer.ybase !== this.buffer.ydisp && + this.scrollToBottom(), + !1 + ); + t || + ("Dead" !== e.key && "AltGraph" !== e.key) || + (this._unprocessedDeadKey = !0); + const i = (0, R.evaluateKeyboardEvent)( + e, + this.coreService.decPrivateModes.applicationCursorKeys, + this.browser.isMac, + this.options.macOptionIsMeta, + ); + if ((this.updateCursorStyle(e), 3 === i.type || 2 === i.type)) { + const t = this.rows - 1; + return ( + this.scrollLines(2 === i.type ? -t : t), + this.cancel(e, !0) + ); + } + return ( + 1 === i.type && this.selectAll(), + !!this._isThirdLevelShift(this.browser, e) || + (i.cancel && this.cancel(e, !0), + !i.key || + !!( + e.key && + !e.ctrlKey && + !e.altKey && + !e.metaKey && + 1 === e.key.length && + e.key.charCodeAt(0) >= 65 && + e.key.charCodeAt(0) <= 90 + ) || + (this._unprocessedDeadKey + ? ((this._unprocessedDeadKey = !1), !0) + : ((i.key !== D.C0.ETX && i.key !== D.C0.CR) || + (this.textarea.value = ""), + this._onKey.fire({ key: i.key, domEvent: e }), + this._showCursor(), + this.coreService.triggerDataEvent(i.key, !0), + !this.optionsService.rawOptions.screenReaderMode || + e.altKey || + e.ctrlKey + ? this.cancel(e, !0) + : void (this._keyDownHandled = !0)))) + ); + } + _isThirdLevelShift(e, t) { + const i = + (e.isMac && + !this.options.macOptionIsMeta && + t.altKey && + !t.ctrlKey && + !t.metaKey) || + (e.isWindows && t.altKey && t.ctrlKey && !t.metaKey) || + (e.isWindows && t.getModifierState("AltGraph")); + return "keypress" === t.type + ? i + : i && (!t.keyCode || t.keyCode > 47); + } + _keyUp(e) { + ((this._keyDownSeen = !1), + (this._customKeyEventHandler && + !1 === this._customKeyEventHandler(e)) || + ((function (e) { + return ( + 16 === e.keyCode || 17 === e.keyCode || 18 === e.keyCode + ); + })(e) || this.focus(), + this.updateCursorStyle(e), + (this._keyPressHandled = !1))); + } + _keyPress(e) { + let t; + if (((this._keyPressHandled = !1), this._keyDownHandled)) + return !1; + if ( + this._customKeyEventHandler && + !1 === this._customKeyEventHandler(e) + ) + return !1; + if ((this.cancel(e), e.charCode)) t = e.charCode; + else if (null === e.which || void 0 === e.which) t = e.keyCode; + else { + if (0 === e.which || 0 === e.charCode) return !1; + t = e.which; + } + return !( + !t || + ((e.altKey || e.ctrlKey || e.metaKey) && + !this._isThirdLevelShift(this.browser, e)) || + ((t = String.fromCharCode(t)), + this._onKey.fire({ key: t, domEvent: e }), + this._showCursor(), + this.coreService.triggerDataEvent(t, !0), + (this._keyPressHandled = !0), + (this._unprocessedDeadKey = !1), + 0) + ); + } + _inputEvent(e) { + if ( + e.data && + "insertText" === e.inputType && + (!e.composed || !this._keyDownSeen) && + !this.optionsService.rawOptions.screenReaderMode + ) { + if (this._keyPressHandled) return !1; + this._unprocessedDeadKey = !1; + const t = e.data; + return ( + this.coreService.triggerDataEvent(t, !0), + this.cancel(e), + !0 + ); + } + return !1; + } + resize(e, t) { + e !== this.cols || t !== this.rows + ? super.resize(e, t) + : this._charSizeService && + !this._charSizeService.hasValidSize && + this._charSizeService.measure(); + } + _afterResize(e, t) { + var i, s; + (null === (i = this._charSizeService) || + void 0 === i || + i.measure(), + null === (s = this.viewport) || + void 0 === s || + s.syncScrollArea(!0)); + } + clear() { + var e; + if (0 !== this.buffer.ybase || 0 !== this.buffer.y) { + (this.buffer.clearAllMarkers(), + this.buffer.lines.set( + 0, + this.buffer.lines.get(this.buffer.ybase + this.buffer.y), + ), + (this.buffer.lines.length = 1), + (this.buffer.ydisp = 0), + (this.buffer.ybase = 0), + (this.buffer.y = 0)); + for (let e = 1; e < this.rows; e++) + this.buffer.lines.push( + this.buffer.getBlankLine(L.DEFAULT_ATTR_DATA), + ); + (this._onScroll.fire({ + position: this.buffer.ydisp, + source: 0, + }), + null === (e = this.viewport) || void 0 === e || e.reset(), + this.refresh(0, this.rows - 1)); + } + } + reset() { + var e, t; + ((this.options.rows = this.rows), + (this.options.cols = this.cols)); + const i = this._customKeyEventHandler; + (this._setup(), + super.reset(), + null === (e = this._selectionService) || + void 0 === e || + e.reset(), + this._decorationService.reset(), + null === (t = this.viewport) || void 0 === t || t.reset(), + (this._customKeyEventHandler = i), + this.refresh(0, this.rows - 1)); + } + clearTextureAtlas() { + var e; + null === (e = this._renderService) || + void 0 === e || + e.clearTextureAtlas(); + } + _reportFocus() { + var e; + ( + null === (e = this.element) || void 0 === e + ? void 0 + : e.classList.contains("focus") + ) + ? this.coreService.triggerDataEvent(D.C0.ESC + "[I") + : this.coreService.triggerDataEvent(D.C0.ESC + "[O"); + } + _reportWindowsOptions(e) { + if (this._renderService) + switch (e) { + case T.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS: + const e = + this._renderService.dimensions.css.canvas.width.toFixed( + 0, + ), + t = + this._renderService.dimensions.css.canvas.height.toFixed( + 0, + ); + this.coreService.triggerDataEvent( + `${D.C0.ESC}[4;${t};${e}t`, + ); + break; + case T.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS: + const i = + this._renderService.dimensions.css.cell.width.toFixed( + 0, + ), + s = + this._renderService.dimensions.css.cell.height.toFixed( + 0, + ); + this.coreService.triggerDataEvent( + `${D.C0.ESC}[6;${s};${i}t`, + ); + } + } + cancel(e, t) { + if (this.options.cancelEvents || t) + return (e.preventDefault(), e.stopPropagation(), !1); + } + } + t.Terminal = P; + }, + 9924: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.TimeBasedDebouncer = void 0), + (t.TimeBasedDebouncer = class { + constructor(e, t = 1e3) { + ((this._renderCallback = e), + (this._debounceThresholdMS = t), + (this._lastRefreshMs = 0), + (this._additionalRefreshRequested = !1)); + } + dispose() { + this._refreshTimeoutID && clearTimeout(this._refreshTimeoutID); + } + refresh(e, t, i) { + ((this._rowCount = i), + (e = void 0 !== e ? e : 0), + (t = void 0 !== t ? t : this._rowCount - 1), + (this._rowStart = + void 0 !== this._rowStart + ? Math.min(this._rowStart, e) + : e), + (this._rowEnd = + void 0 !== this._rowEnd ? Math.max(this._rowEnd, t) : t)); + const s = Date.now(); + if (s - this._lastRefreshMs >= this._debounceThresholdMS) + ((this._lastRefreshMs = s), this._innerRefresh()); + else if (!this._additionalRefreshRequested) { + const e = s - this._lastRefreshMs, + t = this._debounceThresholdMS - e; + ((this._additionalRefreshRequested = !0), + (this._refreshTimeoutID = window.setTimeout(() => { + ((this._lastRefreshMs = Date.now()), + this._innerRefresh(), + (this._additionalRefreshRequested = !1), + (this._refreshTimeoutID = void 0)); + }, t))); + } + } + _innerRefresh() { + if ( + void 0 === this._rowStart || + void 0 === this._rowEnd || + void 0 === this._rowCount + ) + return; + const e = Math.max(this._rowStart, 0), + t = Math.min(this._rowEnd, this._rowCount - 1); + ((this._rowStart = void 0), + (this._rowEnd = void 0), + this._renderCallback(e, t)); + } + })); + }, + 1680: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.Viewport = void 0)); + const n = i(3656), + o = i(4725), + a = i(8460), + h = i(844), + c = i(2585); + let l = (t.Viewport = class extends h.Disposable { + constructor(e, t, i, s, r, o, h, c) { + (super(), + (this._viewportElement = e), + (this._scrollArea = t), + (this._bufferService = i), + (this._optionsService = s), + (this._charSizeService = r), + (this._renderService = o), + (this._coreBrowserService = h), + (this.scrollBarWidth = 0), + (this._currentRowHeight = 0), + (this._currentDeviceCellHeight = 0), + (this._lastRecordedBufferLength = 0), + (this._lastRecordedViewportHeight = 0), + (this._lastRecordedBufferHeight = 0), + (this._lastTouchY = 0), + (this._lastScrollTop = 0), + (this._wheelPartialScroll = 0), + (this._refreshAnimationFrame = null), + (this._ignoreNextScrollEvent = !1), + (this._smoothScrollState = { + startTime: 0, + origin: -1, + target: -1, + }), + (this._onRequestScrollLines = this.register( + new a.EventEmitter(), + )), + (this.onRequestScrollLines = this._onRequestScrollLines.event), + (this.scrollBarWidth = + this._viewportElement.offsetWidth - + this._scrollArea.offsetWidth || 15), + this.register( + (0, n.addDisposableDomListener)( + this._viewportElement, + "scroll", + this._handleScroll.bind(this), + ), + ), + (this._activeBuffer = this._bufferService.buffer), + this.register( + this._bufferService.buffers.onBufferActivate( + (e) => (this._activeBuffer = e.activeBuffer), + ), + ), + (this._renderDimensions = this._renderService.dimensions), + this.register( + this._renderService.onDimensionsChange( + (e) => (this._renderDimensions = e), + ), + ), + this._handleThemeChange(c.colors), + this.register( + c.onChangeColors((e) => this._handleThemeChange(e)), + ), + this.register( + this._optionsService.onSpecificOptionChange( + "scrollback", + () => this.syncScrollArea(), + ), + ), + setTimeout(() => this.syncScrollArea())); + } + _handleThemeChange(e) { + this._viewportElement.style.backgroundColor = e.background.css; + } + reset() { + ((this._currentRowHeight = 0), + (this._currentDeviceCellHeight = 0), + (this._lastRecordedBufferLength = 0), + (this._lastRecordedViewportHeight = 0), + (this._lastRecordedBufferHeight = 0), + (this._lastTouchY = 0), + (this._lastScrollTop = 0), + this._coreBrowserService.window.requestAnimationFrame(() => + this.syncScrollArea(), + )); + } + _refresh(e) { + if (e) + return ( + this._innerRefresh(), + void ( + null !== this._refreshAnimationFrame && + this._coreBrowserService.window.cancelAnimationFrame( + this._refreshAnimationFrame, + ) + ) + ); + null === this._refreshAnimationFrame && + (this._refreshAnimationFrame = + this._coreBrowserService.window.requestAnimationFrame(() => + this._innerRefresh(), + )); + } + _innerRefresh() { + if (this._charSizeService.height > 0) { + ((this._currentRowHeight = + this._renderService.dimensions.device.cell.height / + this._coreBrowserService.dpr), + (this._currentDeviceCellHeight = + this._renderService.dimensions.device.cell.height), + (this._lastRecordedViewportHeight = + this._viewportElement.offsetHeight)); + const e = + Math.round( + this._currentRowHeight * this._lastRecordedBufferLength, + ) + + (this._lastRecordedViewportHeight - + this._renderService.dimensions.css.canvas.height); + this._lastRecordedBufferHeight !== e && + ((this._lastRecordedBufferHeight = e), + (this._scrollArea.style.height = + this._lastRecordedBufferHeight + "px")); + } + const e = + this._bufferService.buffer.ydisp * this._currentRowHeight; + (this._viewportElement.scrollTop !== e && + ((this._ignoreNextScrollEvent = !0), + (this._viewportElement.scrollTop = e)), + (this._refreshAnimationFrame = null)); + } + syncScrollArea(e = !1) { + if ( + this._lastRecordedBufferLength !== + this._bufferService.buffer.lines.length + ) + return ( + (this._lastRecordedBufferLength = + this._bufferService.buffer.lines.length), + void this._refresh(e) + ); + (this._lastRecordedViewportHeight === + this._renderService.dimensions.css.canvas.height && + this._lastScrollTop === + this._activeBuffer.ydisp * this._currentRowHeight && + this._renderDimensions.device.cell.height === + this._currentDeviceCellHeight) || + this._refresh(e); + } + _handleScroll(e) { + if ( + ((this._lastScrollTop = this._viewportElement.scrollTop), + !this._viewportElement.offsetParent) + ) + return; + if (this._ignoreNextScrollEvent) + return ( + (this._ignoreNextScrollEvent = !1), + void this._onRequestScrollLines.fire({ + amount: 0, + suppressScrollEvent: !0, + }) + ); + const t = + Math.round(this._lastScrollTop / this._currentRowHeight) - + this._bufferService.buffer.ydisp; + this._onRequestScrollLines.fire({ + amount: t, + suppressScrollEvent: !0, + }); + } + _smoothScroll() { + if ( + this._isDisposed || + -1 === this._smoothScrollState.origin || + -1 === this._smoothScrollState.target + ) + return; + const e = this._smoothScrollPercent(); + ((this._viewportElement.scrollTop = + this._smoothScrollState.origin + + Math.round( + e * + (this._smoothScrollState.target - + this._smoothScrollState.origin), + )), + e < 1 + ? this._coreBrowserService.window.requestAnimationFrame(() => + this._smoothScroll(), + ) + : this._clearSmoothScrollState()); + } + _smoothScrollPercent() { + return this._optionsService.rawOptions.smoothScrollDuration && + this._smoothScrollState.startTime + ? Math.max( + Math.min( + (Date.now() - this._smoothScrollState.startTime) / + this._optionsService.rawOptions.smoothScrollDuration, + 1, + ), + 0, + ) + : 1; + } + _clearSmoothScrollState() { + ((this._smoothScrollState.startTime = 0), + (this._smoothScrollState.origin = -1), + (this._smoothScrollState.target = -1)); + } + _bubbleScroll(e, t) { + const i = + this._viewportElement.scrollTop + + this._lastRecordedViewportHeight; + return ( + !( + (t < 0 && 0 !== this._viewportElement.scrollTop) || + (t > 0 && i < this._lastRecordedBufferHeight) + ) || (e.cancelable && e.preventDefault(), !1) + ); + } + handleWheel(e) { + const t = this._getPixelsScrolled(e); + return ( + 0 !== t && + (this._optionsService.rawOptions.smoothScrollDuration + ? ((this._smoothScrollState.startTime = Date.now()), + this._smoothScrollPercent() < 1 + ? ((this._smoothScrollState.origin = + this._viewportElement.scrollTop), + -1 === this._smoothScrollState.target + ? (this._smoothScrollState.target = + this._viewportElement.scrollTop + t) + : (this._smoothScrollState.target += t), + (this._smoothScrollState.target = Math.max( + Math.min( + this._smoothScrollState.target, + this._viewportElement.scrollHeight, + ), + 0, + )), + this._smoothScroll()) + : this._clearSmoothScrollState()) + : (this._viewportElement.scrollTop += t), + this._bubbleScroll(e, t)) + ); + } + scrollLines(e) { + if (0 !== e) + if (this._optionsService.rawOptions.smoothScrollDuration) { + const t = e * this._currentRowHeight; + ((this._smoothScrollState.startTime = Date.now()), + this._smoothScrollPercent() < 1 + ? ((this._smoothScrollState.origin = + this._viewportElement.scrollTop), + (this._smoothScrollState.target = + this._smoothScrollState.origin + t), + (this._smoothScrollState.target = Math.max( + Math.min( + this._smoothScrollState.target, + this._viewportElement.scrollHeight, + ), + 0, + )), + this._smoothScroll()) + : this._clearSmoothScrollState()); + } else + this._onRequestScrollLines.fire({ + amount: e, + suppressScrollEvent: !1, + }); + } + _getPixelsScrolled(e) { + if (0 === e.deltaY || e.shiftKey) return 0; + let t = this._applyScrollModifier(e.deltaY, e); + return ( + e.deltaMode === WheelEvent.DOM_DELTA_LINE + ? (t *= this._currentRowHeight) + : e.deltaMode === WheelEvent.DOM_DELTA_PAGE && + (t *= this._currentRowHeight * this._bufferService.rows), + t + ); + } + getBufferElements(e, t) { + var i; + let s, + r = ""; + const n = [], + o = null != t ? t : this._bufferService.buffer.lines.length, + a = this._bufferService.buffer.lines; + for (let t = e; t < o; t++) { + const e = a.get(t); + if (!e) continue; + const o = + null === (i = a.get(t + 1)) || void 0 === i + ? void 0 + : i.isWrapped; + if ( + ((r += e.translateToString(!o)), !o || t === a.length - 1) + ) { + const e = document.createElement("div"); + ((e.textContent = r), + n.push(e), + r.length > 0 && (s = e), + (r = "")); + } + } + return { bufferElements: n, cursorElement: s }; + } + getLinesScrolled(e) { + if (0 === e.deltaY || e.shiftKey) return 0; + let t = this._applyScrollModifier(e.deltaY, e); + return ( + e.deltaMode === WheelEvent.DOM_DELTA_PIXEL + ? ((t /= this._currentRowHeight + 0), + (this._wheelPartialScroll += t), + (t = + Math.floor(Math.abs(this._wheelPartialScroll)) * + (this._wheelPartialScroll > 0 ? 1 : -1)), + (this._wheelPartialScroll %= 1)) + : e.deltaMode === WheelEvent.DOM_DELTA_PAGE && + (t *= this._bufferService.rows), + t + ); + } + _applyScrollModifier(e, t) { + const i = this._optionsService.rawOptions.fastScrollModifier; + return ("alt" === i && t.altKey) || + ("ctrl" === i && t.ctrlKey) || + ("shift" === i && t.shiftKey) + ? e * + this._optionsService.rawOptions.fastScrollSensitivity * + this._optionsService.rawOptions.scrollSensitivity + : e * this._optionsService.rawOptions.scrollSensitivity; + } + handleTouchStart(e) { + this._lastTouchY = e.touches[0].pageY; + } + handleTouchMove(e) { + const t = this._lastTouchY - e.touches[0].pageY; + return ( + (this._lastTouchY = e.touches[0].pageY), + 0 !== t && + ((this._viewportElement.scrollTop += t), + this._bubbleScroll(e, t)) + ); + } + }); + t.Viewport = l = s( + [ + r(2, c.IBufferService), + r(3, c.IOptionsService), + r(4, o.ICharSizeService), + r(5, o.IRenderService), + r(6, o.ICoreBrowserService), + r(7, o.IThemeService), + ], + l, + ); + }, + 3107: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.BufferDecorationRenderer = void 0)); + const n = i(3656), + o = i(4725), + a = i(844), + h = i(2585); + let c = (t.BufferDecorationRenderer = class extends a.Disposable { + constructor(e, t, i, s) { + (super(), + (this._screenElement = e), + (this._bufferService = t), + (this._decorationService = i), + (this._renderService = s), + (this._decorationElements = new Map()), + (this._altBufferIsActive = !1), + (this._dimensionsChanged = !1), + (this._container = document.createElement("div")), + this._container.classList.add("xterm-decoration-container"), + this._screenElement.appendChild(this._container), + this.register( + this._renderService.onRenderedViewportChange(() => + this._doRefreshDecorations(), + ), + ), + this.register( + this._renderService.onDimensionsChange(() => { + ((this._dimensionsChanged = !0), this._queueRefresh()); + }), + ), + this.register( + (0, n.addDisposableDomListener)(window, "resize", () => + this._queueRefresh(), + ), + ), + this.register( + this._bufferService.buffers.onBufferActivate(() => { + this._altBufferIsActive = + this._bufferService.buffer === + this._bufferService.buffers.alt; + }), + ), + this.register( + this._decorationService.onDecorationRegistered(() => + this._queueRefresh(), + ), + ), + this.register( + this._decorationService.onDecorationRemoved((e) => + this._removeDecoration(e), + ), + ), + this.register( + (0, a.toDisposable)(() => { + (this._container.remove(), + this._decorationElements.clear()); + }), + )); + } + _queueRefresh() { + void 0 === this._animationFrame && + (this._animationFrame = this._renderService.addRefreshCallback( + () => { + (this._doRefreshDecorations(), + (this._animationFrame = void 0)); + }, + )); + } + _doRefreshDecorations() { + for (const e of this._decorationService.decorations) + this._renderDecoration(e); + this._dimensionsChanged = !1; + } + _renderDecoration(e) { + (this._refreshStyle(e), + this._dimensionsChanged && this._refreshXPosition(e)); + } + _createElement(e) { + var t, i; + const s = document.createElement("div"); + (s.classList.add("xterm-decoration"), + s.classList.toggle( + "xterm-decoration-top-layer", + "top" === + (null === (t = null == e ? void 0 : e.options) || + void 0 === t + ? void 0 + : t.layer), + ), + (s.style.width = `${Math.round((e.options.width || 1) * this._renderService.dimensions.css.cell.width)}px`), + (s.style.height = + (e.options.height || 1) * + this._renderService.dimensions.css.cell.height + + "px"), + (s.style.top = + (e.marker.line - this._bufferService.buffers.active.ydisp) * + this._renderService.dimensions.css.cell.height + + "px"), + (s.style.lineHeight = `${this._renderService.dimensions.css.cell.height}px`)); + const r = null !== (i = e.options.x) && void 0 !== i ? i : 0; + return ( + r && r > this._bufferService.cols && (s.style.display = "none"), + this._refreshXPosition(e, s), + s + ); + } + _refreshStyle(e) { + const t = + e.marker.line - this._bufferService.buffers.active.ydisp; + if (t < 0 || t >= this._bufferService.rows) + e.element && + ((e.element.style.display = "none"), + e.onRenderEmitter.fire(e.element)); + else { + let i = this._decorationElements.get(e); + (i || + ((i = this._createElement(e)), + (e.element = i), + this._decorationElements.set(e, i), + this._container.appendChild(i), + e.onDispose(() => { + (this._decorationElements.delete(e), i.remove()); + })), + (i.style.top = + t * this._renderService.dimensions.css.cell.height + "px"), + (i.style.display = this._altBufferIsActive + ? "none" + : "block"), + e.onRenderEmitter.fire(i)); + } + } + _refreshXPosition(e, t = e.element) { + var i; + if (!t) return; + const s = null !== (i = e.options.x) && void 0 !== i ? i : 0; + "right" === (e.options.anchor || "left") + ? (t.style.right = s + ? s * this._renderService.dimensions.css.cell.width + "px" + : "") + : (t.style.left = s + ? s * this._renderService.dimensions.css.cell.width + "px" + : ""); + } + _removeDecoration(e) { + var t; + (null === (t = this._decorationElements.get(e)) || + void 0 === t || + t.remove(), + this._decorationElements.delete(e), + e.dispose()); + } + }); + t.BufferDecorationRenderer = c = s( + [ + r(1, h.IBufferService), + r(2, h.IDecorationService), + r(3, o.IRenderService), + ], + c, + ); + }, + 5871: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.ColorZoneStore = void 0), + (t.ColorZoneStore = class { + constructor() { + ((this._zones = []), + (this._zonePool = []), + (this._zonePoolIndex = 0), + (this._linePadding = { + full: 0, + left: 0, + center: 0, + right: 0, + })); + } + get zones() { + return ( + (this._zonePool.length = Math.min( + this._zonePool.length, + this._zones.length, + )), + this._zones + ); + } + clear() { + ((this._zones.length = 0), (this._zonePoolIndex = 0)); + } + addDecoration(e) { + if (e.options.overviewRulerOptions) { + for (const t of this._zones) + if ( + t.color === e.options.overviewRulerOptions.color && + t.position === e.options.overviewRulerOptions.position + ) { + if (this._lineIntersectsZone(t, e.marker.line)) return; + if ( + this._lineAdjacentToZone( + t, + e.marker.line, + e.options.overviewRulerOptions.position, + ) + ) + return void this._addLineToZone(t, e.marker.line); + } + if (this._zonePoolIndex < this._zonePool.length) + return ( + (this._zonePool[this._zonePoolIndex].color = + e.options.overviewRulerOptions.color), + (this._zonePool[this._zonePoolIndex].position = + e.options.overviewRulerOptions.position), + (this._zonePool[this._zonePoolIndex].startBufferLine = + e.marker.line), + (this._zonePool[this._zonePoolIndex].endBufferLine = + e.marker.line), + void this._zones.push( + this._zonePool[this._zonePoolIndex++], + ) + ); + (this._zones.push({ + color: e.options.overviewRulerOptions.color, + position: e.options.overviewRulerOptions.position, + startBufferLine: e.marker.line, + endBufferLine: e.marker.line, + }), + this._zonePool.push(this._zones[this._zones.length - 1]), + this._zonePoolIndex++); + } + } + setPadding(e) { + this._linePadding = e; + } + _lineIntersectsZone(e, t) { + return t >= e.startBufferLine && t <= e.endBufferLine; + } + _lineAdjacentToZone(e, t, i) { + return ( + t >= e.startBufferLine - this._linePadding[i || "full"] && + t <= e.endBufferLine + this._linePadding[i || "full"] + ); + } + _addLineToZone(e, t) { + ((e.startBufferLine = Math.min(e.startBufferLine, t)), + (e.endBufferLine = Math.max(e.endBufferLine, t))); + } + })); + }, + 5744: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.OverviewRulerRenderer = void 0)); + const n = i(5871), + o = i(3656), + a = i(4725), + h = i(844), + c = i(2585), + l = { full: 0, left: 0, center: 0, right: 0 }, + d = { full: 0, left: 0, center: 0, right: 0 }, + _ = { full: 0, left: 0, center: 0, right: 0 }; + let u = (t.OverviewRulerRenderer = class extends h.Disposable { + get _width() { + return this._optionsService.options.overviewRulerWidth || 0; + } + constructor(e, t, i, s, r, o, a) { + var c; + (super(), + (this._viewportElement = e), + (this._screenElement = t), + (this._bufferService = i), + (this._decorationService = s), + (this._renderService = r), + (this._optionsService = o), + (this._coreBrowseService = a), + (this._colorZoneStore = new n.ColorZoneStore()), + (this._shouldUpdateDimensions = !0), + (this._shouldUpdateAnchor = !0), + (this._lastKnownBufferLength = 0), + (this._canvas = document.createElement("canvas")), + this._canvas.classList.add("xterm-decoration-overview-ruler"), + this._refreshCanvasDimensions(), + null === (c = this._viewportElement.parentElement) || + void 0 === c || + c.insertBefore(this._canvas, this._viewportElement)); + const l = this._canvas.getContext("2d"); + if (!l) throw new Error("Ctx cannot be null"); + ((this._ctx = l), + this._registerDecorationListeners(), + this._registerBufferChangeListeners(), + this._registerDimensionChangeListeners(), + this.register( + (0, h.toDisposable)(() => { + var e; + null === (e = this._canvas) || void 0 === e || e.remove(); + }), + )); + } + _registerDecorationListeners() { + (this.register( + this._decorationService.onDecorationRegistered(() => + this._queueRefresh(void 0, !0), + ), + ), + this.register( + this._decorationService.onDecorationRemoved(() => + this._queueRefresh(void 0, !0), + ), + )); + } + _registerBufferChangeListeners() { + (this.register( + this._renderService.onRenderedViewportChange(() => + this._queueRefresh(), + ), + ), + this.register( + this._bufferService.buffers.onBufferActivate(() => { + this._canvas.style.display = + this._bufferService.buffer === + this._bufferService.buffers.alt + ? "none" + : "block"; + }), + ), + this.register( + this._bufferService.onScroll(() => { + this._lastKnownBufferLength !== + this._bufferService.buffers.normal.lines.length && + (this._refreshDrawHeightConstants(), + this._refreshColorZonePadding()); + }), + )); + } + _registerDimensionChangeListeners() { + (this.register( + this._renderService.onRender(() => { + (this._containerHeight && + this._containerHeight === + this._screenElement.clientHeight) || + (this._queueRefresh(!0), + (this._containerHeight = this._screenElement.clientHeight)); + }), + ), + this.register( + this._optionsService.onSpecificOptionChange( + "overviewRulerWidth", + () => this._queueRefresh(!0), + ), + ), + this.register( + (0, o.addDisposableDomListener)( + this._coreBrowseService.window, + "resize", + () => this._queueRefresh(!0), + ), + ), + this._queueRefresh(!0)); + } + _refreshDrawConstants() { + const e = Math.floor(this._canvas.width / 3), + t = Math.ceil(this._canvas.width / 3); + ((d.full = this._canvas.width), + (d.left = e), + (d.center = t), + (d.right = e), + this._refreshDrawHeightConstants(), + (_.full = 0), + (_.left = 0), + (_.center = d.left), + (_.right = d.left + d.center)); + } + _refreshDrawHeightConstants() { + l.full = Math.round(2 * this._coreBrowseService.dpr); + const e = + this._canvas.height / this._bufferService.buffer.lines.length, + t = Math.round( + Math.max(Math.min(e, 12), 6) * this._coreBrowseService.dpr, + ); + ((l.left = t), (l.center = t), (l.right = t)); + } + _refreshColorZonePadding() { + (this._colorZoneStore.setPadding({ + full: Math.floor( + (this._bufferService.buffers.active.lines.length / + (this._canvas.height - 1)) * + l.full, + ), + left: Math.floor( + (this._bufferService.buffers.active.lines.length / + (this._canvas.height - 1)) * + l.left, + ), + center: Math.floor( + (this._bufferService.buffers.active.lines.length / + (this._canvas.height - 1)) * + l.center, + ), + right: Math.floor( + (this._bufferService.buffers.active.lines.length / + (this._canvas.height - 1)) * + l.right, + ), + }), + (this._lastKnownBufferLength = + this._bufferService.buffers.normal.lines.length)); + } + _refreshCanvasDimensions() { + ((this._canvas.style.width = `${this._width}px`), + (this._canvas.width = Math.round( + this._width * this._coreBrowseService.dpr, + )), + (this._canvas.style.height = `${this._screenElement.clientHeight}px`), + (this._canvas.height = Math.round( + this._screenElement.clientHeight * + this._coreBrowseService.dpr, + )), + this._refreshDrawConstants(), + this._refreshColorZonePadding()); + } + _refreshDecorations() { + (this._shouldUpdateDimensions && this._refreshCanvasDimensions(), + this._ctx.clearRect( + 0, + 0, + this._canvas.width, + this._canvas.height, + ), + this._colorZoneStore.clear()); + for (const e of this._decorationService.decorations) + this._colorZoneStore.addDecoration(e); + this._ctx.lineWidth = 1; + const e = this._colorZoneStore.zones; + for (const t of e) + "full" !== t.position && this._renderColorZone(t); + for (const t of e) + "full" === t.position && this._renderColorZone(t); + ((this._shouldUpdateDimensions = !1), + (this._shouldUpdateAnchor = !1)); + } + _renderColorZone(e) { + ((this._ctx.fillStyle = e.color), + this._ctx.fillRect( + _[e.position || "full"], + Math.round( + (this._canvas.height - 1) * + (e.startBufferLine / + this._bufferService.buffers.active.lines.length) - + l[e.position || "full"] / 2, + ), + d[e.position || "full"], + Math.round( + (this._canvas.height - 1) * + ((e.endBufferLine - e.startBufferLine) / + this._bufferService.buffers.active.lines.length) + + l[e.position || "full"], + ), + )); + } + _queueRefresh(e, t) { + ((this._shouldUpdateDimensions = + e || this._shouldUpdateDimensions), + (this._shouldUpdateAnchor = t || this._shouldUpdateAnchor), + void 0 === this._animationFrame && + (this._animationFrame = + this._coreBrowseService.window.requestAnimationFrame(() => { + (this._refreshDecorations(), + (this._animationFrame = void 0)); + }))); + } + }); + t.OverviewRulerRenderer = u = s( + [ + r(2, c.IBufferService), + r(3, c.IDecorationService), + r(4, a.IRenderService), + r(5, c.IOptionsService), + r(6, a.ICoreBrowserService), + ], + u, + ); + }, + 2950: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CompositionHelper = void 0)); + const n = i(4725), + o = i(2585), + a = i(2584); + let h = (t.CompositionHelper = class { + get isComposing() { + return this._isComposing; + } + constructor(e, t, i, s, r, n) { + ((this._textarea = e), + (this._compositionView = t), + (this._bufferService = i), + (this._optionsService = s), + (this._coreService = r), + (this._renderService = n), + (this._isComposing = !1), + (this._isSendingComposition = !1), + (this._compositionPosition = { start: 0, end: 0 }), + (this._dataAlreadySent = "")); + } + compositionstart() { + ((this._isComposing = !0), + (this._compositionPosition.start = this._textarea.value.length), + (this._compositionView.textContent = ""), + (this._dataAlreadySent = ""), + this._compositionView.classList.add("active")); + } + compositionupdate(e) { + ((this._compositionView.textContent = e.data), + this.updateCompositionElements(), + setTimeout(() => { + this._compositionPosition.end = this._textarea.value.length; + }, 0)); + } + compositionend() { + this._finalizeComposition(!0); + } + keydown(e) { + if (this._isComposing || this._isSendingComposition) { + if (229 === e.keyCode) return !1; + if (16 === e.keyCode || 17 === e.keyCode || 18 === e.keyCode) + return !1; + this._finalizeComposition(!1); + } + return ( + 229 !== e.keyCode || (this._handleAnyTextareaChanges(), !1) + ); + } + _finalizeComposition(e) { + if ( + (this._compositionView.classList.remove("active"), + (this._isComposing = !1), + e) + ) { + const e = { + start: this._compositionPosition.start, + end: this._compositionPosition.end, + }; + ((this._isSendingComposition = !0), + setTimeout(() => { + if (this._isSendingComposition) { + let t; + ((this._isSendingComposition = !1), + (e.start += this._dataAlreadySent.length), + (t = this._isComposing + ? this._textarea.value.substring(e.start, e.end) + : this._textarea.value.substring(e.start)), + t.length > 0 && + this._coreService.triggerDataEvent(t, !0)); + } + }, 0)); + } else { + this._isSendingComposition = !1; + const e = this._textarea.value.substring( + this._compositionPosition.start, + this._compositionPosition.end, + ); + this._coreService.triggerDataEvent(e, !0); + } + } + _handleAnyTextareaChanges() { + const e = this._textarea.value; + setTimeout(() => { + if (!this._isComposing) { + const t = this._textarea.value, + i = t.replace(e, ""); + ((this._dataAlreadySent = i), + t.length > e.length + ? this._coreService.triggerDataEvent(i, !0) + : t.length < e.length + ? this._coreService.triggerDataEvent(`${a.C0.DEL}`, !0) + : t.length === e.length && + t !== e && + this._coreService.triggerDataEvent(t, !0)); + } + }, 0); + } + updateCompositionElements(e) { + if (this._isComposing) { + if (this._bufferService.buffer.isCursorInViewport) { + const e = Math.min( + this._bufferService.buffer.x, + this._bufferService.cols - 1, + ), + t = this._renderService.dimensions.css.cell.height, + i = + this._bufferService.buffer.y * + this._renderService.dimensions.css.cell.height, + s = e * this._renderService.dimensions.css.cell.width; + ((this._compositionView.style.left = s + "px"), + (this._compositionView.style.top = i + "px"), + (this._compositionView.style.height = t + "px"), + (this._compositionView.style.lineHeight = t + "px"), + (this._compositionView.style.fontFamily = + this._optionsService.rawOptions.fontFamily), + (this._compositionView.style.fontSize = + this._optionsService.rawOptions.fontSize + "px")); + const r = this._compositionView.getBoundingClientRect(); + ((this._textarea.style.left = s + "px"), + (this._textarea.style.top = i + "px"), + (this._textarea.style.width = Math.max(r.width, 1) + "px"), + (this._textarea.style.height = + Math.max(r.height, 1) + "px"), + (this._textarea.style.lineHeight = r.height + "px")); + } + e || setTimeout(() => this.updateCompositionElements(!0), 0); + } + } + }); + t.CompositionHelper = h = s( + [ + r(2, o.IBufferService), + r(3, o.IOptionsService), + r(4, o.ICoreService), + r(5, n.IRenderService), + ], + h, + ); + }, + 9806: (e, t) => { + function i(e, t, i) { + const s = i.getBoundingClientRect(), + r = e.getComputedStyle(i), + n = parseInt(r.getPropertyValue("padding-left")), + o = parseInt(r.getPropertyValue("padding-top")); + return [t.clientX - s.left - n, t.clientY - s.top - o]; + } + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.getCoords = t.getCoordsRelativeToElement = void 0), + (t.getCoordsRelativeToElement = i), + (t.getCoords = function (e, t, s, r, n, o, a, h, c) { + if (!o) return; + const l = i(e, t, s); + return l + ? ((l[0] = Math.ceil((l[0] + (c ? a / 2 : 0)) / a)), + (l[1] = Math.ceil(l[1] / h)), + (l[0] = Math.min(Math.max(l[0], 1), r + (c ? 1 : 0))), + (l[1] = Math.min(Math.max(l[1], 1), n)), + l) + : void 0; + })); + }, + 9504: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.moveToCellSequence = void 0)); + const s = i(2584); + function r(e, t, i, s) { + const r = e - n(e, i), + a = t - n(t, i), + l = + Math.abs(r - a) - + (function (e, t, i) { + let s = 0; + const r = e - n(e, i), + a = t - n(t, i); + for (let n = 0; n < Math.abs(r - a); n++) { + const a = "A" === o(e, t) ? -1 : 1, + h = i.buffer.lines.get(r + a * n); + (null == h ? void 0 : h.isWrapped) && s++; + } + return s; + })(e, t, i); + return c(l, h(o(e, t), s)); + } + function n(e, t) { + let i = 0, + s = t.buffer.lines.get(e), + r = null == s ? void 0 : s.isWrapped; + for (; r && e >= 0 && e < t.rows; ) + (i++, + (s = t.buffer.lines.get(--e)), + (r = null == s ? void 0 : s.isWrapped)); + return i; + } + function o(e, t) { + return e > t ? "A" : "B"; + } + function a(e, t, i, s, r, n) { + let o = e, + a = t, + h = ""; + for (; o !== i || a !== s; ) + ((o += r ? 1 : -1), + r && o > n.cols - 1 + ? ((h += n.buffer.translateBufferLineToString(a, !1, e, o)), + (o = 0), + (e = 0), + a++) + : !r && + o < 0 && + ((h += n.buffer.translateBufferLineToString( + a, + !1, + 0, + e + 1, + )), + (o = n.cols - 1), + (e = o), + a--)); + return h + n.buffer.translateBufferLineToString(a, !1, e, o); + } + function h(e, t) { + const i = t ? "O" : "["; + return s.C0.ESC + i + e; + } + function c(e, t) { + e = Math.floor(e); + let i = ""; + for (let s = 0; s < e; s++) i += t; + return i; + } + t.moveToCellSequence = function (e, t, i, s) { + const o = i.buffer.x, + l = i.buffer.y; + if (!i.buffer.hasScrollback) + return ( + (function (e, t, i, s, o, l) { + return 0 === r(t, s, o, l).length + ? "" + : c(a(e, t, e, t - n(t, o), !1, o).length, h("D", l)); + })(o, l, 0, t, i, s) + + r(l, t, i, s) + + (function (e, t, i, s, o, l) { + let d; + d = r(t, s, o, l).length > 0 ? s - n(s, o) : t; + const _ = s, + u = (function (e, t, i, s, o, a) { + let h; + return ( + (h = r(i, s, o, a).length > 0 ? s - n(s, o) : t), + (e < i && h <= s) || (e >= i && h < s) ? "C" : "D" + ); + })(e, t, i, s, o, l); + return c(a(e, d, i, _, "C" === u, o).length, h(u, l)); + })(o, l, e, t, i, s) + ); + let d; + if (l === t) + return ((d = o > e ? "D" : "C"), c(Math.abs(o - e), h(d, s))); + d = l > t ? "D" : "C"; + const _ = Math.abs(l - t); + return c( + (function (e, t) { + return t.cols - e; + })(l > t ? e : o, i) + + (_ - 1) * i.cols + + 1 + + ((l > t ? o : e) - 1), + h(d, s), + ); + }; + }, + 1296: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.DomRenderer = void 0)); + const n = i(3787), + o = i(2550), + a = i(2223), + h = i(6171), + c = i(4725), + l = i(8055), + d = i(8460), + _ = i(844), + u = i(2585), + f = "xterm-dom-renderer-owner-", + v = "xterm-rows", + p = "xterm-fg-", + g = "xterm-bg-", + m = "xterm-focus", + S = "xterm-selection"; + let C = 1, + b = (t.DomRenderer = class extends _.Disposable { + constructor(e, t, i, s, r, a, c, l, u, p) { + (super(), + (this._element = e), + (this._screenElement = t), + (this._viewportElement = i), + (this._linkifier2 = s), + (this._charSizeService = a), + (this._optionsService = c), + (this._bufferService = l), + (this._coreBrowserService = u), + (this._themeService = p), + (this._terminalClass = C++), + (this._rowElements = []), + (this.onRequestRedraw = this.register( + new d.EventEmitter(), + ).event), + (this._rowContainer = document.createElement("div")), + this._rowContainer.classList.add(v), + (this._rowContainer.style.lineHeight = "normal"), + this._rowContainer.setAttribute("aria-hidden", "true"), + this._refreshRowElements( + this._bufferService.cols, + this._bufferService.rows, + ), + (this._selectionContainer = document.createElement("div")), + this._selectionContainer.classList.add(S), + this._selectionContainer.setAttribute("aria-hidden", "true"), + (this.dimensions = (0, h.createRenderDimensions)()), + this._updateDimensions(), + this.register( + this._optionsService.onOptionChange(() => + this._handleOptionsChanged(), + ), + ), + this.register( + this._themeService.onChangeColors((e) => + this._injectCss(e), + ), + ), + this._injectCss(this._themeService.colors), + (this._rowFactory = r.createInstance( + n.DomRendererRowFactory, + document, + )), + this._element.classList.add(f + this._terminalClass), + this._screenElement.appendChild(this._rowContainer), + this._screenElement.appendChild(this._selectionContainer), + this.register( + this._linkifier2.onShowLinkUnderline((e) => + this._handleLinkHover(e), + ), + ), + this.register( + this._linkifier2.onHideLinkUnderline((e) => + this._handleLinkLeave(e), + ), + ), + this.register( + (0, _.toDisposable)(() => { + (this._element.classList.remove(f + this._terminalClass), + this._rowContainer.remove(), + this._selectionContainer.remove(), + this._widthCache.dispose(), + this._themeStyleElement.remove(), + this._dimensionsStyleElement.remove()); + }), + ), + (this._widthCache = new o.WidthCache(document)), + this._widthCache.setFont( + this._optionsService.rawOptions.fontFamily, + this._optionsService.rawOptions.fontSize, + this._optionsService.rawOptions.fontWeight, + this._optionsService.rawOptions.fontWeightBold, + ), + this._setDefaultSpacing()); + } + _updateDimensions() { + const e = this._coreBrowserService.dpr; + ((this.dimensions.device.char.width = + this._charSizeService.width * e), + (this.dimensions.device.char.height = Math.ceil( + this._charSizeService.height * e, + )), + (this.dimensions.device.cell.width = + this.dimensions.device.char.width + + Math.round(this._optionsService.rawOptions.letterSpacing)), + (this.dimensions.device.cell.height = Math.floor( + this.dimensions.device.char.height * + this._optionsService.rawOptions.lineHeight, + )), + (this.dimensions.device.char.left = 0), + (this.dimensions.device.char.top = 0), + (this.dimensions.device.canvas.width = + this.dimensions.device.cell.width * + this._bufferService.cols), + (this.dimensions.device.canvas.height = + this.dimensions.device.cell.height * + this._bufferService.rows), + (this.dimensions.css.canvas.width = Math.round( + this.dimensions.device.canvas.width / e, + )), + (this.dimensions.css.canvas.height = Math.round( + this.dimensions.device.canvas.height / e, + )), + (this.dimensions.css.cell.width = + this.dimensions.css.canvas.width / + this._bufferService.cols), + (this.dimensions.css.cell.height = + this.dimensions.css.canvas.height / + this._bufferService.rows)); + for (const e of this._rowElements) + ((e.style.width = `${this.dimensions.css.canvas.width}px`), + (e.style.height = `${this.dimensions.css.cell.height}px`), + (e.style.lineHeight = `${this.dimensions.css.cell.height}px`), + (e.style.overflow = "hidden")); + this._dimensionsStyleElement || + ((this._dimensionsStyleElement = + document.createElement("style")), + this._screenElement.appendChild( + this._dimensionsStyleElement, + )); + const t = `${this._terminalSelector} .${v} span { display: inline-block; height: 100%; vertical-align: top;}`; + ((this._dimensionsStyleElement.textContent = t), + (this._selectionContainer.style.height = + this._viewportElement.style.height), + (this._screenElement.style.width = `${this.dimensions.css.canvas.width}px`), + (this._screenElement.style.height = `${this.dimensions.css.canvas.height}px`)); + } + _injectCss(e) { + this._themeStyleElement || + ((this._themeStyleElement = document.createElement("style")), + this._screenElement.appendChild(this._themeStyleElement)); + let t = `${this._terminalSelector} .${v} { color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`; + ((t += `${this._terminalSelector} .${v} .xterm-dim { color: ${l.color.multiplyOpacity(e.foreground, 0.5).css};}`), + (t += `${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`), + (t += + "@keyframes blink_box_shadow_" + + this._terminalClass + + " { 50% { border-bottom-style: hidden; }}"), + (t += + "@keyframes blink_block_" + + this._terminalClass + + " { 0% {" + + ` background-color: ${e.cursor.css};` + + ` color: ${e.cursorAccent.css}; } 50% { background-color: inherit;` + + ` color: ${e.cursor.css}; }}`), + (t += + `${this._terminalSelector} .${v}.${m} .xterm-cursor.xterm-cursor-blink:not(.xterm-cursor-block) { animation: blink_box_shadow_` + + this._terminalClass + + " 1s step-end infinite;}" + + `${this._terminalSelector} .${v}.${m} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: blink_block_` + + this._terminalClass + + " 1s step-end infinite;}" + + `${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-block {` + + ` background-color: ${e.cursor.css};` + + ` color: ${e.cursorAccent.css};}` + + `${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-outline {` + + ` outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}` + + `${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-bar {` + + ` box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}` + + `${this._terminalSelector} .${v} .xterm-cursor.xterm-cursor-underline {` + + ` border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`), + (t += `${this._terminalSelector} .${S} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${S} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${S} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`)); + for (const [i, s] of e.ansi.entries()) + t += `${this._terminalSelector} .${p}${i} { color: ${s.css}; }${this._terminalSelector} .${p}${i}.xterm-dim { color: ${l.color.multiplyOpacity(s, 0.5).css}; }${this._terminalSelector} .${g}${i} { background-color: ${s.css}; }`; + ((t += `${this._terminalSelector} .${p}${a.INVERTED_DEFAULT_COLOR} { color: ${l.color.opaque(e.background).css}; }${this._terminalSelector} .${p}${a.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${l.color.multiplyOpacity(l.color.opaque(e.background), 0.5).css}; }${this._terminalSelector} .${g}${a.INVERTED_DEFAULT_COLOR} { background-color: ${e.foreground.css}; }`), + (this._themeStyleElement.textContent = t)); + } + _setDefaultSpacing() { + const e = + this.dimensions.css.cell.width - + this._widthCache.get("W", !1, !1); + ((this._rowContainer.style.letterSpacing = `${e}px`), + (this._rowFactory.defaultSpacing = e)); + } + handleDevicePixelRatioChange() { + (this._updateDimensions(), + this._widthCache.clear(), + this._setDefaultSpacing()); + } + _refreshRowElements(e, t) { + for (let e = this._rowElements.length; e <= t; e++) { + const e = document.createElement("div"); + (this._rowContainer.appendChild(e), + this._rowElements.push(e)); + } + for (; this._rowElements.length > t; ) + this._rowContainer.removeChild(this._rowElements.pop()); + } + handleResize(e, t) { + (this._refreshRowElements(e, t), this._updateDimensions()); + } + handleCharSizeChanged() { + (this._updateDimensions(), + this._widthCache.clear(), + this._setDefaultSpacing()); + } + handleBlur() { + this._rowContainer.classList.remove(m); + } + handleFocus() { + (this._rowContainer.classList.add(m), + this.renderRows( + this._bufferService.buffer.y, + this._bufferService.buffer.y, + )); + } + handleSelectionChanged(e, t, i) { + if ( + (this._selectionContainer.replaceChildren(), + this._rowFactory.handleSelectionChanged(e, t, i), + this.renderRows(0, this._bufferService.rows - 1), + !e || !t) + ) + return; + const s = e[1] - this._bufferService.buffer.ydisp, + r = t[1] - this._bufferService.buffer.ydisp, + n = Math.max(s, 0), + o = Math.min(r, this._bufferService.rows - 1); + if (n >= this._bufferService.rows || o < 0) return; + const a = document.createDocumentFragment(); + if (i) { + const i = e[0] > t[0]; + a.appendChild( + this._createSelectionElement( + n, + i ? t[0] : e[0], + i ? e[0] : t[0], + o - n + 1, + ), + ); + } else { + const i = s === n ? e[0] : 0, + h = n === r ? t[0] : this._bufferService.cols; + a.appendChild(this._createSelectionElement(n, i, h)); + const c = o - n - 1; + if ( + (a.appendChild( + this._createSelectionElement( + n + 1, + 0, + this._bufferService.cols, + c, + ), + ), + n !== o) + ) { + const e = r === o ? t[0] : this._bufferService.cols; + a.appendChild(this._createSelectionElement(o, 0, e)); + } + } + this._selectionContainer.appendChild(a); + } + _createSelectionElement(e, t, i, s = 1) { + const r = document.createElement("div"); + return ( + (r.style.height = s * this.dimensions.css.cell.height + "px"), + (r.style.top = e * this.dimensions.css.cell.height + "px"), + (r.style.left = t * this.dimensions.css.cell.width + "px"), + (r.style.width = + this.dimensions.css.cell.width * (i - t) + "px"), + r + ); + } + handleCursorMove() {} + _handleOptionsChanged() { + (this._updateDimensions(), + this._injectCss(this._themeService.colors), + this._widthCache.setFont( + this._optionsService.rawOptions.fontFamily, + this._optionsService.rawOptions.fontSize, + this._optionsService.rawOptions.fontWeight, + this._optionsService.rawOptions.fontWeightBold, + ), + this._setDefaultSpacing()); + } + clear() { + for (const e of this._rowElements) e.replaceChildren(); + } + renderRows(e, t) { + const i = this._bufferService.buffer, + s = i.ybase + i.y, + r = Math.min(i.x, this._bufferService.cols - 1), + n = this._optionsService.rawOptions.cursorBlink, + o = this._optionsService.rawOptions.cursorStyle, + a = this._optionsService.rawOptions.cursorInactiveStyle; + for (let h = e; h <= t; h++) { + const e = h + i.ydisp, + t = this._rowElements[h], + c = i.lines.get(e); + if (!t || !c) break; + t.replaceChildren( + ...this._rowFactory.createRow( + c, + e, + e === s, + o, + a, + r, + n, + this.dimensions.css.cell.width, + this._widthCache, + -1, + -1, + ), + ); + } + } + get _terminalSelector() { + return `.${f}${this._terminalClass}`; + } + _handleLinkHover(e) { + this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, !0); + } + _handleLinkLeave(e) { + this._setCellUnderline(e.x1, e.x2, e.y1, e.y2, e.cols, !1); + } + _setCellUnderline(e, t, i, s, r, n) { + (i < 0 && (e = 0), s < 0 && (t = 0)); + const o = this._bufferService.rows - 1; + ((i = Math.max(Math.min(i, o), 0)), + (s = Math.max(Math.min(s, o), 0)), + (r = Math.min(r, this._bufferService.cols))); + const a = this._bufferService.buffer, + h = a.ybase + a.y, + c = Math.min(a.x, r - 1), + l = this._optionsService.rawOptions.cursorBlink, + d = this._optionsService.rawOptions.cursorStyle, + _ = this._optionsService.rawOptions.cursorInactiveStyle; + for (let o = i; o <= s; ++o) { + const u = o + a.ydisp, + f = this._rowElements[o], + v = a.lines.get(u); + if (!f || !v) break; + f.replaceChildren( + ...this._rowFactory.createRow( + v, + u, + u === h, + d, + _, + c, + l, + this.dimensions.css.cell.width, + this._widthCache, + n ? (o === i ? e : 0) : -1, + n ? (o === s ? t : r) - 1 : -1, + ), + ); + } + } + }); + t.DomRenderer = b = s( + [ + r(4, u.IInstantiationService), + r(5, c.ICharSizeService), + r(6, u.IOptionsService), + r(7, u.IBufferService), + r(8, c.ICoreBrowserService), + r(9, c.IThemeService), + ], + b, + ); + }, + 3787: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.DomRendererRowFactory = void 0)); + const n = i(2223), + o = i(643), + a = i(511), + h = i(2585), + c = i(8055), + l = i(4725), + d = i(4269), + _ = i(6171), + u = i(3734); + let f = (t.DomRendererRowFactory = class { + constructor(e, t, i, s, r, n, o) { + ((this._document = e), + (this._characterJoinerService = t), + (this._optionsService = i), + (this._coreBrowserService = s), + (this._coreService = r), + (this._decorationService = n), + (this._themeService = o), + (this._workCell = new a.CellData()), + (this._columnSelectMode = !1), + (this.defaultSpacing = 0)); + } + handleSelectionChanged(e, t, i) { + ((this._selectionStart = e), + (this._selectionEnd = t), + (this._columnSelectMode = i)); + } + createRow(e, t, i, s, r, a, h, l, _, f, p) { + const g = [], + m = this._characterJoinerService.getJoinedCharacters(t), + S = this._themeService.colors; + let C, + b = e.getNoBgTrimmedLength(); + i && b < a + 1 && (b = a + 1); + let y = 0, + w = "", + E = 0, + k = 0, + L = 0, + D = !1, + R = 0, + x = !1, + A = 0; + const B = [], + T = -1 !== f && -1 !== p; + for (let M = 0; M < b; M++) { + e.loadCell(M, this._workCell); + let b = this._workCell.getWidth(); + if (0 === b) continue; + let O = !1, + P = M, + I = this._workCell; + if (m.length > 0 && M === m[0][0]) { + O = !0; + const t = m.shift(); + ((I = new d.JoinedCellData( + this._workCell, + e.translateToString(!0, t[0], t[1]), + t[1] - t[0], + )), + (P = t[1] - 1), + (b = I.getWidth())); + } + const H = this._isCellInSelection(M, t), + F = i && M === a, + W = T && M >= f && M <= p; + let U = !1; + this._decorationService.forEachDecorationAtCell( + M, + t, + void 0, + (e) => { + U = !0; + }, + ); + let N = I.getChars() || o.WHITESPACE_CELL_CHAR; + if ( + (" " === N && + (I.isUnderline() || I.isOverline()) && + (N = " "), + (A = b * l - _.get(N, I.isBold(), I.isItalic())), + C) + ) { + if ( + y && + ((H && x) || (!H && !x && I.bg === E)) && + ((H && x && S.selectionForeground) || I.fg === k) && + I.extended.ext === L && + W === D && + A === R && + !F && + !O && + !U + ) { + ((w += N), y++); + continue; + } + (y && (C.textContent = w), + (C = this._document.createElement("span")), + (y = 0), + (w = "")); + } else C = this._document.createElement("span"); + if ( + ((E = I.bg), + (k = I.fg), + (L = I.extended.ext), + (D = W), + (R = A), + (x = H), + O && a >= M && a <= P && (a = M), + !this._coreService.isCursorHidden && F) + ) + if ( + (B.push("xterm-cursor"), this._coreBrowserService.isFocused) + ) + (h && B.push("xterm-cursor-blink"), + B.push( + "bar" === s + ? "xterm-cursor-bar" + : "underline" === s + ? "xterm-cursor-underline" + : "xterm-cursor-block", + )); + else if (r) + switch (r) { + case "outline": + B.push("xterm-cursor-outline"); + break; + case "block": + B.push("xterm-cursor-block"); + break; + case "bar": + B.push("xterm-cursor-bar"); + break; + case "underline": + B.push("xterm-cursor-underline"); + } + if ( + (I.isBold() && B.push("xterm-bold"), + I.isItalic() && B.push("xterm-italic"), + I.isDim() && B.push("xterm-dim"), + (w = I.isInvisible() + ? o.WHITESPACE_CELL_CHAR + : I.getChars() || o.WHITESPACE_CELL_CHAR), + I.isUnderline() && + (B.push(`xterm-underline-${I.extended.underlineStyle}`), + " " === w && (w = " "), + !I.isUnderlineColorDefault())) + ) + if (I.isUnderlineColorRGB()) + C.style.textDecorationColor = `rgb(${u.AttributeData.toColorRGB(I.getUnderlineColor()).join(",")})`; + else { + let e = I.getUnderlineColor(); + (this._optionsService.rawOptions + .drawBoldTextInBrightColors && + I.isBold() && + e < 8 && + (e += 8), + (C.style.textDecorationColor = S.ansi[e].css)); + } + (I.isOverline() && + (B.push("xterm-overline"), " " === w && (w = " ")), + I.isStrikethrough() && B.push("xterm-strikethrough"), + W && (C.style.textDecoration = "underline")); + let $ = I.getFgColor(), + j = I.getFgColorMode(), + z = I.getBgColor(), + K = I.getBgColorMode(); + const q = !!I.isInverse(); + if (q) { + const e = $; + (($ = z), (z = e)); + const t = j; + ((j = K), (K = t)); + } + let V, + G, + X, + J = !1; + switch ( + (this._decorationService.forEachDecorationAtCell( + M, + t, + void 0, + (e) => { + ("top" !== e.options.layer && J) || + (e.backgroundColorRGB && + ((K = 50331648), + (z = (e.backgroundColorRGB.rgba >> 8) & 16777215), + (V = e.backgroundColorRGB)), + e.foregroundColorRGB && + ((j = 50331648), + ($ = (e.foregroundColorRGB.rgba >> 8) & 16777215), + (G = e.foregroundColorRGB)), + (J = "top" === e.options.layer)); + }, + ), + !J && + H && + ((V = this._coreBrowserService.isFocused + ? S.selectionBackgroundOpaque + : S.selectionInactiveBackgroundOpaque), + (z = (V.rgba >> 8) & 16777215), + (K = 50331648), + (J = !0), + S.selectionForeground && + ((j = 50331648), + ($ = (S.selectionForeground.rgba >> 8) & 16777215), + (G = S.selectionForeground))), + J && B.push("xterm-decoration-top"), + K) + ) { + case 16777216: + case 33554432: + ((X = S.ansi[z]), B.push(`xterm-bg-${z}`)); + break; + case 50331648: + ((X = c.rgba.toColor(z >> 16, (z >> 8) & 255, 255 & z)), + this._addStyle( + C, + `background-color:#${v((z >>> 0).toString(16), "0", 6)}`, + )); + break; + default: + q + ? ((X = S.foreground), + B.push(`xterm-bg-${n.INVERTED_DEFAULT_COLOR}`)) + : (X = S.background); + } + switch ( + (V || (I.isDim() && (V = c.color.multiplyOpacity(X, 0.5))), j) + ) { + case 16777216: + case 33554432: + (I.isBold() && + $ < 8 && + this._optionsService.rawOptions + .drawBoldTextInBrightColors && + ($ += 8), + this._applyMinimumContrast( + C, + X, + S.ansi[$], + I, + V, + void 0, + ) || B.push(`xterm-fg-${$}`)); + break; + case 50331648: + const e = c.rgba.toColor( + ($ >> 16) & 255, + ($ >> 8) & 255, + 255 & $, + ); + this._applyMinimumContrast(C, X, e, I, V, G) || + this._addStyle(C, `color:#${v($.toString(16), "0", 6)}`); + break; + default: + this._applyMinimumContrast( + C, + X, + S.foreground, + I, + V, + void 0, + ) || + (q && B.push(`xterm-fg-${n.INVERTED_DEFAULT_COLOR}`)); + } + (B.length && ((C.className = B.join(" ")), (B.length = 0)), + F || O || U ? (C.textContent = w) : y++, + A !== this.defaultSpacing && + (C.style.letterSpacing = `${A}px`), + g.push(C), + (M = P)); + } + return (C && y && (C.textContent = w), g); + } + _applyMinimumContrast(e, t, i, s, r, n) { + if ( + 1 === this._optionsService.rawOptions.minimumContrastRatio || + (0, _.excludeFromContrastRatioDemands)(s.getCode()) + ) + return !1; + const o = this._getContrastCache(s); + let a; + if ((r || n || (a = o.getColor(t.rgba, i.rgba)), void 0 === a)) { + const e = + this._optionsService.rawOptions.minimumContrastRatio / + (s.isDim() ? 2 : 1); + ((a = c.color.ensureContrastRatio(r || t, n || i, e)), + o.setColor( + (r || t).rgba, + (n || i).rgba, + null != a ? a : null, + )); + } + return !!a && (this._addStyle(e, `color:${a.css}`), !0); + } + _getContrastCache(e) { + return e.isDim() + ? this._themeService.colors.halfContrastCache + : this._themeService.colors.contrastCache; + } + _addStyle(e, t) { + e.setAttribute("style", `${e.getAttribute("style") || ""}${t};`); + } + _isCellInSelection(e, t) { + const i = this._selectionStart, + s = this._selectionEnd; + return ( + !(!i || !s) && + (this._columnSelectMode + ? i[0] <= s[0] + ? e >= i[0] && t >= i[1] && e < s[0] && t <= s[1] + : e < i[0] && t >= i[1] && e >= s[0] && t <= s[1] + : (t > i[1] && t < s[1]) || + (i[1] === s[1] && t === i[1] && e >= i[0] && e < s[0]) || + (i[1] < s[1] && t === s[1] && e < s[0]) || + (i[1] < s[1] && t === i[1] && e >= i[0])) + ); + } + }); + function v(e, t, i) { + for (; e.length < i; ) e = t + e; + return e; + } + t.DomRendererRowFactory = f = s( + [ + r(1, l.ICharacterJoinerService), + r(2, h.IOptionsService), + r(3, l.ICoreBrowserService), + r(4, h.ICoreService), + r(5, h.IDecorationService), + r(6, l.IThemeService), + ], + f, + ); + }, + 2550: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.WidthCache = void 0), + (t.WidthCache = class { + constructor(e) { + ((this._flat = new Float32Array(256)), + (this._font = ""), + (this._fontSize = 0), + (this._weight = "normal"), + (this._weightBold = "bold"), + (this._measureElements = []), + (this._container = e.createElement("div")), + (this._container.style.position = "absolute"), + (this._container.style.top = "-50000px"), + (this._container.style.width = "50000px"), + (this._container.style.whiteSpace = "pre"), + (this._container.style.fontKerning = "none")); + const t = e.createElement("span"), + i = e.createElement("span"); + i.style.fontWeight = "bold"; + const s = e.createElement("span"); + s.style.fontStyle = "italic"; + const r = e.createElement("span"); + ((r.style.fontWeight = "bold"), + (r.style.fontStyle = "italic"), + (this._measureElements = [t, i, s, r]), + this._container.appendChild(t), + this._container.appendChild(i), + this._container.appendChild(s), + this._container.appendChild(r), + e.body.appendChild(this._container), + this.clear()); + } + dispose() { + (this._container.remove(), + (this._measureElements.length = 0), + (this._holey = void 0)); + } + clear() { + (this._flat.fill(-9999), (this._holey = new Map())); + } + setFont(e, t, i, s) { + (e === this._font && + t === this._fontSize && + i === this._weight && + s === this._weightBold) || + ((this._font = e), + (this._fontSize = t), + (this._weight = i), + (this._weightBold = s), + (this._container.style.fontFamily = this._font), + (this._container.style.fontSize = `${this._fontSize}px`), + (this._measureElements[0].style.fontWeight = `${i}`), + (this._measureElements[1].style.fontWeight = `${s}`), + (this._measureElements[2].style.fontWeight = `${i}`), + (this._measureElements[3].style.fontWeight = `${s}`), + this.clear()); + } + get(e, t, i) { + let s = 0; + if (!t && !i && 1 === e.length && (s = e.charCodeAt(0)) < 256) + return -9999 !== this._flat[s] + ? this._flat[s] + : (this._flat[s] = this._measure(e, 0)); + let r = e; + (t && (r += "B"), i && (r += "I")); + let n = this._holey.get(r); + if (void 0 === n) { + let s = 0; + (t && (s |= 1), + i && (s |= 2), + (n = this._measure(e, s)), + this._holey.set(r, n)); + } + return n; + } + _measure(e, t) { + const i = this._measureElements[t]; + return ((i.textContent = e.repeat(32)), i.offsetWidth / 32); + } + })); + }, + 2223: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.TEXT_BASELINE = + t.DIM_OPACITY = + t.INVERTED_DEFAULT_COLOR = + void 0)); + const s = i(6114); + ((t.INVERTED_DEFAULT_COLOR = 257), + (t.DIM_OPACITY = 0.5), + (t.TEXT_BASELINE = + s.isFirefox || s.isLegacyEdge ? "bottom" : "ideographic")); + }, + 6171: (e, t) => { + function i(e) { + return 57508 <= e && e <= 57558; + } + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.createRenderDimensions = + t.excludeFromContrastRatioDemands = + t.isRestrictedPowerlineGlyph = + t.isPowerlineGlyph = + t.throwIfFalsy = + void 0), + (t.throwIfFalsy = function (e) { + if (!e) throw new Error("value must not be falsy"); + return e; + }), + (t.isPowerlineGlyph = i), + (t.isRestrictedPowerlineGlyph = function (e) { + return 57520 <= e && e <= 57527; + }), + (t.excludeFromContrastRatioDemands = function (e) { + return ( + i(e) || + (function (e) { + return 9472 <= e && e <= 9631; + })(e) + ); + }), + (t.createRenderDimensions = function () { + return { + css: { + canvas: { width: 0, height: 0 }, + cell: { width: 0, height: 0 }, + }, + device: { + canvas: { width: 0, height: 0 }, + cell: { width: 0, height: 0 }, + char: { width: 0, height: 0, left: 0, top: 0 }, + }, + }; + })); + }, + 456: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.SelectionModel = void 0), + (t.SelectionModel = class { + constructor(e) { + ((this._bufferService = e), + (this.isSelectAllActive = !1), + (this.selectionStartLength = 0)); + } + clearSelection() { + ((this.selectionStart = void 0), + (this.selectionEnd = void 0), + (this.isSelectAllActive = !1), + (this.selectionStartLength = 0)); + } + get finalSelectionStart() { + return this.isSelectAllActive + ? [0, 0] + : this.selectionEnd && + this.selectionStart && + this.areSelectionValuesReversed() + ? this.selectionEnd + : this.selectionStart; + } + get finalSelectionEnd() { + if (this.isSelectAllActive) + return [ + this._bufferService.cols, + this._bufferService.buffer.ybase + + this._bufferService.rows - + 1, + ]; + if (this.selectionStart) { + if (!this.selectionEnd || this.areSelectionValuesReversed()) { + const e = + this.selectionStart[0] + this.selectionStartLength; + return e > this._bufferService.cols + ? e % this._bufferService.cols == 0 + ? [ + this._bufferService.cols, + this.selectionStart[1] + + Math.floor(e / this._bufferService.cols) - + 1, + ] + : [ + e % this._bufferService.cols, + this.selectionStart[1] + + Math.floor(e / this._bufferService.cols), + ] + : [e, this.selectionStart[1]]; + } + if ( + this.selectionStartLength && + this.selectionEnd[1] === this.selectionStart[1] + ) { + const e = + this.selectionStart[0] + this.selectionStartLength; + return e > this._bufferService.cols + ? [ + e % this._bufferService.cols, + this.selectionStart[1] + + Math.floor(e / this._bufferService.cols), + ] + : [ + Math.max(e, this.selectionEnd[0]), + this.selectionEnd[1], + ]; + } + return this.selectionEnd; + } + } + areSelectionValuesReversed() { + const e = this.selectionStart, + t = this.selectionEnd; + return ( + !(!e || !t) && (e[1] > t[1] || (e[1] === t[1] && e[0] > t[0])) + ); + } + handleTrim(e) { + return ( + this.selectionStart && (this.selectionStart[1] -= e), + this.selectionEnd && (this.selectionEnd[1] -= e), + this.selectionEnd && this.selectionEnd[1] < 0 + ? (this.clearSelection(), !0) + : (this.selectionStart && + this.selectionStart[1] < 0 && + (this.selectionStart[1] = 0), + !1) + ); + } + })); + }, + 428: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CharSizeService = void 0)); + const n = i(2585), + o = i(8460), + a = i(844); + let h = (t.CharSizeService = class extends a.Disposable { + get hasValidSize() { + return this.width > 0 && this.height > 0; + } + constructor(e, t, i) { + (super(), + (this._optionsService = i), + (this.width = 0), + (this.height = 0), + (this._onCharSizeChange = this.register(new o.EventEmitter())), + (this.onCharSizeChange = this._onCharSizeChange.event), + (this._measureStrategy = new c(e, t, this._optionsService)), + this.register( + this._optionsService.onMultipleOptionChange( + ["fontFamily", "fontSize"], + () => this.measure(), + ), + )); + } + measure() { + const e = this._measureStrategy.measure(); + (e.width === this.width && e.height === this.height) || + ((this.width = e.width), + (this.height = e.height), + this._onCharSizeChange.fire()); + } + }); + t.CharSizeService = h = s([r(2, n.IOptionsService)], h); + class c { + constructor(e, t, i) { + ((this._document = e), + (this._parentElement = t), + (this._optionsService = i), + (this._result = { width: 0, height: 0 }), + (this._measureElement = this._document.createElement("span")), + this._measureElement.classList.add( + "xterm-char-measure-element", + ), + (this._measureElement.textContent = "W".repeat(32)), + this._measureElement.setAttribute("aria-hidden", "true"), + (this._measureElement.style.whiteSpace = "pre"), + (this._measureElement.style.fontKerning = "none"), + this._parentElement.appendChild(this._measureElement)); + } + measure() { + ((this._measureElement.style.fontFamily = + this._optionsService.rawOptions.fontFamily), + (this._measureElement.style.fontSize = `${this._optionsService.rawOptions.fontSize}px`)); + const e = { + height: Number(this._measureElement.offsetHeight), + width: Number(this._measureElement.offsetWidth), + }; + return ( + 0 !== e.width && + 0 !== e.height && + ((this._result.width = e.width / 32), + (this._result.height = Math.ceil(e.height))), + this._result + ); + } + } + }, + 4269: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CharacterJoinerService = t.JoinedCellData = void 0)); + const n = i(3734), + o = i(643), + a = i(511), + h = i(2585); + class c extends n.AttributeData { + constructor(e, t, i) { + (super(), + (this.content = 0), + (this.combinedData = ""), + (this.fg = e.fg), + (this.bg = e.bg), + (this.combinedData = t), + (this._width = i)); + } + isCombined() { + return 2097152; + } + getWidth() { + return this._width; + } + getChars() { + return this.combinedData; + } + getCode() { + return 2097151; + } + setFromCharData(e) { + throw new Error("not implemented"); + } + getAsCharData() { + return [ + this.fg, + this.getChars(), + this.getWidth(), + this.getCode(), + ]; + } + } + t.JoinedCellData = c; + let l = (t.CharacterJoinerService = class e { + constructor(e) { + ((this._bufferService = e), + (this._characterJoiners = []), + (this._nextCharacterJoinerId = 0), + (this._workCell = new a.CellData())); + } + register(e) { + const t = { id: this._nextCharacterJoinerId++, handler: e }; + return (this._characterJoiners.push(t), t.id); + } + deregister(e) { + for (let t = 0; t < this._characterJoiners.length; t++) + if (this._characterJoiners[t].id === e) + return (this._characterJoiners.splice(t, 1), !0); + return !1; + } + getJoinedCharacters(e) { + if (0 === this._characterJoiners.length) return []; + const t = this._bufferService.buffer.lines.get(e); + if (!t || 0 === t.length) return []; + const i = [], + s = t.translateToString(!0); + let r = 0, + n = 0, + a = 0, + h = t.getFg(0), + c = t.getBg(0); + for (let e = 0; e < t.getTrimmedLength(); e++) + if ( + (t.loadCell(e, this._workCell), + 0 !== this._workCell.getWidth()) + ) { + if (this._workCell.fg !== h || this._workCell.bg !== c) { + if (e - r > 1) { + const e = this._getJoinedRanges(s, a, n, t, r); + for (let t = 0; t < e.length; t++) i.push(e[t]); + } + ((r = e), + (a = n), + (h = this._workCell.fg), + (c = this._workCell.bg)); + } + n += + this._workCell.getChars().length || + o.WHITESPACE_CELL_CHAR.length; + } + if (this._bufferService.cols - r > 1) { + const e = this._getJoinedRanges(s, a, n, t, r); + for (let t = 0; t < e.length; t++) i.push(e[t]); + } + return i; + } + _getJoinedRanges(t, i, s, r, n) { + const o = t.substring(i, s); + let a = []; + try { + a = this._characterJoiners[0].handler(o); + } catch (e) { + console.error(e); + } + for (let t = 1; t < this._characterJoiners.length; t++) + try { + const i = this._characterJoiners[t].handler(o); + for (let t = 0; t < i.length; t++) e._mergeRanges(a, i[t]); + } catch (e) { + console.error(e); + } + return (this._stringRangesToCellRanges(a, r, n), a); + } + _stringRangesToCellRanges(e, t, i) { + let s = 0, + r = !1, + n = 0, + a = e[s]; + if (a) { + for (let h = i; h < this._bufferService.cols; h++) { + const i = t.getWidth(h), + c = t.getString(h).length || o.WHITESPACE_CELL_CHAR.length; + if (0 !== i) { + if ( + (!r && a[0] <= n && ((a[0] = h), (r = !0)), a[1] <= n) + ) { + if (((a[1] = h), (a = e[++s]), !a)) break; + a[0] <= n ? ((a[0] = h), (r = !0)) : (r = !1); + } + n += c; + } + } + a && (a[1] = this._bufferService.cols); + } + } + static _mergeRanges(e, t) { + let i = !1; + for (let s = 0; s < e.length; s++) { + const r = e[s]; + if (i) { + if (t[1] <= r[0]) return ((e[s - 1][1] = t[1]), e); + if (t[1] <= r[1]) + return ( + (e[s - 1][1] = Math.max(t[1], r[1])), + e.splice(s, 1), + e + ); + (e.splice(s, 1), s--); + } else { + if (t[1] <= r[0]) return (e.splice(s, 0, t), e); + if (t[1] <= r[1]) return ((r[0] = Math.min(t[0], r[0])), e); + t[0] < r[1] && ((r[0] = Math.min(t[0], r[0])), (i = !0)); + } + } + return (i ? (e[e.length - 1][1] = t[1]) : e.push(t), e); + } + }); + t.CharacterJoinerService = l = s([r(0, h.IBufferService)], l); + }, + 5114: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CoreBrowserService = void 0), + (t.CoreBrowserService = class { + constructor(e, t) { + ((this._textarea = e), + (this.window = t), + (this._isFocused = !1), + (this._cachedIsFocused = void 0), + this._textarea.addEventListener( + "focus", + () => (this._isFocused = !0), + ), + this._textarea.addEventListener( + "blur", + () => (this._isFocused = !1), + )); + } + get dpr() { + return this.window.devicePixelRatio; + } + get isFocused() { + return ( + void 0 === this._cachedIsFocused && + ((this._cachedIsFocused = + this._isFocused && + this._textarea.ownerDocument.hasFocus()), + queueMicrotask(() => (this._cachedIsFocused = void 0))), + this._cachedIsFocused + ); + } + })); + }, + 8934: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.MouseService = void 0)); + const n = i(4725), + o = i(9806); + let a = (t.MouseService = class { + constructor(e, t) { + ((this._renderService = e), (this._charSizeService = t)); + } + getCoords(e, t, i, s, r) { + return (0, o.getCoords)( + window, + e, + t, + i, + s, + this._charSizeService.hasValidSize, + this._renderService.dimensions.css.cell.width, + this._renderService.dimensions.css.cell.height, + r, + ); + } + getMouseReportCoords(e, t) { + const i = (0, o.getCoordsRelativeToElement)(window, e, t); + if (this._charSizeService.hasValidSize) + return ( + (i[0] = Math.min( + Math.max(i[0], 0), + this._renderService.dimensions.css.canvas.width - 1, + )), + (i[1] = Math.min( + Math.max(i[1], 0), + this._renderService.dimensions.css.canvas.height - 1, + )), + { + col: Math.floor( + i[0] / this._renderService.dimensions.css.cell.width, + ), + row: Math.floor( + i[1] / this._renderService.dimensions.css.cell.height, + ), + x: Math.floor(i[0]), + y: Math.floor(i[1]), + } + ); + } + }); + t.MouseService = a = s( + [r(0, n.IRenderService), r(1, n.ICharSizeService)], + a, + ); + }, + 3230: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.RenderService = void 0)); + const n = i(3656), + o = i(6193), + a = i(5596), + h = i(4725), + c = i(8460), + l = i(844), + d = i(7226), + _ = i(2585); + let u = (t.RenderService = class extends l.Disposable { + get dimensions() { + return this._renderer.value.dimensions; + } + constructor(e, t, i, s, r, h, _, u) { + if ( + (super(), + (this._rowCount = e), + (this._charSizeService = s), + (this._renderer = this.register(new l.MutableDisposable())), + (this._pausedResizeTask = new d.DebouncedIdleTask()), + (this._isPaused = !1), + (this._needsFullRefresh = !1), + (this._isNextRenderRedrawOnly = !0), + (this._needsSelectionRefresh = !1), + (this._canvasWidth = 0), + (this._canvasHeight = 0), + (this._selectionState = { + start: void 0, + end: void 0, + columnSelectMode: !1, + }), + (this._onDimensionsChange = this.register( + new c.EventEmitter(), + )), + (this.onDimensionsChange = this._onDimensionsChange.event), + (this._onRenderedViewportChange = this.register( + new c.EventEmitter(), + )), + (this.onRenderedViewportChange = + this._onRenderedViewportChange.event), + (this._onRender = this.register(new c.EventEmitter())), + (this.onRender = this._onRender.event), + (this._onRefreshRequest = this.register(new c.EventEmitter())), + (this.onRefreshRequest = this._onRefreshRequest.event), + (this._renderDebouncer = new o.RenderDebouncer( + _.window, + (e, t) => this._renderRows(e, t), + )), + this.register(this._renderDebouncer), + (this._screenDprMonitor = new a.ScreenDprMonitor(_.window)), + this._screenDprMonitor.setListener(() => + this.handleDevicePixelRatioChange(), + ), + this.register(this._screenDprMonitor), + this.register(h.onResize(() => this._fullRefresh())), + this.register( + h.buffers.onBufferActivate(() => { + var e; + return null === (e = this._renderer.value) || void 0 === e + ? void 0 + : e.clear(); + }), + ), + this.register( + i.onOptionChange(() => this._handleOptionsChanged()), + ), + this.register( + this._charSizeService.onCharSizeChange(() => + this.handleCharSizeChanged(), + ), + ), + this.register( + r.onDecorationRegistered(() => this._fullRefresh()), + ), + this.register(r.onDecorationRemoved(() => this._fullRefresh())), + this.register( + i.onMultipleOptionChange( + [ + "customGlyphs", + "drawBoldTextInBrightColors", + "letterSpacing", + "lineHeight", + "fontFamily", + "fontSize", + "fontWeight", + "fontWeightBold", + "minimumContrastRatio", + ], + () => { + (this.clear(), + this.handleResize(h.cols, h.rows), + this._fullRefresh()); + }, + ), + ), + this.register( + i.onMultipleOptionChange(["cursorBlink", "cursorStyle"], () => + this.refreshRows(h.buffer.y, h.buffer.y, !0), + ), + ), + this.register( + (0, n.addDisposableDomListener)(_.window, "resize", () => + this.handleDevicePixelRatioChange(), + ), + ), + this.register(u.onChangeColors(() => this._fullRefresh())), + "IntersectionObserver" in _.window) + ) { + const e = new _.window.IntersectionObserver( + (e) => this._handleIntersectionChange(e[e.length - 1]), + { threshold: 0 }, + ); + (e.observe(t), + this.register({ dispose: () => e.disconnect() })); + } + } + _handleIntersectionChange(e) { + ((this._isPaused = + void 0 === e.isIntersecting + ? 0 === e.intersectionRatio + : !e.isIntersecting), + this._isPaused || + this._charSizeService.hasValidSize || + this._charSizeService.measure(), + !this._isPaused && + this._needsFullRefresh && + (this._pausedResizeTask.flush(), + this.refreshRows(0, this._rowCount - 1), + (this._needsFullRefresh = !1))); + } + refreshRows(e, t, i = !1) { + this._isPaused + ? (this._needsFullRefresh = !0) + : (i || (this._isNextRenderRedrawOnly = !1), + this._renderDebouncer.refresh(e, t, this._rowCount)); + } + _renderRows(e, t) { + this._renderer.value && + ((e = Math.min(e, this._rowCount - 1)), + (t = Math.min(t, this._rowCount - 1)), + this._renderer.value.renderRows(e, t), + this._needsSelectionRefresh && + (this._renderer.value.handleSelectionChanged( + this._selectionState.start, + this._selectionState.end, + this._selectionState.columnSelectMode, + ), + (this._needsSelectionRefresh = !1)), + this._isNextRenderRedrawOnly || + this._onRenderedViewportChange.fire({ start: e, end: t }), + this._onRender.fire({ start: e, end: t }), + (this._isNextRenderRedrawOnly = !0)); + } + resize(e, t) { + ((this._rowCount = t), this._fireOnCanvasResize()); + } + _handleOptionsChanged() { + this._renderer.value && + (this.refreshRows(0, this._rowCount - 1), + this._fireOnCanvasResize()); + } + _fireOnCanvasResize() { + this._renderer.value && + ((this._renderer.value.dimensions.css.canvas.width === + this._canvasWidth && + this._renderer.value.dimensions.css.canvas.height === + this._canvasHeight) || + this._onDimensionsChange.fire( + this._renderer.value.dimensions, + )); + } + hasRenderer() { + return !!this._renderer.value; + } + setRenderer(e) { + ((this._renderer.value = e), + this._renderer.value.onRequestRedraw((e) => + this.refreshRows(e.start, e.end, !0), + ), + (this._needsSelectionRefresh = !0), + this._fullRefresh()); + } + addRefreshCallback(e) { + return this._renderDebouncer.addRefreshCallback(e); + } + _fullRefresh() { + this._isPaused + ? (this._needsFullRefresh = !0) + : this.refreshRows(0, this._rowCount - 1); + } + clearTextureAtlas() { + var e, t; + this._renderer.value && + (null === (t = (e = this._renderer.value).clearTextureAtlas) || + void 0 === t || + t.call(e), + this._fullRefresh()); + } + handleDevicePixelRatioChange() { + (this._charSizeService.measure(), + this._renderer.value && + (this._renderer.value.handleDevicePixelRatioChange(), + this.refreshRows(0, this._rowCount - 1))); + } + handleResize(e, t) { + this._renderer.value && + (this._isPaused + ? this._pausedResizeTask.set(() => + this._renderer.value.handleResize(e, t), + ) + : this._renderer.value.handleResize(e, t), + this._fullRefresh()); + } + handleCharSizeChanged() { + var e; + null === (e = this._renderer.value) || + void 0 === e || + e.handleCharSizeChanged(); + } + handleBlur() { + var e; + null === (e = this._renderer.value) || + void 0 === e || + e.handleBlur(); + } + handleFocus() { + var e; + null === (e = this._renderer.value) || + void 0 === e || + e.handleFocus(); + } + handleSelectionChanged(e, t, i) { + var s; + ((this._selectionState.start = e), + (this._selectionState.end = t), + (this._selectionState.columnSelectMode = i), + null === (s = this._renderer.value) || + void 0 === s || + s.handleSelectionChanged(e, t, i)); + } + handleCursorMove() { + var e; + null === (e = this._renderer.value) || + void 0 === e || + e.handleCursorMove(); + } + clear() { + var e; + null === (e = this._renderer.value) || void 0 === e || e.clear(); + } + }); + t.RenderService = u = s( + [ + r(2, _.IOptionsService), + r(3, h.ICharSizeService), + r(4, _.IDecorationService), + r(5, _.IBufferService), + r(6, h.ICoreBrowserService), + r(7, h.IThemeService), + ], + u, + ); + }, + 9312: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.SelectionService = void 0)); + const n = i(9806), + o = i(9504), + a = i(456), + h = i(4725), + c = i(8460), + l = i(844), + d = i(6114), + _ = i(4841), + u = i(511), + f = i(2585), + v = String.fromCharCode(160), + p = new RegExp(v, "g"); + let g = (t.SelectionService = class extends l.Disposable { + constructor(e, t, i, s, r, n, o, h, d) { + (super(), + (this._element = e), + (this._screenElement = t), + (this._linkifier = i), + (this._bufferService = s), + (this._coreService = r), + (this._mouseService = n), + (this._optionsService = o), + (this._renderService = h), + (this._coreBrowserService = d), + (this._dragScrollAmount = 0), + (this._enabled = !0), + (this._workCell = new u.CellData()), + (this._mouseDownTimeStamp = 0), + (this._oldHasSelection = !1), + (this._oldSelectionStart = void 0), + (this._oldSelectionEnd = void 0), + (this._onLinuxMouseSelection = this.register( + new c.EventEmitter(), + )), + (this.onLinuxMouseSelection = + this._onLinuxMouseSelection.event), + (this._onRedrawRequest = this.register(new c.EventEmitter())), + (this.onRequestRedraw = this._onRedrawRequest.event), + (this._onSelectionChange = this.register(new c.EventEmitter())), + (this.onSelectionChange = this._onSelectionChange.event), + (this._onRequestScrollLines = this.register( + new c.EventEmitter(), + )), + (this.onRequestScrollLines = this._onRequestScrollLines.event), + (this._mouseMoveListener = (e) => this._handleMouseMove(e)), + (this._mouseUpListener = (e) => this._handleMouseUp(e)), + this._coreService.onUserInput(() => { + this.hasSelection && this.clearSelection(); + }), + (this._trimListener = this._bufferService.buffer.lines.onTrim( + (e) => this._handleTrim(e), + )), + this.register( + this._bufferService.buffers.onBufferActivate((e) => + this._handleBufferActivate(e), + ), + ), + this.enable(), + (this._model = new a.SelectionModel(this._bufferService)), + (this._activeSelectionMode = 0), + this.register( + (0, l.toDisposable)(() => { + this._removeMouseDownListeners(); + }), + )); + } + reset() { + this.clearSelection(); + } + disable() { + (this.clearSelection(), (this._enabled = !1)); + } + enable() { + this._enabled = !0; + } + get selectionStart() { + return this._model.finalSelectionStart; + } + get selectionEnd() { + return this._model.finalSelectionEnd; + } + get hasSelection() { + const e = this._model.finalSelectionStart, + t = this._model.finalSelectionEnd; + return !(!e || !t || (e[0] === t[0] && e[1] === t[1])); + } + get selectionText() { + const e = this._model.finalSelectionStart, + t = this._model.finalSelectionEnd; + if (!e || !t) return ""; + const i = this._bufferService.buffer, + s = []; + if (3 === this._activeSelectionMode) { + if (e[0] === t[0]) return ""; + const r = e[0] < t[0] ? e[0] : t[0], + n = e[0] < t[0] ? t[0] : e[0]; + for (let o = e[1]; o <= t[1]; o++) { + const e = i.translateBufferLineToString(o, !0, r, n); + s.push(e); + } + } else { + const r = e[1] === t[1] ? t[0] : void 0; + s.push(i.translateBufferLineToString(e[1], !0, e[0], r)); + for (let r = e[1] + 1; r <= t[1] - 1; r++) { + const e = i.lines.get(r), + t = i.translateBufferLineToString(r, !0); + (null == e ? void 0 : e.isWrapped) + ? (s[s.length - 1] += t) + : s.push(t); + } + if (e[1] !== t[1]) { + const e = i.lines.get(t[1]), + r = i.translateBufferLineToString(t[1], !0, 0, t[0]); + e && e.isWrapped ? (s[s.length - 1] += r) : s.push(r); + } + } + return s + .map((e) => e.replace(p, " ")) + .join(d.isWindows ? "\r\n" : "\n"); + } + clearSelection() { + (this._model.clearSelection(), + this._removeMouseDownListeners(), + this.refresh(), + this._onSelectionChange.fire()); + } + refresh(e) { + (this._refreshAnimationFrame || + (this._refreshAnimationFrame = + this._coreBrowserService.window.requestAnimationFrame(() => + this._refresh(), + )), + d.isLinux && + e && + this.selectionText.length && + this._onLinuxMouseSelection.fire(this.selectionText)); + } + _refresh() { + ((this._refreshAnimationFrame = void 0), + this._onRedrawRequest.fire({ + start: this._model.finalSelectionStart, + end: this._model.finalSelectionEnd, + columnSelectMode: 3 === this._activeSelectionMode, + })); + } + _isClickInSelection(e) { + const t = this._getMouseBufferCoords(e), + i = this._model.finalSelectionStart, + s = this._model.finalSelectionEnd; + return !!(i && s && t) && this._areCoordsInSelection(t, i, s); + } + isCellInSelection(e, t) { + const i = this._model.finalSelectionStart, + s = this._model.finalSelectionEnd; + return !(!i || !s) && this._areCoordsInSelection([e, t], i, s); + } + _areCoordsInSelection(e, t, i) { + return ( + (e[1] > t[1] && e[1] < i[1]) || + (t[1] === i[1] && + e[1] === t[1] && + e[0] >= t[0] && + e[0] < i[0]) || + (t[1] < i[1] && e[1] === i[1] && e[0] < i[0]) || + (t[1] < i[1] && e[1] === t[1] && e[0] >= t[0]) + ); + } + _selectWordAtCursor(e, t) { + var i, s; + const r = + null === + (s = + null === (i = this._linkifier.currentLink) || void 0 === i + ? void 0 + : i.link) || void 0 === s + ? void 0 + : s.range; + if (r) + return ( + (this._model.selectionStart = [r.start.x - 1, r.start.y - 1]), + (this._model.selectionStartLength = (0, _.getRangeLength)( + r, + this._bufferService.cols, + )), + (this._model.selectionEnd = void 0), + !0 + ); + const n = this._getMouseBufferCoords(e); + return ( + !!n && + (this._selectWordAt(n, t), + (this._model.selectionEnd = void 0), + !0) + ); + } + selectAll() { + ((this._model.isSelectAllActive = !0), + this.refresh(), + this._onSelectionChange.fire()); + } + selectLines(e, t) { + (this._model.clearSelection(), + (e = Math.max(e, 0)), + (t = Math.min(t, this._bufferService.buffer.lines.length - 1)), + (this._model.selectionStart = [0, e]), + (this._model.selectionEnd = [this._bufferService.cols, t]), + this.refresh(), + this._onSelectionChange.fire()); + } + _handleTrim(e) { + this._model.handleTrim(e) && this.refresh(); + } + _getMouseBufferCoords(e) { + const t = this._mouseService.getCoords( + e, + this._screenElement, + this._bufferService.cols, + this._bufferService.rows, + !0, + ); + if (t) + return ( + t[0]--, + t[1]--, + (t[1] += this._bufferService.buffer.ydisp), + t + ); + } + _getMouseEventScrollAmount(e) { + let t = (0, n.getCoordsRelativeToElement)( + this._coreBrowserService.window, + e, + this._screenElement, + )[1]; + const i = this._renderService.dimensions.css.canvas.height; + return t >= 0 && t <= i + ? 0 + : (t > i && (t -= i), + (t = Math.min(Math.max(t, -50), 50)), + (t /= 50), + t / Math.abs(t) + Math.round(14 * t)); + } + shouldForceSelection(e) { + return d.isMac + ? e.altKey && + this._optionsService.rawOptions + .macOptionClickForcesSelection + : e.shiftKey; + } + handleMouseDown(e) { + if ( + ((this._mouseDownTimeStamp = e.timeStamp), + (2 !== e.button || !this.hasSelection) && 0 === e.button) + ) { + if (!this._enabled) { + if (!this.shouldForceSelection(e)) return; + e.stopPropagation(); + } + (e.preventDefault(), + (this._dragScrollAmount = 0), + this._enabled && e.shiftKey + ? this._handleIncrementalClick(e) + : 1 === e.detail + ? this._handleSingleClick(e) + : 2 === e.detail + ? this._handleDoubleClick(e) + : 3 === e.detail && this._handleTripleClick(e), + this._addMouseDownListeners(), + this.refresh(!0)); + } + } + _addMouseDownListeners() { + (this._screenElement.ownerDocument && + (this._screenElement.ownerDocument.addEventListener( + "mousemove", + this._mouseMoveListener, + ), + this._screenElement.ownerDocument.addEventListener( + "mouseup", + this._mouseUpListener, + )), + (this._dragScrollIntervalTimer = + this._coreBrowserService.window.setInterval( + () => this._dragScroll(), + 50, + ))); + } + _removeMouseDownListeners() { + (this._screenElement.ownerDocument && + (this._screenElement.ownerDocument.removeEventListener( + "mousemove", + this._mouseMoveListener, + ), + this._screenElement.ownerDocument.removeEventListener( + "mouseup", + this._mouseUpListener, + )), + this._coreBrowserService.window.clearInterval( + this._dragScrollIntervalTimer, + ), + (this._dragScrollIntervalTimer = void 0)); + } + _handleIncrementalClick(e) { + this._model.selectionStart && + (this._model.selectionEnd = this._getMouseBufferCoords(e)); + } + _handleSingleClick(e) { + if ( + ((this._model.selectionStartLength = 0), + (this._model.isSelectAllActive = !1), + (this._activeSelectionMode = this.shouldColumnSelect(e) + ? 3 + : 0), + (this._model.selectionStart = this._getMouseBufferCoords(e)), + !this._model.selectionStart) + ) + return; + this._model.selectionEnd = void 0; + const t = this._bufferService.buffer.lines.get( + this._model.selectionStart[1], + ); + t && + t.length !== this._model.selectionStart[0] && + 0 === t.hasWidth(this._model.selectionStart[0]) && + this._model.selectionStart[0]++; + } + _handleDoubleClick(e) { + this._selectWordAtCursor(e, !0) && + (this._activeSelectionMode = 1); + } + _handleTripleClick(e) { + const t = this._getMouseBufferCoords(e); + t && ((this._activeSelectionMode = 2), this._selectLineAt(t[1])); + } + shouldColumnSelect(e) { + return ( + e.altKey && + !( + d.isMac && + this._optionsService.rawOptions.macOptionClickForcesSelection + ) + ); + } + _handleMouseMove(e) { + if ((e.stopImmediatePropagation(), !this._model.selectionStart)) + return; + const t = this._model.selectionEnd + ? [this._model.selectionEnd[0], this._model.selectionEnd[1]] + : null; + if ( + ((this._model.selectionEnd = this._getMouseBufferCoords(e)), + !this._model.selectionEnd) + ) + return void this.refresh(!0); + (2 === this._activeSelectionMode + ? this._model.selectionEnd[1] < this._model.selectionStart[1] + ? (this._model.selectionEnd[0] = 0) + : (this._model.selectionEnd[0] = this._bufferService.cols) + : 1 === this._activeSelectionMode && + this._selectToWordAt(this._model.selectionEnd), + (this._dragScrollAmount = this._getMouseEventScrollAmount(e)), + 3 !== this._activeSelectionMode && + (this._dragScrollAmount > 0 + ? (this._model.selectionEnd[0] = this._bufferService.cols) + : this._dragScrollAmount < 0 && + (this._model.selectionEnd[0] = 0))); + const i = this._bufferService.buffer; + if (this._model.selectionEnd[1] < i.lines.length) { + const e = i.lines.get(this._model.selectionEnd[1]); + e && + 0 === e.hasWidth(this._model.selectionEnd[0]) && + this._model.selectionEnd[0]++; + } + (t && + t[0] === this._model.selectionEnd[0] && + t[1] === this._model.selectionEnd[1]) || + this.refresh(!0); + } + _dragScroll() { + if ( + this._model.selectionEnd && + this._model.selectionStart && + this._dragScrollAmount + ) { + this._onRequestScrollLines.fire({ + amount: this._dragScrollAmount, + suppressScrollEvent: !1, + }); + const e = this._bufferService.buffer; + (this._dragScrollAmount > 0 + ? (3 !== this._activeSelectionMode && + (this._model.selectionEnd[0] = this._bufferService.cols), + (this._model.selectionEnd[1] = Math.min( + e.ydisp + this._bufferService.rows, + e.lines.length - 1, + ))) + : (3 !== this._activeSelectionMode && + (this._model.selectionEnd[0] = 0), + (this._model.selectionEnd[1] = e.ydisp)), + this.refresh()); + } + } + _handleMouseUp(e) { + const t = e.timeStamp - this._mouseDownTimeStamp; + if ( + (this._removeMouseDownListeners(), + this.selectionText.length <= 1 && + t < 500 && + e.altKey && + this._optionsService.rawOptions.altClickMovesCursor) + ) { + if ( + this._bufferService.buffer.ybase === + this._bufferService.buffer.ydisp + ) { + const t = this._mouseService.getCoords( + e, + this._element, + this._bufferService.cols, + this._bufferService.rows, + !1, + ); + if (t && void 0 !== t[0] && void 0 !== t[1]) { + const e = (0, o.moveToCellSequence)( + t[0] - 1, + t[1] - 1, + this._bufferService, + this._coreService.decPrivateModes.applicationCursorKeys, + ); + this._coreService.triggerDataEvent(e, !0); + } + } + } else this._fireEventIfSelectionChanged(); + } + _fireEventIfSelectionChanged() { + const e = this._model.finalSelectionStart, + t = this._model.finalSelectionEnd, + i = !(!e || !t || (e[0] === t[0] && e[1] === t[1])); + i + ? e && + t && + ((this._oldSelectionStart && + this._oldSelectionEnd && + e[0] === this._oldSelectionStart[0] && + e[1] === this._oldSelectionStart[1] && + t[0] === this._oldSelectionEnd[0] && + t[1] === this._oldSelectionEnd[1]) || + this._fireOnSelectionChange(e, t, i)) + : this._oldHasSelection && this._fireOnSelectionChange(e, t, i); + } + _fireOnSelectionChange(e, t, i) { + ((this._oldSelectionStart = e), + (this._oldSelectionEnd = t), + (this._oldHasSelection = i), + this._onSelectionChange.fire()); + } + _handleBufferActivate(e) { + (this.clearSelection(), + this._trimListener.dispose(), + (this._trimListener = e.activeBuffer.lines.onTrim((e) => + this._handleTrim(e), + ))); + } + _convertViewportColToCharacterIndex(e, t) { + let i = t; + for (let s = 0; t >= s; s++) { + const r = e.loadCell(s, this._workCell).getChars().length; + 0 === this._workCell.getWidth() + ? i-- + : r > 1 && t !== s && (i += r - 1); + } + return i; + } + setSelection(e, t, i) { + (this._model.clearSelection(), + this._removeMouseDownListeners(), + (this._model.selectionStart = [e, t]), + (this._model.selectionStartLength = i), + this.refresh(), + this._fireEventIfSelectionChanged()); + } + rightClickSelect(e) { + this._isClickInSelection(e) || + (this._selectWordAtCursor(e, !1) && this.refresh(!0), + this._fireEventIfSelectionChanged()); + } + _getWordAt(e, t, i = !0, s = !0) { + if (e[0] >= this._bufferService.cols) return; + const r = this._bufferService.buffer, + n = r.lines.get(e[1]); + if (!n) return; + const o = r.translateBufferLineToString(e[1], !1); + let a = this._convertViewportColToCharacterIndex(n, e[0]), + h = a; + const c = e[0] - a; + let l = 0, + d = 0, + _ = 0, + u = 0; + if (" " === o.charAt(a)) { + for (; a > 0 && " " === o.charAt(a - 1); ) a--; + for (; h < o.length && " " === o.charAt(h + 1); ) h++; + } else { + let t = e[0], + i = e[0]; + (0 === n.getWidth(t) && (l++, t--), + 2 === n.getWidth(i) && (d++, i++)); + const s = n.getString(i).length; + for ( + s > 1 && ((u += s - 1), (h += s - 1)); + t > 0 && + a > 0 && + !this._isCharWordSeparator(n.loadCell(t - 1, this._workCell)); + + ) { + n.loadCell(t - 1, this._workCell); + const e = this._workCell.getChars().length; + (0 === this._workCell.getWidth() + ? (l++, t--) + : e > 1 && ((_ += e - 1), (a -= e - 1)), + a--, + t--); + } + for ( + ; + i < n.length && + h + 1 < o.length && + !this._isCharWordSeparator(n.loadCell(i + 1, this._workCell)); + + ) { + n.loadCell(i + 1, this._workCell); + const e = this._workCell.getChars().length; + (2 === this._workCell.getWidth() + ? (d++, i++) + : e > 1 && ((u += e - 1), (h += e - 1)), + h++, + i++); + } + } + h++; + let f = a + c - l + _, + v = Math.min(this._bufferService.cols, h - a + l + d - _ - u); + if (t || "" !== o.slice(a, h).trim()) { + if (i && 0 === f && 32 !== n.getCodePoint(0)) { + const t = r.lines.get(e[1] - 1); + if ( + t && + n.isWrapped && + 32 !== t.getCodePoint(this._bufferService.cols - 1) + ) { + const t = this._getWordAt( + [this._bufferService.cols - 1, e[1] - 1], + !1, + !0, + !1, + ); + if (t) { + const e = this._bufferService.cols - t.start; + ((f -= e), (v += e)); + } + } + } + if ( + s && + f + v === this._bufferService.cols && + 32 !== n.getCodePoint(this._bufferService.cols - 1) + ) { + const t = r.lines.get(e[1] + 1); + if ( + (null == t ? void 0 : t.isWrapped) && + 32 !== t.getCodePoint(0) + ) { + const t = this._getWordAt([0, e[1] + 1], !1, !1, !0); + t && (v += t.length); + } + } + return { start: f, length: v }; + } + } + _selectWordAt(e, t) { + const i = this._getWordAt(e, t); + if (i) { + for (; i.start < 0; ) + ((i.start += this._bufferService.cols), e[1]--); + ((this._model.selectionStart = [i.start, e[1]]), + (this._model.selectionStartLength = i.length)); + } + } + _selectToWordAt(e) { + const t = this._getWordAt(e, !0); + if (t) { + let i = e[1]; + for (; t.start < 0; ) + ((t.start += this._bufferService.cols), i--); + if (!this._model.areSelectionValuesReversed()) + for (; t.start + t.length > this._bufferService.cols; ) + ((t.length -= this._bufferService.cols), i++); + this._model.selectionEnd = [ + this._model.areSelectionValuesReversed() + ? t.start + : t.start + t.length, + i, + ]; + } + } + _isCharWordSeparator(e) { + return ( + 0 !== e.getWidth() && + this._optionsService.rawOptions.wordSeparator.indexOf( + e.getChars(), + ) >= 0 + ); + } + _selectLineAt(e) { + const t = this._bufferService.buffer.getWrappedRangeForLine(e), + i = { + start: { x: 0, y: t.first }, + end: { x: this._bufferService.cols - 1, y: t.last }, + }; + ((this._model.selectionStart = [0, t.first]), + (this._model.selectionEnd = void 0), + (this._model.selectionStartLength = (0, _.getRangeLength)( + i, + this._bufferService.cols, + ))); + } + }); + t.SelectionService = g = s( + [ + r(3, f.IBufferService), + r(4, f.ICoreService), + r(5, h.IMouseService), + r(6, f.IOptionsService), + r(7, h.IRenderService), + r(8, h.ICoreBrowserService), + ], + g, + ); + }, + 4725: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.IThemeService = + t.ICharacterJoinerService = + t.ISelectionService = + t.IRenderService = + t.IMouseService = + t.ICoreBrowserService = + t.ICharSizeService = + void 0)); + const s = i(8343); + ((t.ICharSizeService = (0, s.createDecorator)("CharSizeService")), + (t.ICoreBrowserService = (0, s.createDecorator)( + "CoreBrowserService", + )), + (t.IMouseService = (0, s.createDecorator)("MouseService")), + (t.IRenderService = (0, s.createDecorator)("RenderService")), + (t.ISelectionService = (0, s.createDecorator)("SelectionService")), + (t.ICharacterJoinerService = (0, s.createDecorator)( + "CharacterJoinerService", + )), + (t.IThemeService = (0, s.createDecorator)("ThemeService"))); + }, + 6731: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.ThemeService = t.DEFAULT_ANSI_COLORS = void 0)); + const n = i(7239), + o = i(8055), + a = i(8460), + h = i(844), + c = i(2585), + l = o.css.toColor("#ffffff"), + d = o.css.toColor("#000000"), + _ = o.css.toColor("#ffffff"), + u = o.css.toColor("#000000"), + f = { css: "rgba(255, 255, 255, 0.3)", rgba: 4294967117 }; + t.DEFAULT_ANSI_COLORS = Object.freeze( + (() => { + const e = [ + o.css.toColor("#2e3436"), + o.css.toColor("#cc0000"), + o.css.toColor("#4e9a06"), + o.css.toColor("#c4a000"), + o.css.toColor("#3465a4"), + o.css.toColor("#75507b"), + o.css.toColor("#06989a"), + o.css.toColor("#d3d7cf"), + o.css.toColor("#555753"), + o.css.toColor("#ef2929"), + o.css.toColor("#8ae234"), + o.css.toColor("#fce94f"), + o.css.toColor("#729fcf"), + o.css.toColor("#ad7fa8"), + o.css.toColor("#34e2e2"), + o.css.toColor("#eeeeec"), + ], + t = [0, 95, 135, 175, 215, 255]; + for (let i = 0; i < 216; i++) { + const s = t[(i / 36) % 6 | 0], + r = t[(i / 6) % 6 | 0], + n = t[i % 6]; + e.push({ + css: o.channels.toCss(s, r, n), + rgba: o.channels.toRgba(s, r, n), + }); + } + for (let t = 0; t < 24; t++) { + const i = 8 + 10 * t; + e.push({ + css: o.channels.toCss(i, i, i), + rgba: o.channels.toRgba(i, i, i), + }); + } + return e; + })(), + ); + let v = (t.ThemeService = class extends h.Disposable { + get colors() { + return this._colors; + } + constructor(e) { + (super(), + (this._optionsService = e), + (this._contrastCache = new n.ColorContrastCache()), + (this._halfContrastCache = new n.ColorContrastCache()), + (this._onChangeColors = this.register(new a.EventEmitter())), + (this.onChangeColors = this._onChangeColors.event), + (this._colors = { + foreground: l, + background: d, + cursor: _, + cursorAccent: u, + selectionForeground: void 0, + selectionBackgroundTransparent: f, + selectionBackgroundOpaque: o.color.blend(d, f), + selectionInactiveBackgroundTransparent: f, + selectionInactiveBackgroundOpaque: o.color.blend(d, f), + ansi: t.DEFAULT_ANSI_COLORS.slice(), + contrastCache: this._contrastCache, + halfContrastCache: this._halfContrastCache, + }), + this._updateRestoreColors(), + this._setTheme(this._optionsService.rawOptions.theme), + this.register( + this._optionsService.onSpecificOptionChange( + "minimumContrastRatio", + () => this._contrastCache.clear(), + ), + ), + this.register( + this._optionsService.onSpecificOptionChange("theme", () => + this._setTheme(this._optionsService.rawOptions.theme), + ), + )); + } + _setTheme(e = {}) { + const i = this._colors; + if ( + ((i.foreground = p(e.foreground, l)), + (i.background = p(e.background, d)), + (i.cursor = p(e.cursor, _)), + (i.cursorAccent = p(e.cursorAccent, u)), + (i.selectionBackgroundTransparent = p( + e.selectionBackground, + f, + )), + (i.selectionBackgroundOpaque = o.color.blend( + i.background, + i.selectionBackgroundTransparent, + )), + (i.selectionInactiveBackgroundTransparent = p( + e.selectionInactiveBackground, + i.selectionBackgroundTransparent, + )), + (i.selectionInactiveBackgroundOpaque = o.color.blend( + i.background, + i.selectionInactiveBackgroundTransparent, + )), + (i.selectionForeground = e.selectionForeground + ? p(e.selectionForeground, o.NULL_COLOR) + : void 0), + i.selectionForeground === o.NULL_COLOR && + (i.selectionForeground = void 0), + o.color.isOpaque(i.selectionBackgroundTransparent)) + ) { + const e = 0.3; + i.selectionBackgroundTransparent = o.color.opacity( + i.selectionBackgroundTransparent, + e, + ); + } + if (o.color.isOpaque(i.selectionInactiveBackgroundTransparent)) { + const e = 0.3; + i.selectionInactiveBackgroundTransparent = o.color.opacity( + i.selectionInactiveBackgroundTransparent, + e, + ); + } + if ( + ((i.ansi = t.DEFAULT_ANSI_COLORS.slice()), + (i.ansi[0] = p(e.black, t.DEFAULT_ANSI_COLORS[0])), + (i.ansi[1] = p(e.red, t.DEFAULT_ANSI_COLORS[1])), + (i.ansi[2] = p(e.green, t.DEFAULT_ANSI_COLORS[2])), + (i.ansi[3] = p(e.yellow, t.DEFAULT_ANSI_COLORS[3])), + (i.ansi[4] = p(e.blue, t.DEFAULT_ANSI_COLORS[4])), + (i.ansi[5] = p(e.magenta, t.DEFAULT_ANSI_COLORS[5])), + (i.ansi[6] = p(e.cyan, t.DEFAULT_ANSI_COLORS[6])), + (i.ansi[7] = p(e.white, t.DEFAULT_ANSI_COLORS[7])), + (i.ansi[8] = p(e.brightBlack, t.DEFAULT_ANSI_COLORS[8])), + (i.ansi[9] = p(e.brightRed, t.DEFAULT_ANSI_COLORS[9])), + (i.ansi[10] = p(e.brightGreen, t.DEFAULT_ANSI_COLORS[10])), + (i.ansi[11] = p(e.brightYellow, t.DEFAULT_ANSI_COLORS[11])), + (i.ansi[12] = p(e.brightBlue, t.DEFAULT_ANSI_COLORS[12])), + (i.ansi[13] = p(e.brightMagenta, t.DEFAULT_ANSI_COLORS[13])), + (i.ansi[14] = p(e.brightCyan, t.DEFAULT_ANSI_COLORS[14])), + (i.ansi[15] = p(e.brightWhite, t.DEFAULT_ANSI_COLORS[15])), + e.extendedAnsi) + ) { + const s = Math.min(i.ansi.length - 16, e.extendedAnsi.length); + for (let r = 0; r < s; r++) + i.ansi[r + 16] = p( + e.extendedAnsi[r], + t.DEFAULT_ANSI_COLORS[r + 16], + ); + } + (this._contrastCache.clear(), + this._halfContrastCache.clear(), + this._updateRestoreColors(), + this._onChangeColors.fire(this.colors)); + } + restoreColor(e) { + (this._restoreColor(e), this._onChangeColors.fire(this.colors)); + } + _restoreColor(e) { + if (void 0 !== e) + switch (e) { + case 256: + this._colors.foreground = this._restoreColors.foreground; + break; + case 257: + this._colors.background = this._restoreColors.background; + break; + case 258: + this._colors.cursor = this._restoreColors.cursor; + break; + default: + this._colors.ansi[e] = this._restoreColors.ansi[e]; + } + else + for (let e = 0; e < this._restoreColors.ansi.length; ++e) + this._colors.ansi[e] = this._restoreColors.ansi[e]; + } + modifyColors(e) { + (e(this._colors), this._onChangeColors.fire(this.colors)); + } + _updateRestoreColors() { + this._restoreColors = { + foreground: this._colors.foreground, + background: this._colors.background, + cursor: this._colors.cursor, + ansi: this._colors.ansi.slice(), + }; + } + }); + function p(e, t) { + if (void 0 !== e) + try { + return o.css.toColor(e); + } catch (e) {} + return t; + } + t.ThemeService = v = s([r(0, c.IOptionsService)], v); + }, + 6349: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CircularList = void 0)); + const s = i(8460), + r = i(844); + class n extends r.Disposable { + constructor(e) { + (super(), + (this._maxLength = e), + (this.onDeleteEmitter = this.register(new s.EventEmitter())), + (this.onDelete = this.onDeleteEmitter.event), + (this.onInsertEmitter = this.register(new s.EventEmitter())), + (this.onInsert = this.onInsertEmitter.event), + (this.onTrimEmitter = this.register(new s.EventEmitter())), + (this.onTrim = this.onTrimEmitter.event), + (this._array = new Array(this._maxLength)), + (this._startIndex = 0), + (this._length = 0)); + } + get maxLength() { + return this._maxLength; + } + set maxLength(e) { + if (this._maxLength === e) return; + const t = new Array(e); + for (let i = 0; i < Math.min(e, this.length); i++) + t[i] = this._array[this._getCyclicIndex(i)]; + ((this._array = t), + (this._maxLength = e), + (this._startIndex = 0)); + } + get length() { + return this._length; + } + set length(e) { + if (e > this._length) + for (let t = this._length; t < e; t++) this._array[t] = void 0; + this._length = e; + } + get(e) { + return this._array[this._getCyclicIndex(e)]; + } + set(e, t) { + this._array[this._getCyclicIndex(e)] = t; + } + push(e) { + ((this._array[this._getCyclicIndex(this._length)] = e), + this._length === this._maxLength + ? ((this._startIndex = ++this._startIndex % this._maxLength), + this.onTrimEmitter.fire(1)) + : this._length++); + } + recycle() { + if (this._length !== this._maxLength) + throw new Error("Can only recycle when the buffer is full"); + return ( + (this._startIndex = ++this._startIndex % this._maxLength), + this.onTrimEmitter.fire(1), + this._array[this._getCyclicIndex(this._length - 1)] + ); + } + get isFull() { + return this._length === this._maxLength; + } + pop() { + return this._array[this._getCyclicIndex(this._length-- - 1)]; + } + splice(e, t, ...i) { + if (t) { + for (let i = e; i < this._length - t; i++) + this._array[this._getCyclicIndex(i)] = + this._array[this._getCyclicIndex(i + t)]; + ((this._length -= t), + this.onDeleteEmitter.fire({ index: e, amount: t })); + } + for (let t = this._length - 1; t >= e; t--) + this._array[this._getCyclicIndex(t + i.length)] = + this._array[this._getCyclicIndex(t)]; + for (let t = 0; t < i.length; t++) + this._array[this._getCyclicIndex(e + t)] = i[t]; + if ( + (i.length && + this.onInsertEmitter.fire({ index: e, amount: i.length }), + this._length + i.length > this._maxLength) + ) { + const e = this._length + i.length - this._maxLength; + ((this._startIndex += e), + (this._length = this._maxLength), + this.onTrimEmitter.fire(e)); + } else this._length += i.length; + } + trimStart(e) { + (e > this._length && (e = this._length), + (this._startIndex += e), + (this._length -= e), + this.onTrimEmitter.fire(e)); + } + shiftElements(e, t, i) { + if (!(t <= 0)) { + if (e < 0 || e >= this._length) + throw new Error("start argument out of range"); + if (e + i < 0) + throw new Error( + "Cannot shift elements in list beyond index 0", + ); + if (i > 0) { + for (let s = t - 1; s >= 0; s--) + this.set(e + s + i, this.get(e + s)); + const s = e + t + i - this._length; + if (s > 0) + for (this._length += s; this._length > this._maxLength; ) + (this._length--, + this._startIndex++, + this.onTrimEmitter.fire(1)); + } else + for (let s = 0; s < t; s++) + this.set(e + s + i, this.get(e + s)); + } + } + _getCyclicIndex(e) { + return (this._startIndex + e) % this._maxLength; + } + } + t.CircularList = n; + }, + 1439: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.clone = void 0), + (t.clone = function e(t, i = 5) { + if ("object" != typeof t) return t; + const s = Array.isArray(t) ? [] : {}; + for (const r in t) s[r] = i <= 1 ? t[r] : t[r] && e(t[r], i - 1); + return s; + })); + }, + 8055: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.contrastRatio = + t.toPaddedHex = + t.rgba = + t.rgb = + t.css = + t.color = + t.channels = + t.NULL_COLOR = + void 0)); + const s = i(6114); + let r = 0, + n = 0, + o = 0, + a = 0; + var h, c, l, d, _; + function u(e) { + const t = e.toString(16); + return t.length < 2 ? "0" + t : t; + } + function f(e, t) { + return e < t ? (t + 0.05) / (e + 0.05) : (e + 0.05) / (t + 0.05); + } + ((t.NULL_COLOR = { css: "#00000000", rgba: 0 }), + (function (e) { + ((e.toCss = function (e, t, i, s) { + return void 0 !== s + ? `#${u(e)}${u(t)}${u(i)}${u(s)}` + : `#${u(e)}${u(t)}${u(i)}`; + }), + (e.toRgba = function (e, t, i, s = 255) { + return ((e << 24) | (t << 16) | (i << 8) | s) >>> 0; + })); + })(h || (t.channels = h = {})), + (function (e) { + function t(e, t) { + return ( + (a = Math.round(255 * t)), + ([r, n, o] = _.toChannels(e.rgba)), + { css: h.toCss(r, n, o, a), rgba: h.toRgba(r, n, o, a) } + ); + } + ((e.blend = function (e, t) { + if (((a = (255 & t.rgba) / 255), 1 === a)) + return { css: t.css, rgba: t.rgba }; + const i = (t.rgba >> 24) & 255, + s = (t.rgba >> 16) & 255, + c = (t.rgba >> 8) & 255, + l = (e.rgba >> 24) & 255, + d = (e.rgba >> 16) & 255, + _ = (e.rgba >> 8) & 255; + return ( + (r = l + Math.round((i - l) * a)), + (n = d + Math.round((s - d) * a)), + (o = _ + Math.round((c - _) * a)), + { css: h.toCss(r, n, o), rgba: h.toRgba(r, n, o) } + ); + }), + (e.isOpaque = function (e) { + return 255 == (255 & e.rgba); + }), + (e.ensureContrastRatio = function (e, t, i) { + const s = _.ensureContrastRatio(e.rgba, t.rgba, i); + if (s) + return _.toColor( + (s >> 24) & 255, + (s >> 16) & 255, + (s >> 8) & 255, + ); + }), + (e.opaque = function (e) { + const t = (255 | e.rgba) >>> 0; + return ( + ([r, n, o] = _.toChannels(t)), + { css: h.toCss(r, n, o), rgba: t } + ); + }), + (e.opacity = t), + (e.multiplyOpacity = function (e, i) { + return ((a = 255 & e.rgba), t(e, (a * i) / 255)); + }), + (e.toColorRGB = function (e) { + return [ + (e.rgba >> 24) & 255, + (e.rgba >> 16) & 255, + (e.rgba >> 8) & 255, + ]; + })); + })(c || (t.color = c = {})), + (function (e) { + let t, i; + if (!s.isNode) { + const e = document.createElement("canvas"); + ((e.width = 1), (e.height = 1)); + const s = e.getContext("2d", { willReadFrequently: !0 }); + s && + ((t = s), + (t.globalCompositeOperation = "copy"), + (i = t.createLinearGradient(0, 0, 1, 1))); + } + e.toColor = function (e) { + if (e.match(/#[\da-f]{3,8}/i)) + switch (e.length) { + case 4: + return ( + (r = parseInt(e.slice(1, 2).repeat(2), 16)), + (n = parseInt(e.slice(2, 3).repeat(2), 16)), + (o = parseInt(e.slice(3, 4).repeat(2), 16)), + _.toColor(r, n, o) + ); + case 5: + return ( + (r = parseInt(e.slice(1, 2).repeat(2), 16)), + (n = parseInt(e.slice(2, 3).repeat(2), 16)), + (o = parseInt(e.slice(3, 4).repeat(2), 16)), + (a = parseInt(e.slice(4, 5).repeat(2), 16)), + _.toColor(r, n, o, a) + ); + case 7: + return { + css: e, + rgba: ((parseInt(e.slice(1), 16) << 8) | 255) >>> 0, + }; + case 9: + return { css: e, rgba: parseInt(e.slice(1), 16) >>> 0 }; + } + const s = e.match( + /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/, + ); + if (s) + return ( + (r = parseInt(s[1])), + (n = parseInt(s[2])), + (o = parseInt(s[3])), + (a = Math.round( + 255 * (void 0 === s[5] ? 1 : parseFloat(s[5])), + )), + _.toColor(r, n, o, a) + ); + if (!t || !i) + throw new Error("css.toColor: Unsupported css format"); + if ( + ((t.fillStyle = i), + (t.fillStyle = e), + "string" != typeof t.fillStyle) + ) + throw new Error("css.toColor: Unsupported css format"); + if ( + (t.fillRect(0, 0, 1, 1), + ([r, n, o, a] = t.getImageData(0, 0, 1, 1).data), + 255 !== a) + ) + throw new Error("css.toColor: Unsupported css format"); + return { rgba: h.toRgba(r, n, o, a), css: e }; + }; + })(l || (t.css = l = {})), + (function (e) { + function t(e, t, i) { + const s = e / 255, + r = t / 255, + n = i / 255; + return ( + 0.2126 * + (s <= 0.03928 + ? s / 12.92 + : Math.pow((s + 0.055) / 1.055, 2.4)) + + 0.7152 * + (r <= 0.03928 + ? r / 12.92 + : Math.pow((r + 0.055) / 1.055, 2.4)) + + 0.0722 * + (n <= 0.03928 + ? n / 12.92 + : Math.pow((n + 0.055) / 1.055, 2.4)) + ); + } + ((e.relativeLuminance = function (e) { + return t((e >> 16) & 255, (e >> 8) & 255, 255 & e); + }), + (e.relativeLuminance2 = t)); + })(d || (t.rgb = d = {})), + (function (e) { + function t(e, t, i) { + const s = (e >> 24) & 255, + r = (e >> 16) & 255, + n = (e >> 8) & 255; + let o = (t >> 24) & 255, + a = (t >> 16) & 255, + h = (t >> 8) & 255, + c = f( + d.relativeLuminance2(o, a, h), + d.relativeLuminance2(s, r, n), + ); + for (; c < i && (o > 0 || a > 0 || h > 0); ) + ((o -= Math.max(0, Math.ceil(0.1 * o))), + (a -= Math.max(0, Math.ceil(0.1 * a))), + (h -= Math.max(0, Math.ceil(0.1 * h))), + (c = f( + d.relativeLuminance2(o, a, h), + d.relativeLuminance2(s, r, n), + ))); + return ((o << 24) | (a << 16) | (h << 8) | 255) >>> 0; + } + function i(e, t, i) { + const s = (e >> 24) & 255, + r = (e >> 16) & 255, + n = (e >> 8) & 255; + let o = (t >> 24) & 255, + a = (t >> 16) & 255, + h = (t >> 8) & 255, + c = f( + d.relativeLuminance2(o, a, h), + d.relativeLuminance2(s, r, n), + ); + for (; c < i && (o < 255 || a < 255 || h < 255); ) + ((o = Math.min(255, o + Math.ceil(0.1 * (255 - o)))), + (a = Math.min(255, a + Math.ceil(0.1 * (255 - a)))), + (h = Math.min(255, h + Math.ceil(0.1 * (255 - h)))), + (c = f( + d.relativeLuminance2(o, a, h), + d.relativeLuminance2(s, r, n), + ))); + return ((o << 24) | (a << 16) | (h << 8) | 255) >>> 0; + } + ((e.ensureContrastRatio = function (e, s, r) { + const n = d.relativeLuminance(e >> 8), + o = d.relativeLuminance(s >> 8); + if (f(n, o) < r) { + if (o < n) { + const o = t(e, s, r), + a = f(n, d.relativeLuminance(o >> 8)); + if (a < r) { + const t = i(e, s, r); + return a > f(n, d.relativeLuminance(t >> 8)) ? o : t; + } + return o; + } + const a = i(e, s, r), + h = f(n, d.relativeLuminance(a >> 8)); + if (h < r) { + const i = t(e, s, r); + return h > f(n, d.relativeLuminance(i >> 8)) ? a : i; + } + return a; + } + }), + (e.reduceLuminance = t), + (e.increaseLuminance = i), + (e.toChannels = function (e) { + return [ + (e >> 24) & 255, + (e >> 16) & 255, + (e >> 8) & 255, + 255 & e, + ]; + }), + (e.toColor = function (e, t, i, s) { + return { + css: h.toCss(e, t, i, s), + rgba: h.toRgba(e, t, i, s), + }; + })); + })(_ || (t.rgba = _ = {})), + (t.toPaddedHex = u), + (t.contrastRatio = f)); + }, + 8969: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CoreTerminal = void 0)); + const s = i(844), + r = i(2585), + n = i(4348), + o = i(7866), + a = i(744), + h = i(7302), + c = i(6975), + l = i(8460), + d = i(1753), + _ = i(1480), + u = i(7994), + f = i(9282), + v = i(5435), + p = i(5981), + g = i(2660); + let m = !1; + class S extends s.Disposable { + get onScroll() { + return ( + this._onScrollApi || + ((this._onScrollApi = this.register(new l.EventEmitter())), + this._onScroll.event((e) => { + var t; + null === (t = this._onScrollApi) || + void 0 === t || + t.fire(e.position); + })), + this._onScrollApi.event + ); + } + get cols() { + return this._bufferService.cols; + } + get rows() { + return this._bufferService.rows; + } + get buffers() { + return this._bufferService.buffers; + } + get options() { + return this.optionsService.options; + } + set options(e) { + for (const t in e) this.optionsService.options[t] = e[t]; + } + constructor(e) { + (super(), + (this._windowsWrappingHeuristics = this.register( + new s.MutableDisposable(), + )), + (this._onBinary = this.register(new l.EventEmitter())), + (this.onBinary = this._onBinary.event), + (this._onData = this.register(new l.EventEmitter())), + (this.onData = this._onData.event), + (this._onLineFeed = this.register(new l.EventEmitter())), + (this.onLineFeed = this._onLineFeed.event), + (this._onResize = this.register(new l.EventEmitter())), + (this.onResize = this._onResize.event), + (this._onWriteParsed = this.register(new l.EventEmitter())), + (this.onWriteParsed = this._onWriteParsed.event), + (this._onScroll = this.register(new l.EventEmitter())), + (this._instantiationService = new n.InstantiationService()), + (this.optionsService = this.register(new h.OptionsService(e))), + this._instantiationService.setService( + r.IOptionsService, + this.optionsService, + ), + (this._bufferService = this.register( + this._instantiationService.createInstance(a.BufferService), + )), + this._instantiationService.setService( + r.IBufferService, + this._bufferService, + ), + (this._logService = this.register( + this._instantiationService.createInstance(o.LogService), + )), + this._instantiationService.setService( + r.ILogService, + this._logService, + ), + (this.coreService = this.register( + this._instantiationService.createInstance(c.CoreService), + )), + this._instantiationService.setService( + r.ICoreService, + this.coreService, + ), + (this.coreMouseService = this.register( + this._instantiationService.createInstance(d.CoreMouseService), + )), + this._instantiationService.setService( + r.ICoreMouseService, + this.coreMouseService, + ), + (this.unicodeService = this.register( + this._instantiationService.createInstance(_.UnicodeService), + )), + this._instantiationService.setService( + r.IUnicodeService, + this.unicodeService, + ), + (this._charsetService = + this._instantiationService.createInstance(u.CharsetService)), + this._instantiationService.setService( + r.ICharsetService, + this._charsetService, + ), + (this._oscLinkService = + this._instantiationService.createInstance(g.OscLinkService)), + this._instantiationService.setService( + r.IOscLinkService, + this._oscLinkService, + ), + (this._inputHandler = this.register( + new v.InputHandler( + this._bufferService, + this._charsetService, + this.coreService, + this._logService, + this.optionsService, + this._oscLinkService, + this.coreMouseService, + this.unicodeService, + ), + )), + this.register( + (0, l.forwardEvent)( + this._inputHandler.onLineFeed, + this._onLineFeed, + ), + ), + this.register(this._inputHandler), + this.register( + (0, l.forwardEvent)( + this._bufferService.onResize, + this._onResize, + ), + ), + this.register( + (0, l.forwardEvent)(this.coreService.onData, this._onData), + ), + this.register( + (0, l.forwardEvent)( + this.coreService.onBinary, + this._onBinary, + ), + ), + this.register( + this.coreService.onRequestScrollToBottom(() => + this.scrollToBottom(), + ), + ), + this.register( + this.coreService.onUserInput(() => + this._writeBuffer.handleUserInput(), + ), + ), + this.register( + this.optionsService.onMultipleOptionChange( + ["windowsMode", "windowsPty"], + () => this._handleWindowsPtyOptionChange(), + ), + ), + this.register( + this._bufferService.onScroll((e) => { + (this._onScroll.fire({ + position: this._bufferService.buffer.ydisp, + source: 0, + }), + this._inputHandler.markRangeDirty( + this._bufferService.buffer.scrollTop, + this._bufferService.buffer.scrollBottom, + )); + }), + ), + this.register( + this._inputHandler.onScroll((e) => { + (this._onScroll.fire({ + position: this._bufferService.buffer.ydisp, + source: 0, + }), + this._inputHandler.markRangeDirty( + this._bufferService.buffer.scrollTop, + this._bufferService.buffer.scrollBottom, + )); + }), + ), + (this._writeBuffer = this.register( + new p.WriteBuffer((e, t) => this._inputHandler.parse(e, t)), + )), + this.register( + (0, l.forwardEvent)( + this._writeBuffer.onWriteParsed, + this._onWriteParsed, + ), + )); + } + write(e, t) { + this._writeBuffer.write(e, t); + } + writeSync(e, t) { + (this._logService.logLevel <= r.LogLevelEnum.WARN && + !m && + (this._logService.warn( + "writeSync is unreliable and will be removed soon.", + ), + (m = !0)), + this._writeBuffer.writeSync(e, t)); + } + resize(e, t) { + isNaN(e) || + isNaN(t) || + ((e = Math.max(e, a.MINIMUM_COLS)), + (t = Math.max(t, a.MINIMUM_ROWS)), + this._bufferService.resize(e, t)); + } + scroll(e, t = !1) { + this._bufferService.scroll(e, t); + } + scrollLines(e, t, i) { + this._bufferService.scrollLines(e, t, i); + } + scrollPages(e) { + this.scrollLines(e * (this.rows - 1)); + } + scrollToTop() { + this.scrollLines(-this._bufferService.buffer.ydisp); + } + scrollToBottom() { + this.scrollLines( + this._bufferService.buffer.ybase - + this._bufferService.buffer.ydisp, + ); + } + scrollToLine(e) { + const t = e - this._bufferService.buffer.ydisp; + 0 !== t && this.scrollLines(t); + } + registerEscHandler(e, t) { + return this._inputHandler.registerEscHandler(e, t); + } + registerDcsHandler(e, t) { + return this._inputHandler.registerDcsHandler(e, t); + } + registerCsiHandler(e, t) { + return this._inputHandler.registerCsiHandler(e, t); + } + registerOscHandler(e, t) { + return this._inputHandler.registerOscHandler(e, t); + } + _setup() { + this._handleWindowsPtyOptionChange(); + } + reset() { + (this._inputHandler.reset(), + this._bufferService.reset(), + this._charsetService.reset(), + this.coreService.reset(), + this.coreMouseService.reset()); + } + _handleWindowsPtyOptionChange() { + let e = !1; + const t = this.optionsService.rawOptions.windowsPty; + (t && void 0 !== t.buildNumber && void 0 !== t.buildNumber + ? (e = !!("conpty" === t.backend && t.buildNumber < 21376)) + : this.optionsService.rawOptions.windowsMode && (e = !0), + e + ? this._enableWindowsWrappingHeuristics() + : this._windowsWrappingHeuristics.clear()); + } + _enableWindowsWrappingHeuristics() { + if (!this._windowsWrappingHeuristics.value) { + const e = []; + (e.push( + this.onLineFeed( + f.updateWindowsModeWrappedState.bind( + null, + this._bufferService, + ), + ), + ), + e.push( + this.registerCsiHandler( + { final: "H" }, + () => ( + (0, f.updateWindowsModeWrappedState)( + this._bufferService, + ), + !1 + ), + ), + ), + (this._windowsWrappingHeuristics.value = (0, s.toDisposable)( + () => { + for (const t of e) t.dispose(); + }, + ))); + } + } + } + t.CoreTerminal = S; + }, + 8460: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.forwardEvent = t.EventEmitter = void 0), + (t.EventEmitter = class { + constructor() { + ((this._listeners = []), (this._disposed = !1)); + } + get event() { + return ( + this._event || + (this._event = (e) => ( + this._listeners.push(e), + { + dispose: () => { + if (!this._disposed) + for (let t = 0; t < this._listeners.length; t++) + if (this._listeners[t] === e) + return void this._listeners.splice(t, 1); + }, + } + )), + this._event + ); + } + fire(e, t) { + const i = []; + for (let e = 0; e < this._listeners.length; e++) + i.push(this._listeners[e]); + for (let s = 0; s < i.length; s++) i[s].call(void 0, e, t); + } + dispose() { + (this.clearListeners(), (this._disposed = !0)); + } + clearListeners() { + this._listeners && (this._listeners.length = 0); + } + }), + (t.forwardEvent = function (e, t) { + return e((e) => t.fire(e)); + })); + }, + 5435: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.InputHandler = t.WindowsOptionsReportType = void 0)); + const n = i(2584), + o = i(7116), + a = i(2015), + h = i(844), + c = i(482), + l = i(8437), + d = i(8460), + _ = i(643), + u = i(511), + f = i(3734), + v = i(2585), + p = i(6242), + g = i(6351), + m = i(5941), + S = { "(": 0, ")": 1, "*": 2, "+": 3, "-": 1, ".": 2 }, + C = 131072; + function b(e, t) { + if (e > 24) return t.setWinLines || !1; + switch (e) { + case 1: + return !!t.restoreWin; + case 2: + return !!t.minimizeWin; + case 3: + return !!t.setWinPosition; + case 4: + return !!t.setWinSizePixels; + case 5: + return !!t.raiseWin; + case 6: + return !!t.lowerWin; + case 7: + return !!t.refreshWin; + case 8: + return !!t.setWinSizeChars; + case 9: + return !!t.maximizeWin; + case 10: + return !!t.fullscreenWin; + case 11: + return !!t.getWinState; + case 13: + return !!t.getWinPosition; + case 14: + return !!t.getWinSizePixels; + case 15: + return !!t.getScreenSizePixels; + case 16: + return !!t.getCellSizePixels; + case 18: + return !!t.getWinSizeChars; + case 19: + return !!t.getScreenSizeChars; + case 20: + return !!t.getIconTitle; + case 21: + return !!t.getWinTitle; + case 22: + return !!t.pushTitle; + case 23: + return !!t.popTitle; + case 24: + return !!t.setWinLines; + } + return !1; + } + var y; + !(function (e) { + ((e[(e.GET_WIN_SIZE_PIXELS = 0)] = "GET_WIN_SIZE_PIXELS"), + (e[(e.GET_CELL_SIZE_PIXELS = 1)] = "GET_CELL_SIZE_PIXELS")); + })(y || (t.WindowsOptionsReportType = y = {})); + let w = 0; + class E extends h.Disposable { + getAttrData() { + return this._curAttrData; + } + constructor( + e, + t, + i, + s, + r, + h, + _, + f, + v = new a.EscapeSequenceParser(), + ) { + (super(), + (this._bufferService = e), + (this._charsetService = t), + (this._coreService = i), + (this._logService = s), + (this._optionsService = r), + (this._oscLinkService = h), + (this._coreMouseService = _), + (this._unicodeService = f), + (this._parser = v), + (this._parseBuffer = new Uint32Array(4096)), + (this._stringDecoder = new c.StringToUtf32()), + (this._utf8Decoder = new c.Utf8ToUtf32()), + (this._workCell = new u.CellData()), + (this._windowTitle = ""), + (this._iconName = ""), + (this._windowTitleStack = []), + (this._iconNameStack = []), + (this._curAttrData = l.DEFAULT_ATTR_DATA.clone()), + (this._eraseAttrDataInternal = l.DEFAULT_ATTR_DATA.clone()), + (this._onRequestBell = this.register(new d.EventEmitter())), + (this.onRequestBell = this._onRequestBell.event), + (this._onRequestRefreshRows = this.register( + new d.EventEmitter(), + )), + (this.onRequestRefreshRows = this._onRequestRefreshRows.event), + (this._onRequestReset = this.register(new d.EventEmitter())), + (this.onRequestReset = this._onRequestReset.event), + (this._onRequestSendFocus = this.register( + new d.EventEmitter(), + )), + (this.onRequestSendFocus = this._onRequestSendFocus.event), + (this._onRequestSyncScrollBar = this.register( + new d.EventEmitter(), + )), + (this.onRequestSyncScrollBar = + this._onRequestSyncScrollBar.event), + (this._onRequestWindowsOptionsReport = this.register( + new d.EventEmitter(), + )), + (this.onRequestWindowsOptionsReport = + this._onRequestWindowsOptionsReport.event), + (this._onA11yChar = this.register(new d.EventEmitter())), + (this.onA11yChar = this._onA11yChar.event), + (this._onA11yTab = this.register(new d.EventEmitter())), + (this.onA11yTab = this._onA11yTab.event), + (this._onCursorMove = this.register(new d.EventEmitter())), + (this.onCursorMove = this._onCursorMove.event), + (this._onLineFeed = this.register(new d.EventEmitter())), + (this.onLineFeed = this._onLineFeed.event), + (this._onScroll = this.register(new d.EventEmitter())), + (this.onScroll = this._onScroll.event), + (this._onTitleChange = this.register(new d.EventEmitter())), + (this.onTitleChange = this._onTitleChange.event), + (this._onColor = this.register(new d.EventEmitter())), + (this.onColor = this._onColor.event), + (this._parseStack = { + paused: !1, + cursorStartX: 0, + cursorStartY: 0, + decodedLength: 0, + position: 0, + }), + (this._specialColors = [256, 257, 258]), + this.register(this._parser), + (this._dirtyRowTracker = new k(this._bufferService)), + (this._activeBuffer = this._bufferService.buffer), + this.register( + this._bufferService.buffers.onBufferActivate( + (e) => (this._activeBuffer = e.activeBuffer), + ), + ), + this._parser.setCsiHandlerFallback((e, t) => { + this._logService.debug("Unknown CSI code: ", { + identifier: this._parser.identToString(e), + params: t.toArray(), + }); + }), + this._parser.setEscHandlerFallback((e) => { + this._logService.debug("Unknown ESC code: ", { + identifier: this._parser.identToString(e), + }); + }), + this._parser.setExecuteHandlerFallback((e) => { + this._logService.debug("Unknown EXECUTE code: ", { code: e }); + }), + this._parser.setOscHandlerFallback((e, t, i) => { + this._logService.debug("Unknown OSC code: ", { + identifier: e, + action: t, + data: i, + }); + }), + this._parser.setDcsHandlerFallback((e, t, i) => { + ("HOOK" === t && (i = i.toArray()), + this._logService.debug("Unknown DCS code: ", { + identifier: this._parser.identToString(e), + action: t, + payload: i, + })); + }), + this._parser.setPrintHandler((e, t, i) => this.print(e, t, i)), + this._parser.registerCsiHandler({ final: "@" }, (e) => + this.insertChars(e), + ), + this._parser.registerCsiHandler( + { intermediates: " ", final: "@" }, + (e) => this.scrollLeft(e), + ), + this._parser.registerCsiHandler({ final: "A" }, (e) => + this.cursorUp(e), + ), + this._parser.registerCsiHandler( + { intermediates: " ", final: "A" }, + (e) => this.scrollRight(e), + ), + this._parser.registerCsiHandler({ final: "B" }, (e) => + this.cursorDown(e), + ), + this._parser.registerCsiHandler({ final: "C" }, (e) => + this.cursorForward(e), + ), + this._parser.registerCsiHandler({ final: "D" }, (e) => + this.cursorBackward(e), + ), + this._parser.registerCsiHandler({ final: "E" }, (e) => + this.cursorNextLine(e), + ), + this._parser.registerCsiHandler({ final: "F" }, (e) => + this.cursorPrecedingLine(e), + ), + this._parser.registerCsiHandler({ final: "G" }, (e) => + this.cursorCharAbsolute(e), + ), + this._parser.registerCsiHandler({ final: "H" }, (e) => + this.cursorPosition(e), + ), + this._parser.registerCsiHandler({ final: "I" }, (e) => + this.cursorForwardTab(e), + ), + this._parser.registerCsiHandler({ final: "J" }, (e) => + this.eraseInDisplay(e, !1), + ), + this._parser.registerCsiHandler( + { prefix: "?", final: "J" }, + (e) => this.eraseInDisplay(e, !0), + ), + this._parser.registerCsiHandler({ final: "K" }, (e) => + this.eraseInLine(e, !1), + ), + this._parser.registerCsiHandler( + { prefix: "?", final: "K" }, + (e) => this.eraseInLine(e, !0), + ), + this._parser.registerCsiHandler({ final: "L" }, (e) => + this.insertLines(e), + ), + this._parser.registerCsiHandler({ final: "M" }, (e) => + this.deleteLines(e), + ), + this._parser.registerCsiHandler({ final: "P" }, (e) => + this.deleteChars(e), + ), + this._parser.registerCsiHandler({ final: "S" }, (e) => + this.scrollUp(e), + ), + this._parser.registerCsiHandler({ final: "T" }, (e) => + this.scrollDown(e), + ), + this._parser.registerCsiHandler({ final: "X" }, (e) => + this.eraseChars(e), + ), + this._parser.registerCsiHandler({ final: "Z" }, (e) => + this.cursorBackwardTab(e), + ), + this._parser.registerCsiHandler({ final: "`" }, (e) => + this.charPosAbsolute(e), + ), + this._parser.registerCsiHandler({ final: "a" }, (e) => + this.hPositionRelative(e), + ), + this._parser.registerCsiHandler({ final: "b" }, (e) => + this.repeatPrecedingCharacter(e), + ), + this._parser.registerCsiHandler({ final: "c" }, (e) => + this.sendDeviceAttributesPrimary(e), + ), + this._parser.registerCsiHandler( + { prefix: ">", final: "c" }, + (e) => this.sendDeviceAttributesSecondary(e), + ), + this._parser.registerCsiHandler({ final: "d" }, (e) => + this.linePosAbsolute(e), + ), + this._parser.registerCsiHandler({ final: "e" }, (e) => + this.vPositionRelative(e), + ), + this._parser.registerCsiHandler({ final: "f" }, (e) => + this.hVPosition(e), + ), + this._parser.registerCsiHandler({ final: "g" }, (e) => + this.tabClear(e), + ), + this._parser.registerCsiHandler({ final: "h" }, (e) => + this.setMode(e), + ), + this._parser.registerCsiHandler( + { prefix: "?", final: "h" }, + (e) => this.setModePrivate(e), + ), + this._parser.registerCsiHandler({ final: "l" }, (e) => + this.resetMode(e), + ), + this._parser.registerCsiHandler( + { prefix: "?", final: "l" }, + (e) => this.resetModePrivate(e), + ), + this._parser.registerCsiHandler({ final: "m" }, (e) => + this.charAttributes(e), + ), + this._parser.registerCsiHandler({ final: "n" }, (e) => + this.deviceStatus(e), + ), + this._parser.registerCsiHandler( + { prefix: "?", final: "n" }, + (e) => this.deviceStatusPrivate(e), + ), + this._parser.registerCsiHandler( + { intermediates: "!", final: "p" }, + (e) => this.softReset(e), + ), + this._parser.registerCsiHandler( + { intermediates: " ", final: "q" }, + (e) => this.setCursorStyle(e), + ), + this._parser.registerCsiHandler({ final: "r" }, (e) => + this.setScrollRegion(e), + ), + this._parser.registerCsiHandler({ final: "s" }, (e) => + this.saveCursor(e), + ), + this._parser.registerCsiHandler({ final: "t" }, (e) => + this.windowOptions(e), + ), + this._parser.registerCsiHandler({ final: "u" }, (e) => + this.restoreCursor(e), + ), + this._parser.registerCsiHandler( + { intermediates: "'", final: "}" }, + (e) => this.insertColumns(e), + ), + this._parser.registerCsiHandler( + { intermediates: "'", final: "~" }, + (e) => this.deleteColumns(e), + ), + this._parser.registerCsiHandler( + { intermediates: '"', final: "q" }, + (e) => this.selectProtected(e), + ), + this._parser.registerCsiHandler( + { intermediates: "$", final: "p" }, + (e) => this.requestMode(e, !0), + ), + this._parser.registerCsiHandler( + { prefix: "?", intermediates: "$", final: "p" }, + (e) => this.requestMode(e, !1), + ), + this._parser.setExecuteHandler(n.C0.BEL, () => this.bell()), + this._parser.setExecuteHandler(n.C0.LF, () => this.lineFeed()), + this._parser.setExecuteHandler(n.C0.VT, () => this.lineFeed()), + this._parser.setExecuteHandler(n.C0.FF, () => this.lineFeed()), + this._parser.setExecuteHandler(n.C0.CR, () => + this.carriageReturn(), + ), + this._parser.setExecuteHandler(n.C0.BS, () => this.backspace()), + this._parser.setExecuteHandler(n.C0.HT, () => this.tab()), + this._parser.setExecuteHandler(n.C0.SO, () => this.shiftOut()), + this._parser.setExecuteHandler(n.C0.SI, () => this.shiftIn()), + this._parser.setExecuteHandler(n.C1.IND, () => this.index()), + this._parser.setExecuteHandler(n.C1.NEL, () => this.nextLine()), + this._parser.setExecuteHandler(n.C1.HTS, () => this.tabSet()), + this._parser.registerOscHandler( + 0, + new p.OscHandler( + (e) => (this.setTitle(e), this.setIconName(e), !0), + ), + ), + this._parser.registerOscHandler( + 1, + new p.OscHandler((e) => this.setIconName(e)), + ), + this._parser.registerOscHandler( + 2, + new p.OscHandler((e) => this.setTitle(e)), + ), + this._parser.registerOscHandler( + 4, + new p.OscHandler((e) => this.setOrReportIndexedColor(e)), + ), + this._parser.registerOscHandler( + 8, + new p.OscHandler((e) => this.setHyperlink(e)), + ), + this._parser.registerOscHandler( + 10, + new p.OscHandler((e) => this.setOrReportFgColor(e)), + ), + this._parser.registerOscHandler( + 11, + new p.OscHandler((e) => this.setOrReportBgColor(e)), + ), + this._parser.registerOscHandler( + 12, + new p.OscHandler((e) => this.setOrReportCursorColor(e)), + ), + this._parser.registerOscHandler( + 104, + new p.OscHandler((e) => this.restoreIndexedColor(e)), + ), + this._parser.registerOscHandler( + 110, + new p.OscHandler((e) => this.restoreFgColor(e)), + ), + this._parser.registerOscHandler( + 111, + new p.OscHandler((e) => this.restoreBgColor(e)), + ), + this._parser.registerOscHandler( + 112, + new p.OscHandler((e) => this.restoreCursorColor(e)), + ), + this._parser.registerEscHandler({ final: "7" }, () => + this.saveCursor(), + ), + this._parser.registerEscHandler({ final: "8" }, () => + this.restoreCursor(), + ), + this._parser.registerEscHandler({ final: "D" }, () => + this.index(), + ), + this._parser.registerEscHandler({ final: "E" }, () => + this.nextLine(), + ), + this._parser.registerEscHandler({ final: "H" }, () => + this.tabSet(), + ), + this._parser.registerEscHandler({ final: "M" }, () => + this.reverseIndex(), + ), + this._parser.registerEscHandler({ final: "=" }, () => + this.keypadApplicationMode(), + ), + this._parser.registerEscHandler({ final: ">" }, () => + this.keypadNumericMode(), + ), + this._parser.registerEscHandler({ final: "c" }, () => + this.fullReset(), + ), + this._parser.registerEscHandler({ final: "n" }, () => + this.setgLevel(2), + ), + this._parser.registerEscHandler({ final: "o" }, () => + this.setgLevel(3), + ), + this._parser.registerEscHandler({ final: "|" }, () => + this.setgLevel(3), + ), + this._parser.registerEscHandler({ final: "}" }, () => + this.setgLevel(2), + ), + this._parser.registerEscHandler({ final: "~" }, () => + this.setgLevel(1), + ), + this._parser.registerEscHandler( + { intermediates: "%", final: "@" }, + () => this.selectDefaultCharset(), + ), + this._parser.registerEscHandler( + { intermediates: "%", final: "G" }, + () => this.selectDefaultCharset(), + )); + for (const e in o.CHARSETS) + (this._parser.registerEscHandler( + { intermediates: "(", final: e }, + () => this.selectCharset("(" + e), + ), + this._parser.registerEscHandler( + { intermediates: ")", final: e }, + () => this.selectCharset(")" + e), + ), + this._parser.registerEscHandler( + { intermediates: "*", final: e }, + () => this.selectCharset("*" + e), + ), + this._parser.registerEscHandler( + { intermediates: "+", final: e }, + () => this.selectCharset("+" + e), + ), + this._parser.registerEscHandler( + { intermediates: "-", final: e }, + () => this.selectCharset("-" + e), + ), + this._parser.registerEscHandler( + { intermediates: ".", final: e }, + () => this.selectCharset("." + e), + ), + this._parser.registerEscHandler( + { intermediates: "/", final: e }, + () => this.selectCharset("/" + e), + )); + (this._parser.registerEscHandler( + { intermediates: "#", final: "8" }, + () => this.screenAlignmentPattern(), + ), + this._parser.setErrorHandler( + (e) => (this._logService.error("Parsing error: ", e), e), + ), + this._parser.registerDcsHandler( + { intermediates: "$", final: "q" }, + new g.DcsHandler((e, t) => this.requestStatusString(e, t)), + )); + } + _preserveStack(e, t, i, s) { + ((this._parseStack.paused = !0), + (this._parseStack.cursorStartX = e), + (this._parseStack.cursorStartY = t), + (this._parseStack.decodedLength = i), + (this._parseStack.position = s)); + } + _logSlowResolvingAsync(e) { + this._logService.logLevel <= v.LogLevelEnum.WARN && + Promise.race([ + e, + new Promise((e, t) => + setTimeout(() => t("#SLOW_TIMEOUT"), 5e3), + ), + ]).catch((e) => { + if ("#SLOW_TIMEOUT" !== e) throw e; + console.warn( + "async parser handler taking longer than 5000 ms", + ); + }); + } + _getCurrentLinkId() { + return this._curAttrData.extended.urlId; + } + parse(e, t) { + let i, + s = this._activeBuffer.x, + r = this._activeBuffer.y, + n = 0; + const o = this._parseStack.paused; + if (o) { + if ( + (i = this._parser.parse( + this._parseBuffer, + this._parseStack.decodedLength, + t, + )) + ) + return (this._logSlowResolvingAsync(i), i); + ((s = this._parseStack.cursorStartX), + (r = this._parseStack.cursorStartY), + (this._parseStack.paused = !1), + e.length > C && (n = this._parseStack.position + C)); + } + if ( + (this._logService.logLevel <= v.LogLevelEnum.DEBUG && + this._logService.debug( + "parsing data" + + ("string" == typeof e + ? ` "${e}"` + : ` "${Array.prototype.map.call(e, (e) => String.fromCharCode(e)).join("")}"`), + "string" == typeof e + ? e.split("").map((e) => e.charCodeAt(0)) + : e, + ), + this._parseBuffer.length < e.length && + this._parseBuffer.length < C && + (this._parseBuffer = new Uint32Array(Math.min(e.length, C))), + o || this._dirtyRowTracker.clearRange(), + e.length > C) + ) + for (let t = n; t < e.length; t += C) { + const n = t + C < e.length ? t + C : e.length, + o = + "string" == typeof e + ? this._stringDecoder.decode( + e.substring(t, n), + this._parseBuffer, + ) + : this._utf8Decoder.decode( + e.subarray(t, n), + this._parseBuffer, + ); + if ((i = this._parser.parse(this._parseBuffer, o))) + return ( + this._preserveStack(s, r, o, t), + this._logSlowResolvingAsync(i), + i + ); + } + else if (!o) { + const t = + "string" == typeof e + ? this._stringDecoder.decode(e, this._parseBuffer) + : this._utf8Decoder.decode(e, this._parseBuffer); + if ((i = this._parser.parse(this._parseBuffer, t))) + return ( + this._preserveStack(s, r, t, 0), + this._logSlowResolvingAsync(i), + i + ); + } + ((this._activeBuffer.x === s && this._activeBuffer.y === r) || + this._onCursorMove.fire(), + this._onRequestRefreshRows.fire( + this._dirtyRowTracker.start, + this._dirtyRowTracker.end, + )); + } + print(e, t, i) { + let s, r; + const n = this._charsetService.charset, + o = this._optionsService.rawOptions.screenReaderMode, + a = this._bufferService.cols, + h = this._coreService.decPrivateModes.wraparound, + l = this._coreService.modes.insertMode, + d = this._curAttrData; + let u = this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ); + (this._dirtyRowTracker.markDirty(this._activeBuffer.y), + this._activeBuffer.x && + i - t > 0 && + 2 === u.getWidth(this._activeBuffer.x - 1) && + u.setCellFromCodePoint( + this._activeBuffer.x - 1, + 0, + 1, + d.fg, + d.bg, + d.extended, + )); + for (let f = t; f < i; ++f) { + if ( + ((s = e[f]), + (r = this._unicodeService.wcwidth(s)), + s < 127 && n) + ) { + const e = n[String.fromCharCode(s)]; + e && (s = e.charCodeAt(0)); + } + if ( + (o && this._onA11yChar.fire((0, c.stringFromCodePoint)(s)), + this._getCurrentLinkId() && + this._oscLinkService.addLineToLink( + this._getCurrentLinkId(), + this._activeBuffer.ybase + this._activeBuffer.y, + ), + r || !this._activeBuffer.x) + ) { + if (this._activeBuffer.x + r - 1 >= a) + if (h) { + for (; this._activeBuffer.x < a; ) + u.setCellFromCodePoint( + this._activeBuffer.x++, + 0, + 1, + d.fg, + d.bg, + d.extended, + ); + ((this._activeBuffer.x = 0), + this._activeBuffer.y++, + this._activeBuffer.y === + this._activeBuffer.scrollBottom + 1 + ? (this._activeBuffer.y--, + this._bufferService.scroll( + this._eraseAttrData(), + !0, + )) + : (this._activeBuffer.y >= this._bufferService.rows && + (this._activeBuffer.y = + this._bufferService.rows - 1), + (this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ).isWrapped = !0)), + (u = this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ))); + } else if (((this._activeBuffer.x = a - 1), 2 === r)) + continue; + if ( + (l && + (u.insertCells( + this._activeBuffer.x, + r, + this._activeBuffer.getNullCell(d), + d, + ), + 2 === u.getWidth(a - 1) && + u.setCellFromCodePoint( + a - 1, + _.NULL_CELL_CODE, + _.NULL_CELL_WIDTH, + d.fg, + d.bg, + d.extended, + )), + u.setCellFromCodePoint( + this._activeBuffer.x++, + s, + r, + d.fg, + d.bg, + d.extended, + ), + r > 0) + ) + for (; --r; ) + u.setCellFromCodePoint( + this._activeBuffer.x++, + 0, + 0, + d.fg, + d.bg, + d.extended, + ); + } else + u.getWidth(this._activeBuffer.x - 1) + ? u.addCodepointToCell(this._activeBuffer.x - 1, s) + : u.addCodepointToCell(this._activeBuffer.x - 2, s); + } + (i - t > 0 && + (u.loadCell(this._activeBuffer.x - 1, this._workCell), + 2 === this._workCell.getWidth() || + this._workCell.getCode() > 65535 + ? (this._parser.precedingCodepoint = 0) + : this._workCell.isCombined() + ? (this._parser.precedingCodepoint = this._workCell + .getChars() + .charCodeAt(0)) + : (this._parser.precedingCodepoint = + this._workCell.content)), + this._activeBuffer.x < a && + i - t > 0 && + 0 === u.getWidth(this._activeBuffer.x) && + !u.hasContent(this._activeBuffer.x) && + u.setCellFromCodePoint( + this._activeBuffer.x, + 0, + 1, + d.fg, + d.bg, + d.extended, + ), + this._dirtyRowTracker.markDirty(this._activeBuffer.y)); + } + registerCsiHandler(e, t) { + return "t" !== e.final || e.prefix || e.intermediates + ? this._parser.registerCsiHandler(e, t) + : this._parser.registerCsiHandler( + e, + (e) => + !b( + e.params[0], + this._optionsService.rawOptions.windowOptions, + ) || t(e), + ); + } + registerDcsHandler(e, t) { + return this._parser.registerDcsHandler(e, new g.DcsHandler(t)); + } + registerEscHandler(e, t) { + return this._parser.registerEscHandler(e, t); + } + registerOscHandler(e, t) { + return this._parser.registerOscHandler(e, new p.OscHandler(t)); + } + bell() { + return (this._onRequestBell.fire(), !0); + } + lineFeed() { + return ( + this._dirtyRowTracker.markDirty(this._activeBuffer.y), + this._optionsService.rawOptions.convertEol && + (this._activeBuffer.x = 0), + this._activeBuffer.y++, + this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 + ? (this._activeBuffer.y--, + this._bufferService.scroll(this._eraseAttrData())) + : this._activeBuffer.y >= this._bufferService.rows + ? (this._activeBuffer.y = this._bufferService.rows - 1) + : (this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ).isWrapped = !1), + this._activeBuffer.x >= this._bufferService.cols && + this._activeBuffer.x--, + this._dirtyRowTracker.markDirty(this._activeBuffer.y), + this._onLineFeed.fire(), + !0 + ); + } + carriageReturn() { + return ((this._activeBuffer.x = 0), !0); + } + backspace() { + var e; + if (!this._coreService.decPrivateModes.reverseWraparound) + return ( + this._restrictCursor(), + this._activeBuffer.x > 0 && this._activeBuffer.x--, + !0 + ); + if ( + (this._restrictCursor(this._bufferService.cols), + this._activeBuffer.x > 0) + ) + this._activeBuffer.x--; + else if ( + 0 === this._activeBuffer.x && + this._activeBuffer.y > this._activeBuffer.scrollTop && + this._activeBuffer.y <= this._activeBuffer.scrollBottom && + (null === + (e = this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + )) || void 0 === e + ? void 0 + : e.isWrapped) + ) { + ((this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ).isWrapped = !1), + this._activeBuffer.y--, + (this._activeBuffer.x = this._bufferService.cols - 1)); + const e = this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ); + e.hasWidth(this._activeBuffer.x) && + !e.hasContent(this._activeBuffer.x) && + this._activeBuffer.x--; + } + return (this._restrictCursor(), !0); + } + tab() { + if (this._activeBuffer.x >= this._bufferService.cols) return !0; + const e = this._activeBuffer.x; + return ( + (this._activeBuffer.x = this._activeBuffer.nextStop()), + this._optionsService.rawOptions.screenReaderMode && + this._onA11yTab.fire(this._activeBuffer.x - e), + !0 + ); + } + shiftOut() { + return (this._charsetService.setgLevel(1), !0); + } + shiftIn() { + return (this._charsetService.setgLevel(0), !0); + } + _restrictCursor(e = this._bufferService.cols - 1) { + ((this._activeBuffer.x = Math.min( + e, + Math.max(0, this._activeBuffer.x), + )), + (this._activeBuffer.y = this._coreService.decPrivateModes.origin + ? Math.min( + this._activeBuffer.scrollBottom, + Math.max( + this._activeBuffer.scrollTop, + this._activeBuffer.y, + ), + ) + : Math.min( + this._bufferService.rows - 1, + Math.max(0, this._activeBuffer.y), + )), + this._dirtyRowTracker.markDirty(this._activeBuffer.y)); + } + _setCursor(e, t) { + (this._dirtyRowTracker.markDirty(this._activeBuffer.y), + this._coreService.decPrivateModes.origin + ? ((this._activeBuffer.x = e), + (this._activeBuffer.y = this._activeBuffer.scrollTop + t)) + : ((this._activeBuffer.x = e), (this._activeBuffer.y = t)), + this._restrictCursor(), + this._dirtyRowTracker.markDirty(this._activeBuffer.y)); + } + _moveCursor(e, t) { + (this._restrictCursor(), + this._setCursor( + this._activeBuffer.x + e, + this._activeBuffer.y + t, + )); + } + cursorUp(e) { + const t = this._activeBuffer.y - this._activeBuffer.scrollTop; + return ( + t >= 0 + ? this._moveCursor(0, -Math.min(t, e.params[0] || 1)) + : this._moveCursor(0, -(e.params[0] || 1)), + !0 + ); + } + cursorDown(e) { + const t = this._activeBuffer.scrollBottom - this._activeBuffer.y; + return ( + t >= 0 + ? this._moveCursor(0, Math.min(t, e.params[0] || 1)) + : this._moveCursor(0, e.params[0] || 1), + !0 + ); + } + cursorForward(e) { + return (this._moveCursor(e.params[0] || 1, 0), !0); + } + cursorBackward(e) { + return (this._moveCursor(-(e.params[0] || 1), 0), !0); + } + cursorNextLine(e) { + return (this.cursorDown(e), (this._activeBuffer.x = 0), !0); + } + cursorPrecedingLine(e) { + return (this.cursorUp(e), (this._activeBuffer.x = 0), !0); + } + cursorCharAbsolute(e) { + return ( + this._setCursor((e.params[0] || 1) - 1, this._activeBuffer.y), + !0 + ); + } + cursorPosition(e) { + return ( + this._setCursor( + e.length >= 2 ? (e.params[1] || 1) - 1 : 0, + (e.params[0] || 1) - 1, + ), + !0 + ); + } + charPosAbsolute(e) { + return ( + this._setCursor((e.params[0] || 1) - 1, this._activeBuffer.y), + !0 + ); + } + hPositionRelative(e) { + return (this._moveCursor(e.params[0] || 1, 0), !0); + } + linePosAbsolute(e) { + return ( + this._setCursor(this._activeBuffer.x, (e.params[0] || 1) - 1), + !0 + ); + } + vPositionRelative(e) { + return (this._moveCursor(0, e.params[0] || 1), !0); + } + hVPosition(e) { + return (this.cursorPosition(e), !0); + } + tabClear(e) { + const t = e.params[0]; + return ( + 0 === t + ? delete this._activeBuffer.tabs[this._activeBuffer.x] + : 3 === t && (this._activeBuffer.tabs = {}), + !0 + ); + } + cursorForwardTab(e) { + if (this._activeBuffer.x >= this._bufferService.cols) return !0; + let t = e.params[0] || 1; + for (; t--; ) + this._activeBuffer.x = this._activeBuffer.nextStop(); + return !0; + } + cursorBackwardTab(e) { + if (this._activeBuffer.x >= this._bufferService.cols) return !0; + let t = e.params[0] || 1; + for (; t--; ) + this._activeBuffer.x = this._activeBuffer.prevStop(); + return !0; + } + selectProtected(e) { + const t = e.params[0]; + return ( + 1 === t && (this._curAttrData.bg |= 536870912), + (2 !== t && 0 !== t) || (this._curAttrData.bg &= -536870913), + !0 + ); + } + _eraseInBufferLine(e, t, i, s = !1, r = !1) { + const n = this._activeBuffer.lines.get( + this._activeBuffer.ybase + e, + ); + (n.replaceCells( + t, + i, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + r, + ), + s && (n.isWrapped = !1)); + } + _resetBufferLine(e, t = !1) { + const i = this._activeBuffer.lines.get( + this._activeBuffer.ybase + e, + ); + i && + (i.fill( + this._activeBuffer.getNullCell(this._eraseAttrData()), + t, + ), + this._bufferService.buffer.clearMarkers( + this._activeBuffer.ybase + e, + ), + (i.isWrapped = !1)); + } + eraseInDisplay(e, t = !1) { + let i; + switch ( + (this._restrictCursor(this._bufferService.cols), e.params[0]) + ) { + case 0: + for ( + i = this._activeBuffer.y, + this._dirtyRowTracker.markDirty(i), + this._eraseInBufferLine( + i++, + this._activeBuffer.x, + this._bufferService.cols, + 0 === this._activeBuffer.x, + t, + ); + i < this._bufferService.rows; + i++ + ) + this._resetBufferLine(i, t); + this._dirtyRowTracker.markDirty(i); + break; + case 1: + for ( + i = this._activeBuffer.y, + this._dirtyRowTracker.markDirty(i), + this._eraseInBufferLine( + i, + 0, + this._activeBuffer.x + 1, + !0, + t, + ), + this._activeBuffer.x + 1 >= this._bufferService.cols && + (this._activeBuffer.lines.get(i + 1).isWrapped = !1); + i--; + + ) + this._resetBufferLine(i, t); + this._dirtyRowTracker.markDirty(0); + break; + case 2: + for ( + i = this._bufferService.rows, + this._dirtyRowTracker.markDirty(i - 1); + i--; + + ) + this._resetBufferLine(i, t); + this._dirtyRowTracker.markDirty(0); + break; + case 3: + const e = + this._activeBuffer.lines.length - this._bufferService.rows; + e > 0 && + (this._activeBuffer.lines.trimStart(e), + (this._activeBuffer.ybase = Math.max( + this._activeBuffer.ybase - e, + 0, + )), + (this._activeBuffer.ydisp = Math.max( + this._activeBuffer.ydisp - e, + 0, + )), + this._onScroll.fire(0)); + } + return !0; + } + eraseInLine(e, t = !1) { + switch ( + (this._restrictCursor(this._bufferService.cols), e.params[0]) + ) { + case 0: + this._eraseInBufferLine( + this._activeBuffer.y, + this._activeBuffer.x, + this._bufferService.cols, + 0 === this._activeBuffer.x, + t, + ); + break; + case 1: + this._eraseInBufferLine( + this._activeBuffer.y, + 0, + this._activeBuffer.x + 1, + !1, + t, + ); + break; + case 2: + this._eraseInBufferLine( + this._activeBuffer.y, + 0, + this._bufferService.cols, + !0, + t, + ); + } + return ( + this._dirtyRowTracker.markDirty(this._activeBuffer.y), + !0 + ); + } + insertLines(e) { + this._restrictCursor(); + let t = e.params[0] || 1; + if ( + this._activeBuffer.y > this._activeBuffer.scrollBottom || + this._activeBuffer.y < this._activeBuffer.scrollTop + ) + return !0; + const i = this._activeBuffer.ybase + this._activeBuffer.y, + s = + this._bufferService.rows - + 1 - + this._activeBuffer.scrollBottom, + r = + this._bufferService.rows - + 1 + + this._activeBuffer.ybase - + s + + 1; + for (; t--; ) + (this._activeBuffer.lines.splice(r - 1, 1), + this._activeBuffer.lines.splice( + i, + 0, + this._activeBuffer.getBlankLine(this._eraseAttrData()), + )); + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.y, + this._activeBuffer.scrollBottom, + ), + (this._activeBuffer.x = 0), + !0 + ); + } + deleteLines(e) { + this._restrictCursor(); + let t = e.params[0] || 1; + if ( + this._activeBuffer.y > this._activeBuffer.scrollBottom || + this._activeBuffer.y < this._activeBuffer.scrollTop + ) + return !0; + const i = this._activeBuffer.ybase + this._activeBuffer.y; + let s; + for ( + s = + this._bufferService.rows - + 1 - + this._activeBuffer.scrollBottom, + s = + this._bufferService.rows - 1 + this._activeBuffer.ybase - s; + t--; + + ) + (this._activeBuffer.lines.splice(i, 1), + this._activeBuffer.lines.splice( + s, + 0, + this._activeBuffer.getBlankLine(this._eraseAttrData()), + )); + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.y, + this._activeBuffer.scrollBottom, + ), + (this._activeBuffer.x = 0), + !0 + ); + } + insertChars(e) { + this._restrictCursor(); + const t = this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ); + return ( + t && + (t.insertCells( + this._activeBuffer.x, + e.params[0] || 1, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + ), + this._dirtyRowTracker.markDirty(this._activeBuffer.y)), + !0 + ); + } + deleteChars(e) { + this._restrictCursor(); + const t = this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ); + return ( + t && + (t.deleteCells( + this._activeBuffer.x, + e.params[0] || 1, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + ), + this._dirtyRowTracker.markDirty(this._activeBuffer.y)), + !0 + ); + } + scrollUp(e) { + let t = e.params[0] || 1; + for (; t--; ) + (this._activeBuffer.lines.splice( + this._activeBuffer.ybase + this._activeBuffer.scrollTop, + 1, + ), + this._activeBuffer.lines.splice( + this._activeBuffer.ybase + this._activeBuffer.scrollBottom, + 0, + this._activeBuffer.getBlankLine(this._eraseAttrData()), + )); + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.scrollTop, + this._activeBuffer.scrollBottom, + ), + !0 + ); + } + scrollDown(e) { + let t = e.params[0] || 1; + for (; t--; ) + (this._activeBuffer.lines.splice( + this._activeBuffer.ybase + this._activeBuffer.scrollBottom, + 1, + ), + this._activeBuffer.lines.splice( + this._activeBuffer.ybase + this._activeBuffer.scrollTop, + 0, + this._activeBuffer.getBlankLine(l.DEFAULT_ATTR_DATA), + )); + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.scrollTop, + this._activeBuffer.scrollBottom, + ), + !0 + ); + } + scrollLeft(e) { + if ( + this._activeBuffer.y > this._activeBuffer.scrollBottom || + this._activeBuffer.y < this._activeBuffer.scrollTop + ) + return !0; + const t = e.params[0] || 1; + for ( + let e = this._activeBuffer.scrollTop; + e <= this._activeBuffer.scrollBottom; + ++e + ) { + const i = this._activeBuffer.lines.get( + this._activeBuffer.ybase + e, + ); + (i.deleteCells( + 0, + t, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + ), + (i.isWrapped = !1)); + } + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.scrollTop, + this._activeBuffer.scrollBottom, + ), + !0 + ); + } + scrollRight(e) { + if ( + this._activeBuffer.y > this._activeBuffer.scrollBottom || + this._activeBuffer.y < this._activeBuffer.scrollTop + ) + return !0; + const t = e.params[0] || 1; + for ( + let e = this._activeBuffer.scrollTop; + e <= this._activeBuffer.scrollBottom; + ++e + ) { + const i = this._activeBuffer.lines.get( + this._activeBuffer.ybase + e, + ); + (i.insertCells( + 0, + t, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + ), + (i.isWrapped = !1)); + } + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.scrollTop, + this._activeBuffer.scrollBottom, + ), + !0 + ); + } + insertColumns(e) { + if ( + this._activeBuffer.y > this._activeBuffer.scrollBottom || + this._activeBuffer.y < this._activeBuffer.scrollTop + ) + return !0; + const t = e.params[0] || 1; + for ( + let e = this._activeBuffer.scrollTop; + e <= this._activeBuffer.scrollBottom; + ++e + ) { + const i = this._activeBuffer.lines.get( + this._activeBuffer.ybase + e, + ); + (i.insertCells( + this._activeBuffer.x, + t, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + ), + (i.isWrapped = !1)); + } + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.scrollTop, + this._activeBuffer.scrollBottom, + ), + !0 + ); + } + deleteColumns(e) { + if ( + this._activeBuffer.y > this._activeBuffer.scrollBottom || + this._activeBuffer.y < this._activeBuffer.scrollTop + ) + return !0; + const t = e.params[0] || 1; + for ( + let e = this._activeBuffer.scrollTop; + e <= this._activeBuffer.scrollBottom; + ++e + ) { + const i = this._activeBuffer.lines.get( + this._activeBuffer.ybase + e, + ); + (i.deleteCells( + this._activeBuffer.x, + t, + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + ), + (i.isWrapped = !1)); + } + return ( + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.scrollTop, + this._activeBuffer.scrollBottom, + ), + !0 + ); + } + eraseChars(e) { + this._restrictCursor(); + const t = this._activeBuffer.lines.get( + this._activeBuffer.ybase + this._activeBuffer.y, + ); + return ( + t && + (t.replaceCells( + this._activeBuffer.x, + this._activeBuffer.x + (e.params[0] || 1), + this._activeBuffer.getNullCell(this._eraseAttrData()), + this._eraseAttrData(), + ), + this._dirtyRowTracker.markDirty(this._activeBuffer.y)), + !0 + ); + } + repeatPrecedingCharacter(e) { + if (!this._parser.precedingCodepoint) return !0; + const t = e.params[0] || 1, + i = new Uint32Array(t); + for (let e = 0; e < t; ++e) + i[e] = this._parser.precedingCodepoint; + return (this.print(i, 0, i.length), !0); + } + sendDeviceAttributesPrimary(e) { + return ( + e.params[0] > 0 || + (this._is("xterm") || + this._is("rxvt-unicode") || + this._is("screen") + ? this._coreService.triggerDataEvent(n.C0.ESC + "[?1;2c") + : this._is("linux") && + this._coreService.triggerDataEvent(n.C0.ESC + "[?6c")), + !0 + ); + } + sendDeviceAttributesSecondary(e) { + return ( + e.params[0] > 0 || + (this._is("xterm") + ? this._coreService.triggerDataEvent( + n.C0.ESC + "[>0;276;0c", + ) + : this._is("rxvt-unicode") + ? this._coreService.triggerDataEvent( + n.C0.ESC + "[>85;95;0c", + ) + : this._is("linux") + ? this._coreService.triggerDataEvent(e.params[0] + "c") + : this._is("screen") && + this._coreService.triggerDataEvent( + n.C0.ESC + "[>83;40003;0c", + )), + !0 + ); + } + _is(e) { + return ( + 0 === (this._optionsService.rawOptions.termName + "").indexOf(e) + ); + } + setMode(e) { + for (let t = 0; t < e.length; t++) + switch (e.params[t]) { + case 4: + this._coreService.modes.insertMode = !0; + break; + case 20: + this._optionsService.options.convertEol = !0; + } + return !0; + } + setModePrivate(e) { + for (let t = 0; t < e.length; t++) + switch (e.params[t]) { + case 1: + this._coreService.decPrivateModes.applicationCursorKeys = + !0; + break; + case 2: + (this._charsetService.setgCharset(0, o.DEFAULT_CHARSET), + this._charsetService.setgCharset(1, o.DEFAULT_CHARSET), + this._charsetService.setgCharset(2, o.DEFAULT_CHARSET), + this._charsetService.setgCharset(3, o.DEFAULT_CHARSET)); + break; + case 3: + this._optionsService.rawOptions.windowOptions.setWinLines && + (this._bufferService.resize( + 132, + this._bufferService.rows, + ), + this._onRequestReset.fire()); + break; + case 6: + ((this._coreService.decPrivateModes.origin = !0), + this._setCursor(0, 0)); + break; + case 7: + this._coreService.decPrivateModes.wraparound = !0; + break; + case 12: + this._optionsService.options.cursorBlink = !0; + break; + case 45: + this._coreService.decPrivateModes.reverseWraparound = !0; + break; + case 66: + (this._logService.debug( + "Serial port requested application keypad.", + ), + (this._coreService.decPrivateModes.applicationKeypad = + !0), + this._onRequestSyncScrollBar.fire()); + break; + case 9: + this._coreMouseService.activeProtocol = "X10"; + break; + case 1e3: + this._coreMouseService.activeProtocol = "VT200"; + break; + case 1002: + this._coreMouseService.activeProtocol = "DRAG"; + break; + case 1003: + this._coreMouseService.activeProtocol = "ANY"; + break; + case 1004: + ((this._coreService.decPrivateModes.sendFocus = !0), + this._onRequestSendFocus.fire()); + break; + case 1005: + this._logService.debug( + "DECSET 1005 not supported (see #2507)", + ); + break; + case 1006: + this._coreMouseService.activeEncoding = "SGR"; + break; + case 1015: + this._logService.debug( + "DECSET 1015 not supported (see #2507)", + ); + break; + case 1016: + this._coreMouseService.activeEncoding = "SGR_PIXELS"; + break; + case 25: + this._coreService.isCursorHidden = !1; + break; + case 1048: + this.saveCursor(); + break; + case 1049: + this.saveCursor(); + case 47: + case 1047: + (this._bufferService.buffers.activateAltBuffer( + this._eraseAttrData(), + ), + (this._coreService.isCursorInitialized = !0), + this._onRequestRefreshRows.fire( + 0, + this._bufferService.rows - 1, + ), + this._onRequestSyncScrollBar.fire()); + break; + case 2004: + this._coreService.decPrivateModes.bracketedPasteMode = !0; + } + return !0; + } + resetMode(e) { + for (let t = 0; t < e.length; t++) + switch (e.params[t]) { + case 4: + this._coreService.modes.insertMode = !1; + break; + case 20: + this._optionsService.options.convertEol = !1; + } + return !0; + } + resetModePrivate(e) { + for (let t = 0; t < e.length; t++) + switch (e.params[t]) { + case 1: + this._coreService.decPrivateModes.applicationCursorKeys = + !1; + break; + case 3: + this._optionsService.rawOptions.windowOptions.setWinLines && + (this._bufferService.resize(80, this._bufferService.rows), + this._onRequestReset.fire()); + break; + case 6: + ((this._coreService.decPrivateModes.origin = !1), + this._setCursor(0, 0)); + break; + case 7: + this._coreService.decPrivateModes.wraparound = !1; + break; + case 12: + this._optionsService.options.cursorBlink = !1; + break; + case 45: + this._coreService.decPrivateModes.reverseWraparound = !1; + break; + case 66: + (this._logService.debug("Switching back to normal keypad."), + (this._coreService.decPrivateModes.applicationKeypad = + !1), + this._onRequestSyncScrollBar.fire()); + break; + case 9: + case 1e3: + case 1002: + case 1003: + this._coreMouseService.activeProtocol = "NONE"; + break; + case 1004: + this._coreService.decPrivateModes.sendFocus = !1; + break; + case 1005: + this._logService.debug( + "DECRST 1005 not supported (see #2507)", + ); + break; + case 1006: + case 1016: + this._coreMouseService.activeEncoding = "DEFAULT"; + break; + case 1015: + this._logService.debug( + "DECRST 1015 not supported (see #2507)", + ); + break; + case 25: + this._coreService.isCursorHidden = !0; + break; + case 1048: + this.restoreCursor(); + break; + case 1049: + case 47: + case 1047: + (this._bufferService.buffers.activateNormalBuffer(), + 1049 === e.params[t] && this.restoreCursor(), + (this._coreService.isCursorInitialized = !0), + this._onRequestRefreshRows.fire( + 0, + this._bufferService.rows - 1, + ), + this._onRequestSyncScrollBar.fire()); + break; + case 2004: + this._coreService.decPrivateModes.bracketedPasteMode = !1; + } + return !0; + } + requestMode(e, t) { + const i = this._coreService.decPrivateModes, + { activeProtocol: s, activeEncoding: r } = + this._coreMouseService, + o = this._coreService, + { buffers: a, cols: h } = this._bufferService, + { active: c, alt: l } = a, + d = this._optionsService.rawOptions, + _ = (e) => (e ? 1 : 2), + u = e.params[0]; + return ( + (f = u), + (v = t + ? 2 === u + ? 4 + : 4 === u + ? _(o.modes.insertMode) + : 12 === u + ? 3 + : 20 === u + ? _(d.convertEol) + : 0 + : 1 === u + ? _(i.applicationCursorKeys) + : 3 === u + ? d.windowOptions.setWinLines + ? 80 === h + ? 2 + : 132 === h + ? 1 + : 0 + : 0 + : 6 === u + ? _(i.origin) + : 7 === u + ? _(i.wraparound) + : 8 === u + ? 3 + : 9 === u + ? _("X10" === s) + : 12 === u + ? _(d.cursorBlink) + : 25 === u + ? _(!o.isCursorHidden) + : 45 === u + ? _(i.reverseWraparound) + : 66 === u + ? _(i.applicationKeypad) + : 67 === u + ? 4 + : 1e3 === u + ? _("VT200" === s) + : 1002 === u + ? _("DRAG" === s) + : 1003 === u + ? _("ANY" === s) + : 1004 === u + ? _(i.sendFocus) + : 1005 === u + ? 4 + : 1006 === u + ? _("SGR" === r) + : 1015 === u + ? 4 + : 1016 === u + ? _("SGR_PIXELS" === r) + : 1048 === u + ? 1 + : 47 === u || + 1047 === u || + 1049 === u + ? _(c === l) + : 2004 === u + ? _( + i.bracketedPasteMode, + ) + : 0), + o.triggerDataEvent(`${n.C0.ESC}[${t ? "" : "?"}${f};${v}$y`), + !0 + ); + var f, v; + } + _updateAttrColor(e, t, i, s, r) { + return ( + 2 === t + ? ((e |= 50331648), + (e &= -16777216), + (e |= f.AttributeData.fromColorRGB([i, s, r]))) + : 5 === t && ((e &= -50331904), (e |= 33554432 | (255 & i))), + e + ); + } + _extractColor(e, t, i) { + const s = [0, 0, -1, 0, 0, 0]; + let r = 0, + n = 0; + do { + if (((s[n + r] = e.params[t + n]), e.hasSubParams(t + n))) { + const i = e.getSubParams(t + n); + let o = 0; + do { + (5 === s[1] && (r = 1), (s[n + o + 1 + r] = i[o])); + } while (++o < i.length && o + n + 1 + r < s.length); + break; + } + if ((5 === s[1] && n + r >= 2) || (2 === s[1] && n + r >= 5)) + break; + s[1] && (r = 1); + } while (++n + t < e.length && n + r < s.length); + for (let e = 2; e < s.length; ++e) -1 === s[e] && (s[e] = 0); + switch (s[0]) { + case 38: + i.fg = this._updateAttrColor(i.fg, s[1], s[3], s[4], s[5]); + break; + case 48: + i.bg = this._updateAttrColor(i.bg, s[1], s[3], s[4], s[5]); + break; + case 58: + ((i.extended = i.extended.clone()), + (i.extended.underlineColor = this._updateAttrColor( + i.extended.underlineColor, + s[1], + s[3], + s[4], + s[5], + ))); + } + return n; + } + _processUnderline(e, t) { + ((t.extended = t.extended.clone()), + (!~e || e > 5) && (e = 1), + (t.extended.underlineStyle = e), + (t.fg |= 268435456), + 0 === e && (t.fg &= -268435457), + t.updateExtended()); + } + _processSGR0(e) { + ((e.fg = l.DEFAULT_ATTR_DATA.fg), + (e.bg = l.DEFAULT_ATTR_DATA.bg), + (e.extended = e.extended.clone()), + (e.extended.underlineStyle = 0), + (e.extended.underlineColor &= -67108864), + e.updateExtended()); + } + charAttributes(e) { + if (1 === e.length && 0 === e.params[0]) + return (this._processSGR0(this._curAttrData), !0); + const t = e.length; + let i; + const s = this._curAttrData; + for (let r = 0; r < t; r++) + ((i = e.params[r]), + i >= 30 && i <= 37 + ? ((s.fg &= -50331904), (s.fg |= 16777216 | (i - 30))) + : i >= 40 && i <= 47 + ? ((s.bg &= -50331904), (s.bg |= 16777216 | (i - 40))) + : i >= 90 && i <= 97 + ? ((s.fg &= -50331904), (s.fg |= 16777224 | (i - 90))) + : i >= 100 && i <= 107 + ? ((s.bg &= -50331904), + (s.bg |= 16777224 | (i - 100))) + : 0 === i + ? this._processSGR0(s) + : 1 === i + ? (s.fg |= 134217728) + : 3 === i + ? (s.bg |= 67108864) + : 4 === i + ? ((s.fg |= 268435456), + this._processUnderline( + e.hasSubParams(r) + ? e.getSubParams(r)[0] + : 1, + s, + )) + : 5 === i + ? (s.fg |= 536870912) + : 7 === i + ? (s.fg |= 67108864) + : 8 === i + ? (s.fg |= 1073741824) + : 9 === i + ? (s.fg |= 2147483648) + : 2 === i + ? (s.bg |= 134217728) + : 21 === i + ? this._processUnderline(2, s) + : 22 === i + ? ((s.fg &= -134217729), + (s.bg &= -134217729)) + : 23 === i + ? (s.bg &= -67108865) + : 24 === i + ? ((s.fg &= -268435457), + this._processUnderline( + 0, + s, + )) + : 25 === i + ? (s.fg &= -536870913) + : 27 === i + ? (s.fg &= -67108865) + : 28 === i + ? (s.fg &= + -1073741825) + : 29 === i + ? (s.fg &= 2147483647) + : 39 === i + ? ((s.fg &= + -67108864), + (s.fg |= + 16777215 & + l + .DEFAULT_ATTR_DATA + .fg)) + : 49 === i + ? ((s.bg &= + -67108864), + (s.bg |= + 16777215 & + l + .DEFAULT_ATTR_DATA + .bg)) + : 38 === i || + 48 === i || + 58 === i + ? (r += + this._extractColor( + e, + r, + s, + )) + : 53 === i + ? (s.bg |= 1073741824) + : 55 === i + ? (s.bg &= + -1073741825) + : 59 === i + ? ((s.extended = + s.extended.clone()), + (s.extended.underlineColor = + -1), + s.updateExtended()) + : 100 === + i + ? ((s.fg &= + -67108864), + (s.fg |= + 16777215 & + l + .DEFAULT_ATTR_DATA + .fg), + (s.bg &= + -67108864), + (s.bg |= + 16777215 & + l + .DEFAULT_ATTR_DATA + .bg)) + : this._logService.debug( + "Unknown SGR attribute: %d.", + i, + )); + return !0; + } + deviceStatus(e) { + switch (e.params[0]) { + case 5: + this._coreService.triggerDataEvent(`${n.C0.ESC}[0n`); + break; + case 6: + const e = this._activeBuffer.y + 1, + t = this._activeBuffer.x + 1; + this._coreService.triggerDataEvent(`${n.C0.ESC}[${e};${t}R`); + } + return !0; + } + deviceStatusPrivate(e) { + if (6 === e.params[0]) { + const e = this._activeBuffer.y + 1, + t = this._activeBuffer.x + 1; + this._coreService.triggerDataEvent(`${n.C0.ESC}[?${e};${t}R`); + } + return !0; + } + softReset(e) { + return ( + (this._coreService.isCursorHidden = !1), + this._onRequestSyncScrollBar.fire(), + (this._activeBuffer.scrollTop = 0), + (this._activeBuffer.scrollBottom = + this._bufferService.rows - 1), + (this._curAttrData = l.DEFAULT_ATTR_DATA.clone()), + this._coreService.reset(), + this._charsetService.reset(), + (this._activeBuffer.savedX = 0), + (this._activeBuffer.savedY = this._activeBuffer.ybase), + (this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg), + (this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg), + (this._activeBuffer.savedCharset = + this._charsetService.charset), + (this._coreService.decPrivateModes.origin = !1), + !0 + ); + } + setCursorStyle(e) { + const t = e.params[0] || 1; + switch (t) { + case 1: + case 2: + this._optionsService.options.cursorStyle = "block"; + break; + case 3: + case 4: + this._optionsService.options.cursorStyle = "underline"; + break; + case 5: + case 6: + this._optionsService.options.cursorStyle = "bar"; + } + const i = t % 2 == 1; + return ((this._optionsService.options.cursorBlink = i), !0); + } + setScrollRegion(e) { + const t = e.params[0] || 1; + let i; + return ( + (e.length < 2 || + (i = e.params[1]) > this._bufferService.rows || + 0 === i) && + (i = this._bufferService.rows), + i > t && + ((this._activeBuffer.scrollTop = t - 1), + (this._activeBuffer.scrollBottom = i - 1), + this._setCursor(0, 0)), + !0 + ); + } + windowOptions(e) { + if ( + !b(e.params[0], this._optionsService.rawOptions.windowOptions) + ) + return !0; + const t = e.length > 1 ? e.params[1] : 0; + switch (e.params[0]) { + case 14: + 2 !== t && + this._onRequestWindowsOptionsReport.fire( + y.GET_WIN_SIZE_PIXELS, + ); + break; + case 16: + this._onRequestWindowsOptionsReport.fire( + y.GET_CELL_SIZE_PIXELS, + ); + break; + case 18: + this._bufferService && + this._coreService.triggerDataEvent( + `${n.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`, + ); + break; + case 22: + ((0 !== t && 2 !== t) || + (this._windowTitleStack.push(this._windowTitle), + this._windowTitleStack.length > 10 && + this._windowTitleStack.shift()), + (0 !== t && 1 !== t) || + (this._iconNameStack.push(this._iconName), + this._iconNameStack.length > 10 && + this._iconNameStack.shift())); + break; + case 23: + ((0 !== t && 2 !== t) || + (this._windowTitleStack.length && + this.setTitle(this._windowTitleStack.pop())), + (0 !== t && 1 !== t) || + (this._iconNameStack.length && + this.setIconName(this._iconNameStack.pop()))); + } + return !0; + } + saveCursor(e) { + return ( + (this._activeBuffer.savedX = this._activeBuffer.x), + (this._activeBuffer.savedY = + this._activeBuffer.ybase + this._activeBuffer.y), + (this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg), + (this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg), + (this._activeBuffer.savedCharset = + this._charsetService.charset), + !0 + ); + } + restoreCursor(e) { + return ( + (this._activeBuffer.x = this._activeBuffer.savedX || 0), + (this._activeBuffer.y = Math.max( + this._activeBuffer.savedY - this._activeBuffer.ybase, + 0, + )), + (this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg), + (this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg), + (this._charsetService.charset = this._savedCharset), + this._activeBuffer.savedCharset && + (this._charsetService.charset = + this._activeBuffer.savedCharset), + this._restrictCursor(), + !0 + ); + } + setTitle(e) { + return ((this._windowTitle = e), this._onTitleChange.fire(e), !0); + } + setIconName(e) { + return ((this._iconName = e), !0); + } + setOrReportIndexedColor(e) { + const t = [], + i = e.split(";"); + for (; i.length > 1; ) { + const e = i.shift(), + s = i.shift(); + if (/^\d+$/.exec(e)) { + const i = parseInt(e); + if (L(i)) + if ("?" === s) t.push({ type: 0, index: i }); + else { + const e = (0, m.parseColor)(s); + e && t.push({ type: 1, index: i, color: e }); + } + } + } + return (t.length && this._onColor.fire(t), !0); + } + setHyperlink(e) { + const t = e.split(";"); + return ( + !(t.length < 2) && + (t[1] + ? this._createHyperlink(t[0], t[1]) + : !t[0] && this._finishHyperlink()) + ); + } + _createHyperlink(e, t) { + this._getCurrentLinkId() && this._finishHyperlink(); + const i = e.split(":"); + let s; + const r = i.findIndex((e) => e.startsWith("id=")); + return ( + -1 !== r && (s = i[r].slice(3) || void 0), + (this._curAttrData.extended = + this._curAttrData.extended.clone()), + (this._curAttrData.extended.urlId = + this._oscLinkService.registerLink({ id: s, uri: t })), + this._curAttrData.updateExtended(), + !0 + ); + } + _finishHyperlink() { + return ( + (this._curAttrData.extended = + this._curAttrData.extended.clone()), + (this._curAttrData.extended.urlId = 0), + this._curAttrData.updateExtended(), + !0 + ); + } + _setOrReportSpecialColor(e, t) { + const i = e.split(";"); + for ( + let e = 0; + e < i.length && !(t >= this._specialColors.length); + ++e, ++t + ) + if ("?" === i[e]) + this._onColor.fire([ + { type: 0, index: this._specialColors[t] }, + ]); + else { + const s = (0, m.parseColor)(i[e]); + s && + this._onColor.fire([ + { type: 1, index: this._specialColors[t], color: s }, + ]); + } + return !0; + } + setOrReportFgColor(e) { + return this._setOrReportSpecialColor(e, 0); + } + setOrReportBgColor(e) { + return this._setOrReportSpecialColor(e, 1); + } + setOrReportCursorColor(e) { + return this._setOrReportSpecialColor(e, 2); + } + restoreIndexedColor(e) { + if (!e) return (this._onColor.fire([{ type: 2 }]), !0); + const t = [], + i = e.split(";"); + for (let e = 0; e < i.length; ++e) + if (/^\d+$/.exec(i[e])) { + const s = parseInt(i[e]); + L(s) && t.push({ type: 2, index: s }); + } + return (t.length && this._onColor.fire(t), !0); + } + restoreFgColor(e) { + return (this._onColor.fire([{ type: 2, index: 256 }]), !0); + } + restoreBgColor(e) { + return (this._onColor.fire([{ type: 2, index: 257 }]), !0); + } + restoreCursorColor(e) { + return (this._onColor.fire([{ type: 2, index: 258 }]), !0); + } + nextLine() { + return ((this._activeBuffer.x = 0), this.index(), !0); + } + keypadApplicationMode() { + return ( + this._logService.debug( + "Serial port requested application keypad.", + ), + (this._coreService.decPrivateModes.applicationKeypad = !0), + this._onRequestSyncScrollBar.fire(), + !0 + ); + } + keypadNumericMode() { + return ( + this._logService.debug("Switching back to normal keypad."), + (this._coreService.decPrivateModes.applicationKeypad = !1), + this._onRequestSyncScrollBar.fire(), + !0 + ); + } + selectDefaultCharset() { + return ( + this._charsetService.setgLevel(0), + this._charsetService.setgCharset(0, o.DEFAULT_CHARSET), + !0 + ); + } + selectCharset(e) { + return 2 !== e.length + ? (this.selectDefaultCharset(), !0) + : ("/" === e[0] || + this._charsetService.setgCharset( + S[e[0]], + o.CHARSETS[e[1]] || o.DEFAULT_CHARSET, + ), + !0); + } + index() { + return ( + this._restrictCursor(), + this._activeBuffer.y++, + this._activeBuffer.y === this._activeBuffer.scrollBottom + 1 + ? (this._activeBuffer.y--, + this._bufferService.scroll(this._eraseAttrData())) + : this._activeBuffer.y >= this._bufferService.rows && + (this._activeBuffer.y = this._bufferService.rows - 1), + this._restrictCursor(), + !0 + ); + } + tabSet() { + return ((this._activeBuffer.tabs[this._activeBuffer.x] = !0), !0); + } + reverseIndex() { + if ( + (this._restrictCursor(), + this._activeBuffer.y === this._activeBuffer.scrollTop) + ) { + const e = + this._activeBuffer.scrollBottom - + this._activeBuffer.scrollTop; + (this._activeBuffer.lines.shiftElements( + this._activeBuffer.ybase + this._activeBuffer.y, + e, + 1, + ), + this._activeBuffer.lines.set( + this._activeBuffer.ybase + this._activeBuffer.y, + this._activeBuffer.getBlankLine(this._eraseAttrData()), + ), + this._dirtyRowTracker.markRangeDirty( + this._activeBuffer.scrollTop, + this._activeBuffer.scrollBottom, + )); + } else (this._activeBuffer.y--, this._restrictCursor()); + return !0; + } + fullReset() { + return (this._parser.reset(), this._onRequestReset.fire(), !0); + } + reset() { + ((this._curAttrData = l.DEFAULT_ATTR_DATA.clone()), + (this._eraseAttrDataInternal = l.DEFAULT_ATTR_DATA.clone())); + } + _eraseAttrData() { + return ( + (this._eraseAttrDataInternal.bg &= -67108864), + (this._eraseAttrDataInternal.bg |= + 67108863 & this._curAttrData.bg), + this._eraseAttrDataInternal + ); + } + setgLevel(e) { + return (this._charsetService.setgLevel(e), !0); + } + screenAlignmentPattern() { + const e = new u.CellData(); + ((e.content = (1 << 22) | "E".charCodeAt(0)), + (e.fg = this._curAttrData.fg), + (e.bg = this._curAttrData.bg), + this._setCursor(0, 0)); + for (let t = 0; t < this._bufferService.rows; ++t) { + const i = this._activeBuffer.ybase + this._activeBuffer.y + t, + s = this._activeBuffer.lines.get(i); + s && (s.fill(e), (s.isWrapped = !1)); + } + return ( + this._dirtyRowTracker.markAllDirty(), + this._setCursor(0, 0), + !0 + ); + } + requestStatusString(e, t) { + const i = this._bufferService.buffer, + s = this._optionsService.rawOptions; + return ((e) => ( + this._coreService.triggerDataEvent( + `${n.C0.ESC}${e}${n.C0.ESC}\\`, + ), + !0 + ))( + '"q' === e + ? `P1$r${this._curAttrData.isProtected() ? 1 : 0}"q` + : '"p' === e + ? 'P1$r61;1"p' + : "r" === e + ? `P1$r${i.scrollTop + 1};${i.scrollBottom + 1}r` + : "m" === e + ? "P1$r0m" + : " q" === e + ? `P1$r${{ block: 2, underline: 4, bar: 6 }[s.cursorStyle] - (s.cursorBlink ? 1 : 0)} q` + : "P0$r", + ); + } + markRangeDirty(e, t) { + this._dirtyRowTracker.markRangeDirty(e, t); + } + } + t.InputHandler = E; + let k = class { + constructor(e) { + ((this._bufferService = e), this.clearRange()); + } + clearRange() { + ((this.start = this._bufferService.buffer.y), + (this.end = this._bufferService.buffer.y)); + } + markDirty(e) { + e < this.start + ? (this.start = e) + : e > this.end && (this.end = e); + } + markRangeDirty(e, t) { + (e > t && ((w = e), (e = t), (t = w)), + e < this.start && (this.start = e), + t > this.end && (this.end = t)); + } + markAllDirty() { + this.markRangeDirty(0, this._bufferService.rows - 1); + } + }; + function L(e) { + return 0 <= e && e < 256; + } + k = s([r(0, v.IBufferService)], k); + }, + 844: (e, t) => { + function i(e) { + for (const t of e) t.dispose(); + e.length = 0; + } + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.getDisposeArrayDisposable = + t.disposeArray = + t.toDisposable = + t.MutableDisposable = + t.Disposable = + void 0), + (t.Disposable = class { + constructor() { + ((this._disposables = []), (this._isDisposed = !1)); + } + dispose() { + this._isDisposed = !0; + for (const e of this._disposables) e.dispose(); + this._disposables.length = 0; + } + register(e) { + return (this._disposables.push(e), e); + } + unregister(e) { + const t = this._disposables.indexOf(e); + -1 !== t && this._disposables.splice(t, 1); + } + }), + (t.MutableDisposable = class { + constructor() { + this._isDisposed = !1; + } + get value() { + return this._isDisposed ? void 0 : this._value; + } + set value(e) { + var t; + this._isDisposed || + e === this._value || + (null === (t = this._value) || void 0 === t || t.dispose(), + (this._value = e)); + } + clear() { + this.value = void 0; + } + dispose() { + var e; + ((this._isDisposed = !0), + null === (e = this._value) || void 0 === e || e.dispose(), + (this._value = void 0)); + } + }), + (t.toDisposable = function (e) { + return { dispose: e }; + }), + (t.disposeArray = i), + (t.getDisposeArrayDisposable = function (e) { + return { dispose: () => i(e) }; + })); + }, + 1505: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.FourKeyMap = t.TwoKeyMap = void 0)); + class i { + constructor() { + this._data = {}; + } + set(e, t, i) { + (this._data[e] || (this._data[e] = {}), (this._data[e][t] = i)); + } + get(e, t) { + return this._data[e] ? this._data[e][t] : void 0; + } + clear() { + this._data = {}; + } + } + ((t.TwoKeyMap = i), + (t.FourKeyMap = class { + constructor() { + this._data = new i(); + } + set(e, t, s, r, n) { + (this._data.get(e, t) || this._data.set(e, t, new i()), + this._data.get(e, t).set(s, r, n)); + } + get(e, t, i, s) { + var r; + return null === (r = this._data.get(e, t)) || void 0 === r + ? void 0 + : r.get(i, s); + } + clear() { + this._data.clear(); + } + })); + }, + 6114: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.isChromeOS = + t.isLinux = + t.isWindows = + t.isIphone = + t.isIpad = + t.isMac = + t.getSafariVersion = + t.isSafari = + t.isLegacyEdge = + t.isFirefox = + t.isNode = + void 0), + (t.isNode = "undefined" == typeof navigator)); + const i = t.isNode ? "node" : navigator.userAgent, + s = t.isNode ? "node" : navigator.platform; + ((t.isFirefox = i.includes("Firefox")), + (t.isLegacyEdge = i.includes("Edge")), + (t.isSafari = /^((?!chrome|android).)*safari/i.test(i)), + (t.getSafariVersion = function () { + if (!t.isSafari) return 0; + const e = i.match(/Version\/(\d+)/); + return null === e || e.length < 2 ? 0 : parseInt(e[1]); + }), + (t.isMac = ["Macintosh", "MacIntel", "MacPPC", "Mac68K"].includes( + s, + )), + (t.isIpad = "iPad" === s), + (t.isIphone = "iPhone" === s), + (t.isWindows = ["Windows", "Win16", "Win32", "WinCE"].includes(s)), + (t.isLinux = s.indexOf("Linux") >= 0), + (t.isChromeOS = /\bCrOS\b/.test(i))); + }, + 6106: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.SortedList = void 0)); + let i = 0; + t.SortedList = class { + constructor(e) { + ((this._getKey = e), (this._array = [])); + } + clear() { + this._array.length = 0; + } + insert(e) { + 0 !== this._array.length + ? ((i = this._search(this._getKey(e))), + this._array.splice(i, 0, e)) + : this._array.push(e); + } + delete(e) { + if (0 === this._array.length) return !1; + const t = this._getKey(e); + if (void 0 === t) return !1; + if (((i = this._search(t)), -1 === i)) return !1; + if (this._getKey(this._array[i]) !== t) return !1; + do { + if (this._array[i] === e) return (this._array.splice(i, 1), !0); + } while ( + ++i < this._array.length && + this._getKey(this._array[i]) === t + ); + return !1; + } + *getKeyIterator(e) { + if ( + 0 !== this._array.length && + ((i = this._search(e)), + !(i < 0 || i >= this._array.length) && + this._getKey(this._array[i]) === e) + ) + do { + yield this._array[i]; + } while ( + ++i < this._array.length && + this._getKey(this._array[i]) === e + ); + } + forEachByKey(e, t) { + if ( + 0 !== this._array.length && + ((i = this._search(e)), + !(i < 0 || i >= this._array.length) && + this._getKey(this._array[i]) === e) + ) + do { + t(this._array[i]); + } while ( + ++i < this._array.length && + this._getKey(this._array[i]) === e + ); + } + values() { + return [...this._array].values(); + } + _search(e) { + let t = 0, + i = this._array.length - 1; + for (; i >= t; ) { + let s = (t + i) >> 1; + const r = this._getKey(this._array[s]); + if (r > e) i = s - 1; + else { + if (!(r < e)) { + for (; s > 0 && this._getKey(this._array[s - 1]) === e; ) + s--; + return s; + } + t = s + 1; + } + } + return t; + } + }; + }, + 7226: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.DebouncedIdleTask = + t.IdleTaskQueue = + t.PriorityTaskQueue = + void 0)); + const s = i(6114); + class r { + constructor() { + ((this._tasks = []), (this._i = 0)); + } + enqueue(e) { + (this._tasks.push(e), this._start()); + } + flush() { + for (; this._i < this._tasks.length; ) + this._tasks[this._i]() || this._i++; + this.clear(); + } + clear() { + (this._idleCallback && + (this._cancelCallback(this._idleCallback), + (this._idleCallback = void 0)), + (this._i = 0), + (this._tasks.length = 0)); + } + _start() { + this._idleCallback || + (this._idleCallback = this._requestCallback( + this._process.bind(this), + )); + } + _process(e) { + this._idleCallback = void 0; + let t = 0, + i = 0, + s = e.timeRemaining(), + r = 0; + for (; this._i < this._tasks.length; ) { + if ( + ((t = Date.now()), + this._tasks[this._i]() || this._i++, + (t = Math.max(1, Date.now() - t)), + (i = Math.max(t, i)), + (r = e.timeRemaining()), + 1.5 * i > r) + ) + return ( + s - t < -20 && + console.warn( + `task queue exceeded allotted deadline by ${Math.abs(Math.round(s - t))}ms`, + ), + void this._start() + ); + s = r; + } + this.clear(); + } + } + class n extends r { + _requestCallback(e) { + return setTimeout(() => e(this._createDeadline(16))); + } + _cancelCallback(e) { + clearTimeout(e); + } + _createDeadline(e) { + const t = Date.now() + e; + return { timeRemaining: () => Math.max(0, t - Date.now()) }; + } + } + ((t.PriorityTaskQueue = n), + (t.IdleTaskQueue = + !s.isNode && "requestIdleCallback" in window + ? class extends r { + _requestCallback(e) { + return requestIdleCallback(e); + } + _cancelCallback(e) { + cancelIdleCallback(e); + } + } + : n), + (t.DebouncedIdleTask = class { + constructor() { + this._queue = new t.IdleTaskQueue(); + } + set(e) { + (this._queue.clear(), this._queue.enqueue(e)); + } + flush() { + this._queue.flush(); + } + })); + }, + 9282: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.updateWindowsModeWrappedState = void 0)); + const s = i(643); + t.updateWindowsModeWrappedState = function (e) { + const t = e.buffer.lines.get(e.buffer.ybase + e.buffer.y - 1), + i = null == t ? void 0 : t.get(e.cols - 1), + r = e.buffer.lines.get(e.buffer.ybase + e.buffer.y); + r && + i && + (r.isWrapped = + i[s.CHAR_DATA_CODE_INDEX] !== s.NULL_CELL_CODE && + i[s.CHAR_DATA_CODE_INDEX] !== s.WHITESPACE_CELL_CODE); + }; + }, + 3734: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.ExtendedAttrs = t.AttributeData = void 0)); + class i { + constructor() { + ((this.fg = 0), (this.bg = 0), (this.extended = new s())); + } + static toColorRGB(e) { + return [(e >>> 16) & 255, (e >>> 8) & 255, 255 & e]; + } + static fromColorRGB(e) { + return ((255 & e[0]) << 16) | ((255 & e[1]) << 8) | (255 & e[2]); + } + clone() { + const e = new i(); + return ( + (e.fg = this.fg), + (e.bg = this.bg), + (e.extended = this.extended.clone()), + e + ); + } + isInverse() { + return 67108864 & this.fg; + } + isBold() { + return 134217728 & this.fg; + } + isUnderline() { + return this.hasExtendedAttrs() && + 0 !== this.extended.underlineStyle + ? 1 + : 268435456 & this.fg; + } + isBlink() { + return 536870912 & this.fg; + } + isInvisible() { + return 1073741824 & this.fg; + } + isItalic() { + return 67108864 & this.bg; + } + isDim() { + return 134217728 & this.bg; + } + isStrikethrough() { + return 2147483648 & this.fg; + } + isProtected() { + return 536870912 & this.bg; + } + isOverline() { + return 1073741824 & this.bg; + } + getFgColorMode() { + return 50331648 & this.fg; + } + getBgColorMode() { + return 50331648 & this.bg; + } + isFgRGB() { + return 50331648 == (50331648 & this.fg); + } + isBgRGB() { + return 50331648 == (50331648 & this.bg); + } + isFgPalette() { + return ( + 16777216 == (50331648 & this.fg) || + 33554432 == (50331648 & this.fg) + ); + } + isBgPalette() { + return ( + 16777216 == (50331648 & this.bg) || + 33554432 == (50331648 & this.bg) + ); + } + isFgDefault() { + return 0 == (50331648 & this.fg); + } + isBgDefault() { + return 0 == (50331648 & this.bg); + } + isAttributeDefault() { + return 0 === this.fg && 0 === this.bg; + } + getFgColor() { + switch (50331648 & this.fg) { + case 16777216: + case 33554432: + return 255 & this.fg; + case 50331648: + return 16777215 & this.fg; + default: + return -1; + } + } + getBgColor() { + switch (50331648 & this.bg) { + case 16777216: + case 33554432: + return 255 & this.bg; + case 50331648: + return 16777215 & this.bg; + default: + return -1; + } + } + hasExtendedAttrs() { + return 268435456 & this.bg; + } + updateExtended() { + this.extended.isEmpty() + ? (this.bg &= -268435457) + : (this.bg |= 268435456); + } + getUnderlineColor() { + if (268435456 & this.bg && ~this.extended.underlineColor) + switch (50331648 & this.extended.underlineColor) { + case 16777216: + case 33554432: + return 255 & this.extended.underlineColor; + case 50331648: + return 16777215 & this.extended.underlineColor; + default: + return this.getFgColor(); + } + return this.getFgColor(); + } + getUnderlineColorMode() { + return 268435456 & this.bg && ~this.extended.underlineColor + ? 50331648 & this.extended.underlineColor + : this.getFgColorMode(); + } + isUnderlineColorRGB() { + return 268435456 & this.bg && ~this.extended.underlineColor + ? 50331648 == (50331648 & this.extended.underlineColor) + : this.isFgRGB(); + } + isUnderlineColorPalette() { + return 268435456 & this.bg && ~this.extended.underlineColor + ? 16777216 == (50331648 & this.extended.underlineColor) || + 33554432 == (50331648 & this.extended.underlineColor) + : this.isFgPalette(); + } + isUnderlineColorDefault() { + return 268435456 & this.bg && ~this.extended.underlineColor + ? 0 == (50331648 & this.extended.underlineColor) + : this.isFgDefault(); + } + getUnderlineStyle() { + return 268435456 & this.fg + ? 268435456 & this.bg + ? this.extended.underlineStyle + : 1 + : 0; + } + } + t.AttributeData = i; + class s { + get ext() { + return this._urlId + ? (-469762049 & this._ext) | (this.underlineStyle << 26) + : this._ext; + } + set ext(e) { + this._ext = e; + } + get underlineStyle() { + return this._urlId ? 5 : (469762048 & this._ext) >> 26; + } + set underlineStyle(e) { + ((this._ext &= -469762049), (this._ext |= (e << 26) & 469762048)); + } + get underlineColor() { + return 67108863 & this._ext; + } + set underlineColor(e) { + ((this._ext &= -67108864), (this._ext |= 67108863 & e)); + } + get urlId() { + return this._urlId; + } + set urlId(e) { + this._urlId = e; + } + constructor(e = 0, t = 0) { + ((this._ext = 0), + (this._urlId = 0), + (this._ext = e), + (this._urlId = t)); + } + clone() { + return new s(this._ext, this._urlId); + } + isEmpty() { + return 0 === this.underlineStyle && 0 === this._urlId; + } + } + t.ExtendedAttrs = s; + }, + 9092: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.Buffer = t.MAX_BUFFER_SIZE = void 0)); + const s = i(6349), + r = i(7226), + n = i(3734), + o = i(8437), + a = i(4634), + h = i(511), + c = i(643), + l = i(4863), + d = i(7116); + ((t.MAX_BUFFER_SIZE = 4294967295), + (t.Buffer = class { + constructor(e, t, i) { + ((this._hasScrollback = e), + (this._optionsService = t), + (this._bufferService = i), + (this.ydisp = 0), + (this.ybase = 0), + (this.y = 0), + (this.x = 0), + (this.tabs = {}), + (this.savedY = 0), + (this.savedX = 0), + (this.savedCurAttrData = o.DEFAULT_ATTR_DATA.clone()), + (this.savedCharset = d.DEFAULT_CHARSET), + (this.markers = []), + (this._nullCell = h.CellData.fromCharData([ + 0, + c.NULL_CELL_CHAR, + c.NULL_CELL_WIDTH, + c.NULL_CELL_CODE, + ])), + (this._whitespaceCell = h.CellData.fromCharData([ + 0, + c.WHITESPACE_CELL_CHAR, + c.WHITESPACE_CELL_WIDTH, + c.WHITESPACE_CELL_CODE, + ])), + (this._isClearing = !1), + (this._memoryCleanupQueue = new r.IdleTaskQueue()), + (this._memoryCleanupPosition = 0), + (this._cols = this._bufferService.cols), + (this._rows = this._bufferService.rows), + (this.lines = new s.CircularList( + this._getCorrectBufferLength(this._rows), + )), + (this.scrollTop = 0), + (this.scrollBottom = this._rows - 1), + this.setupTabStops()); + } + getNullCell(e) { + return ( + e + ? ((this._nullCell.fg = e.fg), + (this._nullCell.bg = e.bg), + (this._nullCell.extended = e.extended)) + : ((this._nullCell.fg = 0), + (this._nullCell.bg = 0), + (this._nullCell.extended = new n.ExtendedAttrs())), + this._nullCell + ); + } + getWhitespaceCell(e) { + return ( + e + ? ((this._whitespaceCell.fg = e.fg), + (this._whitespaceCell.bg = e.bg), + (this._whitespaceCell.extended = e.extended)) + : ((this._whitespaceCell.fg = 0), + (this._whitespaceCell.bg = 0), + (this._whitespaceCell.extended = new n.ExtendedAttrs())), + this._whitespaceCell + ); + } + getBlankLine(e, t) { + return new o.BufferLine( + this._bufferService.cols, + this.getNullCell(e), + t, + ); + } + get hasScrollback() { + return this._hasScrollback && this.lines.maxLength > this._rows; + } + get isCursorInViewport() { + const e = this.ybase + this.y - this.ydisp; + return e >= 0 && e < this._rows; + } + _getCorrectBufferLength(e) { + if (!this._hasScrollback) return e; + const i = e + this._optionsService.rawOptions.scrollback; + return i > t.MAX_BUFFER_SIZE ? t.MAX_BUFFER_SIZE : i; + } + fillViewportRows(e) { + if (0 === this.lines.length) { + void 0 === e && (e = o.DEFAULT_ATTR_DATA); + let t = this._rows; + for (; t--; ) this.lines.push(this.getBlankLine(e)); + } + } + clear() { + ((this.ydisp = 0), + (this.ybase = 0), + (this.y = 0), + (this.x = 0), + (this.lines = new s.CircularList( + this._getCorrectBufferLength(this._rows), + )), + (this.scrollTop = 0), + (this.scrollBottom = this._rows - 1), + this.setupTabStops()); + } + resize(e, t) { + const i = this.getNullCell(o.DEFAULT_ATTR_DATA); + let s = 0; + const r = this._getCorrectBufferLength(t); + if ( + (r > this.lines.maxLength && (this.lines.maxLength = r), + this.lines.length > 0) + ) { + if (this._cols < e) + for (let t = 0; t < this.lines.length; t++) + s += +this.lines.get(t).resize(e, i); + let n = 0; + if (this._rows < t) + for (let s = this._rows; s < t; s++) + this.lines.length < t + this.ybase && + (this._optionsService.rawOptions.windowsMode || + void 0 !== + this._optionsService.rawOptions.windowsPty.backend || + void 0 !== + this._optionsService.rawOptions.windowsPty.buildNumber + ? this.lines.push(new o.BufferLine(e, i)) + : this.ybase > 0 && + this.lines.length <= this.ybase + this.y + n + 1 + ? (this.ybase--, + n++, + this.ydisp > 0 && this.ydisp--) + : this.lines.push(new o.BufferLine(e, i))); + else + for (let e = this._rows; e > t; e--) + this.lines.length > t + this.ybase && + (this.lines.length > this.ybase + this.y + 1 + ? this.lines.pop() + : (this.ybase++, this.ydisp++)); + if (r < this.lines.maxLength) { + const e = this.lines.length - r; + (e > 0 && + (this.lines.trimStart(e), + (this.ybase = Math.max(this.ybase - e, 0)), + (this.ydisp = Math.max(this.ydisp - e, 0)), + (this.savedY = Math.max(this.savedY - e, 0))), + (this.lines.maxLength = r)); + } + ((this.x = Math.min(this.x, e - 1)), + (this.y = Math.min(this.y, t - 1)), + n && (this.y += n), + (this.savedX = Math.min(this.savedX, e - 1)), + (this.scrollTop = 0)); + } + if ( + ((this.scrollBottom = t - 1), + this._isReflowEnabled && (this._reflow(e, t), this._cols > e)) + ) + for (let t = 0; t < this.lines.length; t++) + s += +this.lines.get(t).resize(e, i); + ((this._cols = e), + (this._rows = t), + this._memoryCleanupQueue.clear(), + s > 0.1 * this.lines.length && + ((this._memoryCleanupPosition = 0), + this._memoryCleanupQueue.enqueue(() => + this._batchedMemoryCleanup(), + ))); + } + _batchedMemoryCleanup() { + let e = !0; + this._memoryCleanupPosition >= this.lines.length && + ((this._memoryCleanupPosition = 0), (e = !1)); + let t = 0; + for (; this._memoryCleanupPosition < this.lines.length; ) + if ( + ((t += this.lines + .get(this._memoryCleanupPosition++) + .cleanupMemory()), + t > 100) + ) + return !0; + return e; + } + get _isReflowEnabled() { + const e = this._optionsService.rawOptions.windowsPty; + return e && e.buildNumber + ? this._hasScrollback && + "conpty" === e.backend && + e.buildNumber >= 21376 + : this._hasScrollback && + !this._optionsService.rawOptions.windowsMode; + } + _reflow(e, t) { + this._cols !== e && + (e > this._cols + ? this._reflowLarger(e, t) + : this._reflowSmaller(e, t)); + } + _reflowLarger(e, t) { + const i = (0, a.reflowLargerGetLinesToRemove)( + this.lines, + this._cols, + e, + this.ybase + this.y, + this.getNullCell(o.DEFAULT_ATTR_DATA), + ); + if (i.length > 0) { + const s = (0, a.reflowLargerCreateNewLayout)(this.lines, i); + ((0, a.reflowLargerApplyNewLayout)(this.lines, s.layout), + this._reflowLargerAdjustViewport(e, t, s.countRemoved)); + } + } + _reflowLargerAdjustViewport(e, t, i) { + const s = this.getNullCell(o.DEFAULT_ATTR_DATA); + let r = i; + for (; r-- > 0; ) + 0 === this.ybase + ? (this.y > 0 && this.y--, + this.lines.length < t && + this.lines.push(new o.BufferLine(e, s))) + : (this.ydisp === this.ybase && this.ydisp--, this.ybase--); + this.savedY = Math.max(this.savedY - i, 0); + } + _reflowSmaller(e, t) { + const i = this.getNullCell(o.DEFAULT_ATTR_DATA), + s = []; + let r = 0; + for (let n = this.lines.length - 1; n >= 0; n--) { + let h = this.lines.get(n); + if (!h || (!h.isWrapped && h.getTrimmedLength() <= e)) + continue; + const c = [h]; + for (; h.isWrapped && n > 0; ) + ((h = this.lines.get(--n)), c.unshift(h)); + const l = this.ybase + this.y; + if (l >= n && l < n + c.length) continue; + const d = c[c.length - 1].getTrimmedLength(), + _ = (0, a.reflowSmallerGetNewLineLengths)(c, this._cols, e), + u = _.length - c.length; + let f; + f = + 0 === this.ybase && this.y !== this.lines.length - 1 + ? Math.max(0, this.y - this.lines.maxLength + u) + : Math.max( + 0, + this.lines.length - this.lines.maxLength + u, + ); + const v = []; + for (let e = 0; e < u; e++) { + const e = this.getBlankLine(o.DEFAULT_ATTR_DATA, !0); + v.push(e); + } + (v.length > 0 && + (s.push({ start: n + c.length + r, newLines: v }), + (r += v.length)), + c.push(...v)); + let p = _.length - 1, + g = _[p]; + 0 === g && (p--, (g = _[p])); + let m = c.length - u - 1, + S = d; + for (; m >= 0; ) { + const e = Math.min(S, g); + if (void 0 === c[p]) break; + if ( + (c[p].copyCellsFrom(c[m], S - e, g - e, e, !0), + (g -= e), + 0 === g && (p--, (g = _[p])), + (S -= e), + 0 === S) + ) { + m--; + const e = Math.max(m, 0); + S = (0, a.getWrappedLineTrimmedLength)(c, e, this._cols); + } + } + for (let t = 0; t < c.length; t++) + _[t] < e && c[t].setCell(_[t], i); + let C = u - f; + for (; C-- > 0; ) + 0 === this.ybase + ? this.y < t - 1 + ? (this.y++, this.lines.pop()) + : (this.ybase++, this.ydisp++) + : this.ybase < + Math.min( + this.lines.maxLength, + this.lines.length + r, + ) - + t && + (this.ybase === this.ydisp && this.ydisp++, + this.ybase++); + this.savedY = Math.min(this.savedY + u, this.ybase + t - 1); + } + if (s.length > 0) { + const e = [], + t = []; + for (let e = 0; e < this.lines.length; e++) + t.push(this.lines.get(e)); + const i = this.lines.length; + let n = i - 1, + o = 0, + a = s[o]; + this.lines.length = Math.min( + this.lines.maxLength, + this.lines.length + r, + ); + let h = 0; + for ( + let c = Math.min(this.lines.maxLength - 1, i + r - 1); + c >= 0; + c-- + ) + if (a && a.start > n + h) { + for (let e = a.newLines.length - 1; e >= 0; e--) + this.lines.set(c--, a.newLines[e]); + (c++, + e.push({ index: n + 1, amount: a.newLines.length }), + (h += a.newLines.length), + (a = s[++o])); + } else this.lines.set(c, t[n--]); + let c = 0; + for (let t = e.length - 1; t >= 0; t--) + ((e[t].index += c), + this.lines.onInsertEmitter.fire(e[t]), + (c += e[t].amount)); + const l = Math.max(0, i + r - this.lines.maxLength); + l > 0 && this.lines.onTrimEmitter.fire(l); + } + } + translateBufferLineToString(e, t, i = 0, s) { + const r = this.lines.get(e); + return r ? r.translateToString(t, i, s) : ""; + } + getWrappedRangeForLine(e) { + let t = e, + i = e; + for (; t > 0 && this.lines.get(t).isWrapped; ) t--; + for ( + ; + i + 1 < this.lines.length && this.lines.get(i + 1).isWrapped; + + ) + i++; + return { first: t, last: i }; + } + setupTabStops(e) { + for ( + null != e + ? this.tabs[e] || (e = this.prevStop(e)) + : ((this.tabs = {}), (e = 0)); + e < this._cols; + e += this._optionsService.rawOptions.tabStopWidth + ) + this.tabs[e] = !0; + } + prevStop(e) { + for (null == e && (e = this.x); !this.tabs[--e] && e > 0; ); + return e >= this._cols ? this._cols - 1 : e < 0 ? 0 : e; + } + nextStop(e) { + for ( + null == e && (e = this.x); + !this.tabs[++e] && e < this._cols; + + ); + return e >= this._cols ? this._cols - 1 : e < 0 ? 0 : e; + } + clearMarkers(e) { + this._isClearing = !0; + for (let t = 0; t < this.markers.length; t++) + this.markers[t].line === e && + (this.markers[t].dispose(), this.markers.splice(t--, 1)); + this._isClearing = !1; + } + clearAllMarkers() { + this._isClearing = !0; + for (let e = 0; e < this.markers.length; e++) + (this.markers[e].dispose(), this.markers.splice(e--, 1)); + this._isClearing = !1; + } + addMarker(e) { + const t = new l.Marker(e); + return ( + this.markers.push(t), + t.register( + this.lines.onTrim((e) => { + ((t.line -= e), t.line < 0 && t.dispose()); + }), + ), + t.register( + this.lines.onInsert((e) => { + t.line >= e.index && (t.line += e.amount); + }), + ), + t.register( + this.lines.onDelete((e) => { + (t.line >= e.index && + t.line < e.index + e.amount && + t.dispose(), + t.line > e.index && (t.line -= e.amount)); + }), + ), + t.register(t.onDispose(() => this._removeMarker(t))), + t + ); + } + _removeMarker(e) { + this._isClearing || + this.markers.splice(this.markers.indexOf(e), 1); + } + })); + }, + 8437: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.BufferLine = t.DEFAULT_ATTR_DATA = void 0)); + const s = i(3734), + r = i(511), + n = i(643), + o = i(482); + t.DEFAULT_ATTR_DATA = Object.freeze(new s.AttributeData()); + let a = 0; + class h { + constructor(e, t, i = !1) { + ((this.isWrapped = i), + (this._combined = {}), + (this._extendedAttrs = {}), + (this._data = new Uint32Array(3 * e))); + const s = + t || + r.CellData.fromCharData([ + 0, + n.NULL_CELL_CHAR, + n.NULL_CELL_WIDTH, + n.NULL_CELL_CODE, + ]); + for (let t = 0; t < e; ++t) this.setCell(t, s); + this.length = e; + } + get(e) { + const t = this._data[3 * e + 0], + i = 2097151 & t; + return [ + this._data[3 * e + 1], + 2097152 & t + ? this._combined[e] + : i + ? (0, o.stringFromCodePoint)(i) + : "", + t >> 22, + 2097152 & t + ? this._combined[e].charCodeAt(this._combined[e].length - 1) + : i, + ]; + } + set(e, t) { + ((this._data[3 * e + 1] = t[n.CHAR_DATA_ATTR_INDEX]), + t[n.CHAR_DATA_CHAR_INDEX].length > 1 + ? ((this._combined[e] = t[1]), + (this._data[3 * e + 0] = + 2097152 | e | (t[n.CHAR_DATA_WIDTH_INDEX] << 22))) + : (this._data[3 * e + 0] = + t[n.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | + (t[n.CHAR_DATA_WIDTH_INDEX] << 22))); + } + getWidth(e) { + return this._data[3 * e + 0] >> 22; + } + hasWidth(e) { + return 12582912 & this._data[3 * e + 0]; + } + getFg(e) { + return this._data[3 * e + 1]; + } + getBg(e) { + return this._data[3 * e + 2]; + } + hasContent(e) { + return 4194303 & this._data[3 * e + 0]; + } + getCodePoint(e) { + const t = this._data[3 * e + 0]; + return 2097152 & t + ? this._combined[e].charCodeAt(this._combined[e].length - 1) + : 2097151 & t; + } + isCombined(e) { + return 2097152 & this._data[3 * e + 0]; + } + getString(e) { + const t = this._data[3 * e + 0]; + return 2097152 & t + ? this._combined[e] + : 2097151 & t + ? (0, o.stringFromCodePoint)(2097151 & t) + : ""; + } + isProtected(e) { + return 536870912 & this._data[3 * e + 2]; + } + loadCell(e, t) { + return ( + (a = 3 * e), + (t.content = this._data[a + 0]), + (t.fg = this._data[a + 1]), + (t.bg = this._data[a + 2]), + 2097152 & t.content && (t.combinedData = this._combined[e]), + 268435456 & t.bg && (t.extended = this._extendedAttrs[e]), + t + ); + } + setCell(e, t) { + (2097152 & t.content && (this._combined[e] = t.combinedData), + 268435456 & t.bg && (this._extendedAttrs[e] = t.extended), + (this._data[3 * e + 0] = t.content), + (this._data[3 * e + 1] = t.fg), + (this._data[3 * e + 2] = t.bg)); + } + setCellFromCodePoint(e, t, i, s, r, n) { + (268435456 & r && (this._extendedAttrs[e] = n), + (this._data[3 * e + 0] = t | (i << 22)), + (this._data[3 * e + 1] = s), + (this._data[3 * e + 2] = r)); + } + addCodepointToCell(e, t) { + let i = this._data[3 * e + 0]; + 2097152 & i + ? (this._combined[e] += (0, o.stringFromCodePoint)(t)) + : (2097151 & i + ? ((this._combined[e] = + (0, o.stringFromCodePoint)(2097151 & i) + + (0, o.stringFromCodePoint)(t)), + (i &= -2097152), + (i |= 2097152)) + : (i = t | (1 << 22)), + (this._data[3 * e + 0] = i)); + } + insertCells(e, t, i, n) { + if ( + ((e %= this.length) && + 2 === this.getWidth(e - 1) && + this.setCellFromCodePoint( + e - 1, + 0, + 1, + (null == n ? void 0 : n.fg) || 0, + (null == n ? void 0 : n.bg) || 0, + (null == n ? void 0 : n.extended) || new s.ExtendedAttrs(), + ), + t < this.length - e) + ) { + const s = new r.CellData(); + for (let i = this.length - e - t - 1; i >= 0; --i) + this.setCell(e + t + i, this.loadCell(e + i, s)); + for (let s = 0; s < t; ++s) this.setCell(e + s, i); + } else for (let t = e; t < this.length; ++t) this.setCell(t, i); + 2 === this.getWidth(this.length - 1) && + this.setCellFromCodePoint( + this.length - 1, + 0, + 1, + (null == n ? void 0 : n.fg) || 0, + (null == n ? void 0 : n.bg) || 0, + (null == n ? void 0 : n.extended) || new s.ExtendedAttrs(), + ); + } + deleteCells(e, t, i, n) { + if (((e %= this.length), t < this.length - e)) { + const s = new r.CellData(); + for (let i = 0; i < this.length - e - t; ++i) + this.setCell(e + i, this.loadCell(e + t + i, s)); + for (let e = this.length - t; e < this.length; ++e) + this.setCell(e, i); + } else for (let t = e; t < this.length; ++t) this.setCell(t, i); + (e && + 2 === this.getWidth(e - 1) && + this.setCellFromCodePoint( + e - 1, + 0, + 1, + (null == n ? void 0 : n.fg) || 0, + (null == n ? void 0 : n.bg) || 0, + (null == n ? void 0 : n.extended) || new s.ExtendedAttrs(), + ), + 0 !== this.getWidth(e) || + this.hasContent(e) || + this.setCellFromCodePoint( + e, + 0, + 1, + (null == n ? void 0 : n.fg) || 0, + (null == n ? void 0 : n.bg) || 0, + (null == n ? void 0 : n.extended) || new s.ExtendedAttrs(), + )); + } + replaceCells(e, t, i, r, n = !1) { + if (n) + for ( + e && + 2 === this.getWidth(e - 1) && + !this.isProtected(e - 1) && + this.setCellFromCodePoint( + e - 1, + 0, + 1, + (null == r ? void 0 : r.fg) || 0, + (null == r ? void 0 : r.bg) || 0, + (null == r ? void 0 : r.extended) || + new s.ExtendedAttrs(), + ), + t < this.length && + 2 === this.getWidth(t - 1) && + !this.isProtected(t) && + this.setCellFromCodePoint( + t, + 0, + 1, + (null == r ? void 0 : r.fg) || 0, + (null == r ? void 0 : r.bg) || 0, + (null == r ? void 0 : r.extended) || + new s.ExtendedAttrs(), + ); + e < t && e < this.length; + + ) + (this.isProtected(e) || this.setCell(e, i), e++); + else + for ( + e && + 2 === this.getWidth(e - 1) && + this.setCellFromCodePoint( + e - 1, + 0, + 1, + (null == r ? void 0 : r.fg) || 0, + (null == r ? void 0 : r.bg) || 0, + (null == r ? void 0 : r.extended) || + new s.ExtendedAttrs(), + ), + t < this.length && + 2 === this.getWidth(t - 1) && + this.setCellFromCodePoint( + t, + 0, + 1, + (null == r ? void 0 : r.fg) || 0, + (null == r ? void 0 : r.bg) || 0, + (null == r ? void 0 : r.extended) || + new s.ExtendedAttrs(), + ); + e < t && e < this.length; + + ) + this.setCell(e++, i); + } + resize(e, t) { + if (e === this.length) + return 4 * this._data.length * 2 < this._data.buffer.byteLength; + const i = 3 * e; + if (e > this.length) { + if (this._data.buffer.byteLength >= 4 * i) + this._data = new Uint32Array(this._data.buffer, 0, i); + else { + const e = new Uint32Array(i); + (e.set(this._data), (this._data = e)); + } + for (let i = this.length; i < e; ++i) this.setCell(i, t); + } else { + this._data = this._data.subarray(0, i); + const t = Object.keys(this._combined); + for (let i = 0; i < t.length; i++) { + const s = parseInt(t[i], 10); + s >= e && delete this._combined[s]; + } + const s = Object.keys(this._extendedAttrs); + for (let t = 0; t < s.length; t++) { + const i = parseInt(s[t], 10); + i >= e && delete this._extendedAttrs[i]; + } + } + return ( + (this.length = e), + 4 * i * 2 < this._data.buffer.byteLength + ); + } + cleanupMemory() { + if (4 * this._data.length * 2 < this._data.buffer.byteLength) { + const e = new Uint32Array(this._data.length); + return (e.set(this._data), (this._data = e), 1); + } + return 0; + } + fill(e, t = !1) { + if (t) + for (let t = 0; t < this.length; ++t) + this.isProtected(t) || this.setCell(t, e); + else { + ((this._combined = {}), (this._extendedAttrs = {})); + for (let t = 0; t < this.length; ++t) this.setCell(t, e); + } + } + copyFrom(e) { + (this.length !== e.length + ? (this._data = new Uint32Array(e._data)) + : this._data.set(e._data), + (this.length = e.length), + (this._combined = {})); + for (const t in e._combined) this._combined[t] = e._combined[t]; + this._extendedAttrs = {}; + for (const t in e._extendedAttrs) + this._extendedAttrs[t] = e._extendedAttrs[t]; + this.isWrapped = e.isWrapped; + } + clone() { + const e = new h(0); + ((e._data = new Uint32Array(this._data)), + (e.length = this.length)); + for (const t in this._combined) + e._combined[t] = this._combined[t]; + for (const t in this._extendedAttrs) + e._extendedAttrs[t] = this._extendedAttrs[t]; + return ((e.isWrapped = this.isWrapped), e); + } + getTrimmedLength() { + for (let e = this.length - 1; e >= 0; --e) + if (4194303 & this._data[3 * e + 0]) + return e + (this._data[3 * e + 0] >> 22); + return 0; + } + getNoBgTrimmedLength() { + for (let e = this.length - 1; e >= 0; --e) + if ( + 4194303 & this._data[3 * e + 0] || + 50331648 & this._data[3 * e + 2] + ) + return e + (this._data[3 * e + 0] >> 22); + return 0; + } + copyCellsFrom(e, t, i, s, r) { + const n = e._data; + if (r) + for (let r = s - 1; r >= 0; r--) { + for (let e = 0; e < 3; e++) + this._data[3 * (i + r) + e] = n[3 * (t + r) + e]; + 268435456 & n[3 * (t + r) + 2] && + (this._extendedAttrs[i + r] = e._extendedAttrs[t + r]); + } + else + for (let r = 0; r < s; r++) { + for (let e = 0; e < 3; e++) + this._data[3 * (i + r) + e] = n[3 * (t + r) + e]; + 268435456 & n[3 * (t + r) + 2] && + (this._extendedAttrs[i + r] = e._extendedAttrs[t + r]); + } + const o = Object.keys(e._combined); + for (let s = 0; s < o.length; s++) { + const r = parseInt(o[s], 10); + r >= t && (this._combined[r - t + i] = e._combined[r]); + } + } + translateToString(e = !1, t = 0, i = this.length) { + e && (i = Math.min(i, this.getTrimmedLength())); + let s = ""; + for (; t < i; ) { + const e = this._data[3 * t + 0], + i = 2097151 & e; + ((s += + 2097152 & e + ? this._combined[t] + : i + ? (0, o.stringFromCodePoint)(i) + : n.WHITESPACE_CELL_CHAR), + (t += e >> 22 || 1)); + } + return s; + } + } + t.BufferLine = h; + }, + 4841: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.getRangeLength = void 0), + (t.getRangeLength = function (e, t) { + if (e.start.y > e.end.y) + throw new Error( + `Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`, + ); + return t * (e.end.y - e.start.y) + (e.end.x - e.start.x + 1); + })); + }, + 4634: (e, t) => { + function i(e, t, i) { + if (t === e.length - 1) return e[t].getTrimmedLength(); + const s = !e[t].hasContent(i - 1) && 1 === e[t].getWidth(i - 1), + r = 2 === e[t + 1].getWidth(0); + return s && r ? i - 1 : i; + } + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.getWrappedLineTrimmedLength = + t.reflowSmallerGetNewLineLengths = + t.reflowLargerApplyNewLayout = + t.reflowLargerCreateNewLayout = + t.reflowLargerGetLinesToRemove = + void 0), + (t.reflowLargerGetLinesToRemove = function (e, t, s, r, n) { + const o = []; + for (let a = 0; a < e.length - 1; a++) { + let h = a, + c = e.get(++h); + if (!c.isWrapped) continue; + const l = [e.get(a)]; + for (; h < e.length && c.isWrapped; ) + (l.push(c), (c = e.get(++h))); + if (r >= a && r < h) { + a += l.length - 1; + continue; + } + let d = 0, + _ = i(l, d, t), + u = 1, + f = 0; + for (; u < l.length; ) { + const e = i(l, u, t), + r = e - f, + o = s - _, + a = Math.min(r, o); + (l[d].copyCellsFrom(l[u], f, _, a, !1), + (_ += a), + _ === s && (d++, (_ = 0)), + (f += a), + f === e && (u++, (f = 0)), + 0 === _ && + 0 !== d && + 2 === l[d - 1].getWidth(s - 1) && + (l[d].copyCellsFrom(l[d - 1], s - 1, _++, 1, !1), + l[d - 1].setCell(s - 1, n))); + } + l[d].replaceCells(_, s, n); + let v = 0; + for ( + let e = l.length - 1; + e > 0 && (e > d || 0 === l[e].getTrimmedLength()); + e-- + ) + v++; + (v > 0 && (o.push(a + l.length - v), o.push(v)), + (a += l.length - 1)); + } + return o; + }), + (t.reflowLargerCreateNewLayout = function (e, t) { + const i = []; + let s = 0, + r = t[s], + n = 0; + for (let o = 0; o < e.length; o++) + if (r === o) { + const i = t[++s]; + (e.onDeleteEmitter.fire({ index: o - n, amount: i }), + (o += i - 1), + (n += i), + (r = t[++s])); + } else i.push(o); + return { layout: i, countRemoved: n }; + }), + (t.reflowLargerApplyNewLayout = function (e, t) { + const i = []; + for (let s = 0; s < t.length; s++) i.push(e.get(t[s])); + for (let t = 0; t < i.length; t++) e.set(t, i[t]); + e.length = t.length; + }), + (t.reflowSmallerGetNewLineLengths = function (e, t, s) { + const r = [], + n = e.map((s, r) => i(e, r, t)).reduce((e, t) => e + t); + let o = 0, + a = 0, + h = 0; + for (; h < n; ) { + if (n - h < s) { + r.push(n - h); + break; + } + o += s; + const c = i(e, a, t); + o > c && ((o -= c), a++); + const l = 2 === e[a].getWidth(o - 1); + l && o--; + const d = l ? s - 1 : s; + (r.push(d), (h += d)); + } + return r; + }), + (t.getWrappedLineTrimmedLength = i)); + }, + 5295: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.BufferSet = void 0)); + const s = i(8460), + r = i(844), + n = i(9092); + class o extends r.Disposable { + constructor(e, t) { + (super(), + (this._optionsService = e), + (this._bufferService = t), + (this._onBufferActivate = this.register(new s.EventEmitter())), + (this.onBufferActivate = this._onBufferActivate.event), + this.reset(), + this.register( + this._optionsService.onSpecificOptionChange( + "scrollback", + () => + this.resize( + this._bufferService.cols, + this._bufferService.rows, + ), + ), + ), + this.register( + this._optionsService.onSpecificOptionChange( + "tabStopWidth", + () => this.setupTabStops(), + ), + )); + } + reset() { + ((this._normal = new n.Buffer( + !0, + this._optionsService, + this._bufferService, + )), + this._normal.fillViewportRows(), + (this._alt = new n.Buffer( + !1, + this._optionsService, + this._bufferService, + )), + (this._activeBuffer = this._normal), + this._onBufferActivate.fire({ + activeBuffer: this._normal, + inactiveBuffer: this._alt, + }), + this.setupTabStops()); + } + get alt() { + return this._alt; + } + get active() { + return this._activeBuffer; + } + get normal() { + return this._normal; + } + activateNormalBuffer() { + this._activeBuffer !== this._normal && + ((this._normal.x = this._alt.x), + (this._normal.y = this._alt.y), + this._alt.clearAllMarkers(), + this._alt.clear(), + (this._activeBuffer = this._normal), + this._onBufferActivate.fire({ + activeBuffer: this._normal, + inactiveBuffer: this._alt, + })); + } + activateAltBuffer(e) { + this._activeBuffer !== this._alt && + (this._alt.fillViewportRows(e), + (this._alt.x = this._normal.x), + (this._alt.y = this._normal.y), + (this._activeBuffer = this._alt), + this._onBufferActivate.fire({ + activeBuffer: this._alt, + inactiveBuffer: this._normal, + })); + } + resize(e, t) { + (this._normal.resize(e, t), + this._alt.resize(e, t), + this.setupTabStops(e)); + } + setupTabStops(e) { + (this._normal.setupTabStops(e), this._alt.setupTabStops(e)); + } + } + t.BufferSet = o; + }, + 511: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CellData = void 0)); + const s = i(482), + r = i(643), + n = i(3734); + class o extends n.AttributeData { + constructor() { + (super(...arguments), + (this.content = 0), + (this.fg = 0), + (this.bg = 0), + (this.extended = new n.ExtendedAttrs()), + (this.combinedData = "")); + } + static fromCharData(e) { + const t = new o(); + return (t.setFromCharData(e), t); + } + isCombined() { + return 2097152 & this.content; + } + getWidth() { + return this.content >> 22; + } + getChars() { + return 2097152 & this.content + ? this.combinedData + : 2097151 & this.content + ? (0, s.stringFromCodePoint)(2097151 & this.content) + : ""; + } + getCode() { + return this.isCombined() + ? this.combinedData.charCodeAt(this.combinedData.length - 1) + : 2097151 & this.content; + } + setFromCharData(e) { + ((this.fg = e[r.CHAR_DATA_ATTR_INDEX]), (this.bg = 0)); + let t = !1; + if (e[r.CHAR_DATA_CHAR_INDEX].length > 2) t = !0; + else if (2 === e[r.CHAR_DATA_CHAR_INDEX].length) { + const i = e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0); + if (55296 <= i && i <= 56319) { + const s = e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(1); + 56320 <= s && s <= 57343 + ? (this.content = + (1024 * (i - 55296) + s - 56320 + 65536) | + (e[r.CHAR_DATA_WIDTH_INDEX] << 22)) + : (t = !0); + } else t = !0; + } else + this.content = + e[r.CHAR_DATA_CHAR_INDEX].charCodeAt(0) | + (e[r.CHAR_DATA_WIDTH_INDEX] << 22); + t && + ((this.combinedData = e[r.CHAR_DATA_CHAR_INDEX]), + (this.content = 2097152 | (e[r.CHAR_DATA_WIDTH_INDEX] << 22))); + } + getAsCharData() { + return [ + this.fg, + this.getChars(), + this.getWidth(), + this.getCode(), + ]; + } + } + t.CellData = o; + }, + 643: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.WHITESPACE_CELL_CODE = + t.WHITESPACE_CELL_WIDTH = + t.WHITESPACE_CELL_CHAR = + t.NULL_CELL_CODE = + t.NULL_CELL_WIDTH = + t.NULL_CELL_CHAR = + t.CHAR_DATA_CODE_INDEX = + t.CHAR_DATA_WIDTH_INDEX = + t.CHAR_DATA_CHAR_INDEX = + t.CHAR_DATA_ATTR_INDEX = + t.DEFAULT_EXT = + t.DEFAULT_ATTR = + t.DEFAULT_COLOR = + void 0), + (t.DEFAULT_COLOR = 0), + (t.DEFAULT_ATTR = 256 | (t.DEFAULT_COLOR << 9)), + (t.DEFAULT_EXT = 0), + (t.CHAR_DATA_ATTR_INDEX = 0), + (t.CHAR_DATA_CHAR_INDEX = 1), + (t.CHAR_DATA_WIDTH_INDEX = 2), + (t.CHAR_DATA_CODE_INDEX = 3), + (t.NULL_CELL_CHAR = ""), + (t.NULL_CELL_WIDTH = 1), + (t.NULL_CELL_CODE = 0), + (t.WHITESPACE_CELL_CHAR = " "), + (t.WHITESPACE_CELL_WIDTH = 1), + (t.WHITESPACE_CELL_CODE = 32)); + }, + 4863: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.Marker = void 0)); + const s = i(8460), + r = i(844); + class n { + get id() { + return this._id; + } + constructor(e) { + ((this.line = e), + (this.isDisposed = !1), + (this._disposables = []), + (this._id = n._nextId++), + (this._onDispose = this.register(new s.EventEmitter())), + (this.onDispose = this._onDispose.event)); + } + dispose() { + this.isDisposed || + ((this.isDisposed = !0), + (this.line = -1), + this._onDispose.fire(), + (0, r.disposeArray)(this._disposables), + (this._disposables.length = 0)); + } + register(e) { + return (this._disposables.push(e), e); + } + } + ((t.Marker = n), (n._nextId = 1)); + }, + 7116: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.DEFAULT_CHARSET = t.CHARSETS = void 0), + (t.CHARSETS = {}), + (t.DEFAULT_CHARSET = t.CHARSETS.B), + (t.CHARSETS[0] = { + "`": "◆", + a: "▒", + b: "␉", + c: "␌", + d: "␍", + e: "␊", + f: "°", + g: "±", + h: "␤", + i: "␋", + j: "┘", + k: "┐", + l: "┌", + m: "└", + n: "┼", + o: "⎺", + p: "⎻", + q: "─", + r: "⎼", + s: "⎽", + t: "├", + u: "┤", + v: "┴", + w: "┬", + x: "│", + y: "≤", + z: "≥", + "{": "π", + "|": "≠", + "}": "£", + "~": "·", + }), + (t.CHARSETS.A = { "#": "£" }), + (t.CHARSETS.B = void 0), + (t.CHARSETS[4] = { + "#": "£", + "@": "¾", + "[": "ij", + "\\": "½", + "]": "|", + "{": "¨", + "|": "f", + "}": "¼", + "~": "´", + }), + (t.CHARSETS.C = t.CHARSETS[5] = + { + "[": "Ä", + "\\": "Ö", + "]": "Å", + "^": "Ü", + "`": "é", + "{": "ä", + "|": "ö", + "}": "å", + "~": "ü", + }), + (t.CHARSETS.R = { + "#": "£", + "@": "à", + "[": "°", + "\\": "ç", + "]": "§", + "{": "é", + "|": "ù", + "}": "è", + "~": "¨", + }), + (t.CHARSETS.Q = { + "@": "à", + "[": "â", + "\\": "ç", + "]": "ê", + "^": "î", + "`": "ô", + "{": "é", + "|": "ù", + "}": "è", + "~": "û", + }), + (t.CHARSETS.K = { + "@": "§", + "[": "Ä", + "\\": "Ö", + "]": "Ü", + "{": "ä", + "|": "ö", + "}": "ü", + "~": "ß", + }), + (t.CHARSETS.Y = { + "#": "£", + "@": "§", + "[": "°", + "\\": "ç", + "]": "é", + "`": "ù", + "{": "à", + "|": "ò", + "}": "è", + "~": "ì", + }), + (t.CHARSETS.E = t.CHARSETS[6] = + { + "@": "Ä", + "[": "Æ", + "\\": "Ø", + "]": "Å", + "^": "Ü", + "`": "ä", + "{": "æ", + "|": "ø", + "}": "å", + "~": "ü", + }), + (t.CHARSETS.Z = { + "#": "£", + "@": "§", + "[": "¡", + "\\": "Ñ", + "]": "¿", + "{": "°", + "|": "ñ", + "}": "ç", + }), + (t.CHARSETS.H = t.CHARSETS[7] = + { + "@": "É", + "[": "Ä", + "\\": "Ö", + "]": "Å", + "^": "Ü", + "`": "é", + "{": "ä", + "|": "ö", + "}": "å", + "~": "ü", + }), + (t.CHARSETS["="] = { + "#": "ù", + "@": "à", + "[": "é", + "\\": "ç", + "]": "ê", + "^": "î", + _: "è", + "`": "ô", + "{": "ä", + "|": "ö", + "}": "ü", + "~": "û", + })); + }, + 2584: (e, t) => { + var i, s, r; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.C1_ESCAPED = t.C1 = t.C0 = void 0), + (function (e) { + ((e.NUL = "\0"), + (e.SOH = ""), + (e.STX = ""), + (e.ETX = ""), + (e.EOT = ""), + (e.ENQ = ""), + (e.ACK = ""), + (e.BEL = ""), + (e.BS = "\b"), + (e.HT = "\t"), + (e.LF = "\n"), + (e.VT = "\v"), + (e.FF = "\f"), + (e.CR = "\r"), + (e.SO = ""), + (e.SI = ""), + (e.DLE = ""), + (e.DC1 = ""), + (e.DC2 = ""), + (e.DC3 = ""), + (e.DC4 = ""), + (e.NAK = ""), + (e.SYN = ""), + (e.ETB = ""), + (e.CAN = ""), + (e.EM = ""), + (e.SUB = ""), + (e.ESC = ""), + (e.FS = ""), + (e.GS = ""), + (e.RS = ""), + (e.US = ""), + (e.SP = " "), + (e.DEL = "")); + })(i || (t.C0 = i = {})), + (function (e) { + ((e.PAD = "€"), + (e.HOP = ""), + (e.BPH = "‚"), + (e.NBH = "ƒ"), + (e.IND = "„"), + (e.NEL = "…"), + (e.SSA = "†"), + (e.ESA = "‡"), + (e.HTS = "ˆ"), + (e.HTJ = "‰"), + (e.VTS = "Š"), + (e.PLD = "‹"), + (e.PLU = "Œ"), + (e.RI = ""), + (e.SS2 = "Ž"), + (e.SS3 = ""), + (e.DCS = ""), + (e.PU1 = "‘"), + (e.PU2 = "’"), + (e.STS = "“"), + (e.CCH = "”"), + (e.MW = "•"), + (e.SPA = "–"), + (e.EPA = "—"), + (e.SOS = "˜"), + (e.SGCI = "™"), + (e.SCI = "š"), + (e.CSI = "›"), + (e.ST = "œ"), + (e.OSC = ""), + (e.PM = "ž"), + (e.APC = "Ÿ")); + })(s || (t.C1 = s = {})), + (function (e) { + e.ST = `${i.ESC}\\`; + })(r || (t.C1_ESCAPED = r = {}))); + }, + 7399: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.evaluateKeyboardEvent = void 0)); + const s = i(2584), + r = { + 48: ["0", ")"], + 49: ["1", "!"], + 50: ["2", "@"], + 51: ["3", "#"], + 52: ["4", "$"], + 53: ["5", "%"], + 54: ["6", "^"], + 55: ["7", "&"], + 56: ["8", "*"], + 57: ["9", "("], + 186: [";", ":"], + 187: ["=", "+"], + 188: [",", "<"], + 189: ["-", "_"], + 190: [".", ">"], + 191: ["/", "?"], + 192: ["`", "~"], + 219: ["[", "{"], + 220: ["\\", "|"], + 221: ["]", "}"], + 222: ["'", '"'], + }; + t.evaluateKeyboardEvent = function (e, t, i, n) { + const o = { type: 0, cancel: !1, key: void 0 }, + a = + (e.shiftKey ? 1 : 0) | + (e.altKey ? 2 : 0) | + (e.ctrlKey ? 4 : 0) | + (e.metaKey ? 8 : 0); + switch (e.keyCode) { + case 0: + "UIKeyInputUpArrow" === e.key + ? (o.key = t ? s.C0.ESC + "OA" : s.C0.ESC + "[A") + : "UIKeyInputLeftArrow" === e.key + ? (o.key = t ? s.C0.ESC + "OD" : s.C0.ESC + "[D") + : "UIKeyInputRightArrow" === e.key + ? (o.key = t ? s.C0.ESC + "OC" : s.C0.ESC + "[C") + : "UIKeyInputDownArrow" === e.key && + (o.key = t ? s.C0.ESC + "OB" : s.C0.ESC + "[B"); + break; + case 8: + if (e.altKey) { + o.key = s.C0.ESC + s.C0.DEL; + break; + } + o.key = s.C0.DEL; + break; + case 9: + if (e.shiftKey) { + o.key = s.C0.ESC + "[Z"; + break; + } + ((o.key = s.C0.HT), (o.cancel = !0)); + break; + case 13: + ((o.key = e.altKey ? s.C0.ESC + s.C0.CR : s.C0.CR), + (o.cancel = !0)); + break; + case 27: + ((o.key = s.C0.ESC), + e.altKey && (o.key = s.C0.ESC + s.C0.ESC), + (o.cancel = !0)); + break; + case 37: + if (e.metaKey) break; + a + ? ((o.key = s.C0.ESC + "[1;" + (a + 1) + "D"), + o.key === s.C0.ESC + "[1;3D" && + (o.key = s.C0.ESC + (i ? "b" : "[1;5D"))) + : (o.key = t ? s.C0.ESC + "OD" : s.C0.ESC + "[D"); + break; + case 39: + if (e.metaKey) break; + a + ? ((o.key = s.C0.ESC + "[1;" + (a + 1) + "C"), + o.key === s.C0.ESC + "[1;3C" && + (o.key = s.C0.ESC + (i ? "f" : "[1;5C"))) + : (o.key = t ? s.C0.ESC + "OC" : s.C0.ESC + "[C"); + break; + case 38: + if (e.metaKey) break; + a + ? ((o.key = s.C0.ESC + "[1;" + (a + 1) + "A"), + i || + o.key !== s.C0.ESC + "[1;3A" || + (o.key = s.C0.ESC + "[1;5A")) + : (o.key = t ? s.C0.ESC + "OA" : s.C0.ESC + "[A"); + break; + case 40: + if (e.metaKey) break; + a + ? ((o.key = s.C0.ESC + "[1;" + (a + 1) + "B"), + i || + o.key !== s.C0.ESC + "[1;3B" || + (o.key = s.C0.ESC + "[1;5B")) + : (o.key = t ? s.C0.ESC + "OB" : s.C0.ESC + "[B"); + break; + case 45: + e.shiftKey || e.ctrlKey || (o.key = s.C0.ESC + "[2~"); + break; + case 46: + o.key = a ? s.C0.ESC + "[3;" + (a + 1) + "~" : s.C0.ESC + "[3~"; + break; + case 36: + o.key = a + ? s.C0.ESC + "[1;" + (a + 1) + "H" + : t + ? s.C0.ESC + "OH" + : s.C0.ESC + "[H"; + break; + case 35: + o.key = a + ? s.C0.ESC + "[1;" + (a + 1) + "F" + : t + ? s.C0.ESC + "OF" + : s.C0.ESC + "[F"; + break; + case 33: + e.shiftKey + ? (o.type = 2) + : e.ctrlKey + ? (o.key = s.C0.ESC + "[5;" + (a + 1) + "~") + : (o.key = s.C0.ESC + "[5~"); + break; + case 34: + e.shiftKey + ? (o.type = 3) + : e.ctrlKey + ? (o.key = s.C0.ESC + "[6;" + (a + 1) + "~") + : (o.key = s.C0.ESC + "[6~"); + break; + case 112: + o.key = a ? s.C0.ESC + "[1;" + (a + 1) + "P" : s.C0.ESC + "OP"; + break; + case 113: + o.key = a ? s.C0.ESC + "[1;" + (a + 1) + "Q" : s.C0.ESC + "OQ"; + break; + case 114: + o.key = a ? s.C0.ESC + "[1;" + (a + 1) + "R" : s.C0.ESC + "OR"; + break; + case 115: + o.key = a ? s.C0.ESC + "[1;" + (a + 1) + "S" : s.C0.ESC + "OS"; + break; + case 116: + o.key = a + ? s.C0.ESC + "[15;" + (a + 1) + "~" + : s.C0.ESC + "[15~"; + break; + case 117: + o.key = a + ? s.C0.ESC + "[17;" + (a + 1) + "~" + : s.C0.ESC + "[17~"; + break; + case 118: + o.key = a + ? s.C0.ESC + "[18;" + (a + 1) + "~" + : s.C0.ESC + "[18~"; + break; + case 119: + o.key = a + ? s.C0.ESC + "[19;" + (a + 1) + "~" + : s.C0.ESC + "[19~"; + break; + case 120: + o.key = a + ? s.C0.ESC + "[20;" + (a + 1) + "~" + : s.C0.ESC + "[20~"; + break; + case 121: + o.key = a + ? s.C0.ESC + "[21;" + (a + 1) + "~" + : s.C0.ESC + "[21~"; + break; + case 122: + o.key = a + ? s.C0.ESC + "[23;" + (a + 1) + "~" + : s.C0.ESC + "[23~"; + break; + case 123: + o.key = a + ? s.C0.ESC + "[24;" + (a + 1) + "~" + : s.C0.ESC + "[24~"; + break; + default: + if (!e.ctrlKey || e.shiftKey || e.altKey || e.metaKey) + if ((i && !n) || !e.altKey || e.metaKey) + !i || e.altKey || e.ctrlKey || e.shiftKey || !e.metaKey + ? e.key && + !e.ctrlKey && + !e.altKey && + !e.metaKey && + e.keyCode >= 48 && + 1 === e.key.length + ? (o.key = e.key) + : e.key && + e.ctrlKey && + ("_" === e.key && (o.key = s.C0.US), + "@" === e.key && (o.key = s.C0.NUL)) + : 65 === e.keyCode && (o.type = 1); + else { + const t = r[e.keyCode], + i = null == t ? void 0 : t[e.shiftKey ? 1 : 0]; + if (i) o.key = s.C0.ESC + i; + else if (e.keyCode >= 65 && e.keyCode <= 90) { + const t = e.ctrlKey ? e.keyCode - 64 : e.keyCode + 32; + let i = String.fromCharCode(t); + (e.shiftKey && (i = i.toUpperCase()), + (o.key = s.C0.ESC + i)); + } else if (32 === e.keyCode) + o.key = s.C0.ESC + (e.ctrlKey ? s.C0.NUL : " "); + else if ("Dead" === e.key && e.code.startsWith("Key")) { + let t = e.code.slice(3, 4); + (e.shiftKey || (t = t.toLowerCase()), + (o.key = s.C0.ESC + t), + (o.cancel = !0)); + } + } + else + e.keyCode >= 65 && e.keyCode <= 90 + ? (o.key = String.fromCharCode(e.keyCode - 64)) + : 32 === e.keyCode + ? (o.key = s.C0.NUL) + : e.keyCode >= 51 && e.keyCode <= 55 + ? (o.key = String.fromCharCode(e.keyCode - 51 + 27)) + : 56 === e.keyCode + ? (o.key = s.C0.DEL) + : 219 === e.keyCode + ? (o.key = s.C0.ESC) + : 220 === e.keyCode + ? (o.key = s.C0.FS) + : 221 === e.keyCode && (o.key = s.C0.GS); + } + return o; + }; + }, + 482: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.Utf8ToUtf32 = + t.StringToUtf32 = + t.utf32ToString = + t.stringFromCodePoint = + void 0), + (t.stringFromCodePoint = function (e) { + return e > 65535 + ? ((e -= 65536), + String.fromCharCode(55296 + (e >> 10)) + + String.fromCharCode((e % 1024) + 56320)) + : String.fromCharCode(e); + }), + (t.utf32ToString = function (e, t = 0, i = e.length) { + let s = ""; + for (let r = t; r < i; ++r) { + let t = e[r]; + t > 65535 + ? ((t -= 65536), + (s += + String.fromCharCode(55296 + (t >> 10)) + + String.fromCharCode((t % 1024) + 56320))) + : (s += String.fromCharCode(t)); + } + return s; + }), + (t.StringToUtf32 = class { + constructor() { + this._interim = 0; + } + clear() { + this._interim = 0; + } + decode(e, t) { + const i = e.length; + if (!i) return 0; + let s = 0, + r = 0; + if (this._interim) { + const i = e.charCodeAt(r++); + (56320 <= i && i <= 57343 + ? (t[s++] = + 1024 * (this._interim - 55296) + i - 56320 + 65536) + : ((t[s++] = this._interim), (t[s++] = i)), + (this._interim = 0)); + } + for (let n = r; n < i; ++n) { + const r = e.charCodeAt(n); + if (55296 <= r && r <= 56319) { + if (++n >= i) return ((this._interim = r), s); + const o = e.charCodeAt(n); + 56320 <= o && o <= 57343 + ? (t[s++] = 1024 * (r - 55296) + o - 56320 + 65536) + : ((t[s++] = r), (t[s++] = o)); + } else 65279 !== r && (t[s++] = r); + } + return s; + } + }), + (t.Utf8ToUtf32 = class { + constructor() { + this.interim = new Uint8Array(3); + } + clear() { + this.interim.fill(0); + } + decode(e, t) { + const i = e.length; + if (!i) return 0; + let s, + r, + n, + o, + a = 0, + h = 0, + c = 0; + if (this.interim[0]) { + let s = !1, + r = this.interim[0]; + r &= 192 == (224 & r) ? 31 : 224 == (240 & r) ? 15 : 7; + let n, + o = 0; + for (; (n = 63 & this.interim[++o]) && o < 4; ) + ((r <<= 6), (r |= n)); + const h = + 192 == (224 & this.interim[0]) + ? 2 + : 224 == (240 & this.interim[0]) + ? 3 + : 4, + l = h - o; + for (; c < l; ) { + if (c >= i) return 0; + if (((n = e[c++]), 128 != (192 & n))) { + (c--, (s = !0)); + break; + } + ((this.interim[o++] = n), (r <<= 6), (r |= 63 & n)); + } + (s || + (2 === h + ? r < 128 + ? c-- + : (t[a++] = r) + : 3 === h + ? r < 2048 || + (r >= 55296 && r <= 57343) || + 65279 === r || + (t[a++] = r) + : r < 65536 || r > 1114111 || (t[a++] = r)), + this.interim.fill(0)); + } + const l = i - 4; + let d = c; + for (; d < i; ) { + for ( + ; + !( + !(d < l) || + 128 & (s = e[d]) || + 128 & (r = e[d + 1]) || + 128 & (n = e[d + 2]) || + 128 & (o = e[d + 3]) + ); + + ) + ((t[a++] = s), + (t[a++] = r), + (t[a++] = n), + (t[a++] = o), + (d += 4)); + if (((s = e[d++]), s < 128)) t[a++] = s; + else if (192 == (224 & s)) { + if (d >= i) return ((this.interim[0] = s), a); + if (((r = e[d++]), 128 != (192 & r))) { + d--; + continue; + } + if (((h = ((31 & s) << 6) | (63 & r)), h < 128)) { + d--; + continue; + } + t[a++] = h; + } else if (224 == (240 & s)) { + if (d >= i) return ((this.interim[0] = s), a); + if (((r = e[d++]), 128 != (192 & r))) { + d--; + continue; + } + if (d >= i) + return ((this.interim[0] = s), (this.interim[1] = r), a); + if (((n = e[d++]), 128 != (192 & n))) { + d--; + continue; + } + if ( + ((h = ((15 & s) << 12) | ((63 & r) << 6) | (63 & n)), + h < 2048 || (h >= 55296 && h <= 57343) || 65279 === h) + ) + continue; + t[a++] = h; + } else if (240 == (248 & s)) { + if (d >= i) return ((this.interim[0] = s), a); + if (((r = e[d++]), 128 != (192 & r))) { + d--; + continue; + } + if (d >= i) + return ((this.interim[0] = s), (this.interim[1] = r), a); + if (((n = e[d++]), 128 != (192 & n))) { + d--; + continue; + } + if (d >= i) + return ( + (this.interim[0] = s), + (this.interim[1] = r), + (this.interim[2] = n), + a + ); + if (((o = e[d++]), 128 != (192 & o))) { + d--; + continue; + } + if ( + ((h = + ((7 & s) << 18) | + ((63 & r) << 12) | + ((63 & n) << 6) | + (63 & o)), + h < 65536 || h > 1114111) + ) + continue; + t[a++] = h; + } + } + return a; + } + })); + }, + 225: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.UnicodeV6 = void 0)); + const i = [ + [768, 879], + [1155, 1158], + [1160, 1161], + [1425, 1469], + [1471, 1471], + [1473, 1474], + [1476, 1477], + [1479, 1479], + [1536, 1539], + [1552, 1557], + [1611, 1630], + [1648, 1648], + [1750, 1764], + [1767, 1768], + [1770, 1773], + [1807, 1807], + [1809, 1809], + [1840, 1866], + [1958, 1968], + [2027, 2035], + [2305, 2306], + [2364, 2364], + [2369, 2376], + [2381, 2381], + [2385, 2388], + [2402, 2403], + [2433, 2433], + [2492, 2492], + [2497, 2500], + [2509, 2509], + [2530, 2531], + [2561, 2562], + [2620, 2620], + [2625, 2626], + [2631, 2632], + [2635, 2637], + [2672, 2673], + [2689, 2690], + [2748, 2748], + [2753, 2757], + [2759, 2760], + [2765, 2765], + [2786, 2787], + [2817, 2817], + [2876, 2876], + [2879, 2879], + [2881, 2883], + [2893, 2893], + [2902, 2902], + [2946, 2946], + [3008, 3008], + [3021, 3021], + [3134, 3136], + [3142, 3144], + [3146, 3149], + [3157, 3158], + [3260, 3260], + [3263, 3263], + [3270, 3270], + [3276, 3277], + [3298, 3299], + [3393, 3395], + [3405, 3405], + [3530, 3530], + [3538, 3540], + [3542, 3542], + [3633, 3633], + [3636, 3642], + [3655, 3662], + [3761, 3761], + [3764, 3769], + [3771, 3772], + [3784, 3789], + [3864, 3865], + [3893, 3893], + [3895, 3895], + [3897, 3897], + [3953, 3966], + [3968, 3972], + [3974, 3975], + [3984, 3991], + [3993, 4028], + [4038, 4038], + [4141, 4144], + [4146, 4146], + [4150, 4151], + [4153, 4153], + [4184, 4185], + [4448, 4607], + [4959, 4959], + [5906, 5908], + [5938, 5940], + [5970, 5971], + [6002, 6003], + [6068, 6069], + [6071, 6077], + [6086, 6086], + [6089, 6099], + [6109, 6109], + [6155, 6157], + [6313, 6313], + [6432, 6434], + [6439, 6440], + [6450, 6450], + [6457, 6459], + [6679, 6680], + [6912, 6915], + [6964, 6964], + [6966, 6970], + [6972, 6972], + [6978, 6978], + [7019, 7027], + [7616, 7626], + [7678, 7679], + [8203, 8207], + [8234, 8238], + [8288, 8291], + [8298, 8303], + [8400, 8431], + [12330, 12335], + [12441, 12442], + [43014, 43014], + [43019, 43019], + [43045, 43046], + [64286, 64286], + [65024, 65039], + [65056, 65059], + [65279, 65279], + [65529, 65531], + ], + s = [ + [68097, 68099], + [68101, 68102], + [68108, 68111], + [68152, 68154], + [68159, 68159], + [119143, 119145], + [119155, 119170], + [119173, 119179], + [119210, 119213], + [119362, 119364], + [917505, 917505], + [917536, 917631], + [917760, 917999], + ]; + let r; + t.UnicodeV6 = class { + constructor() { + if (((this.version = "6"), !r)) { + ((r = new Uint8Array(65536)), + r.fill(1), + (r[0] = 0), + r.fill(0, 1, 32), + r.fill(0, 127, 160), + r.fill(2, 4352, 4448), + (r[9001] = 2), + (r[9002] = 2), + r.fill(2, 11904, 42192), + (r[12351] = 1), + r.fill(2, 44032, 55204), + r.fill(2, 63744, 64256), + r.fill(2, 65040, 65050), + r.fill(2, 65072, 65136), + r.fill(2, 65280, 65377), + r.fill(2, 65504, 65511)); + for (let e = 0; e < i.length; ++e) + r.fill(0, i[e][0], i[e][1] + 1); + } + } + wcwidth(e) { + return e < 32 + ? 0 + : e < 127 + ? 1 + : e < 65536 + ? r[e] + : (function (e, t) { + let i, + s = 0, + r = t.length - 1; + if (e < t[0][0] || e > t[r][1]) return !1; + for (; r >= s; ) + if (((i = (s + r) >> 1), e > t[i][1])) s = i + 1; + else { + if (!(e < t[i][0])) return !0; + r = i - 1; + } + return !1; + })(e, s) + ? 0 + : (e >= 131072 && e <= 196605) || + (e >= 196608 && e <= 262141) + ? 2 + : 1; + } + }; + }, + 5981: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.WriteBuffer = void 0)); + const s = i(8460), + r = i(844); + class n extends r.Disposable { + constructor(e) { + (super(), + (this._action = e), + (this._writeBuffer = []), + (this._callbacks = []), + (this._pendingData = 0), + (this._bufferOffset = 0), + (this._isSyncWriting = !1), + (this._syncCalls = 0), + (this._didUserInput = !1), + (this._onWriteParsed = this.register(new s.EventEmitter())), + (this.onWriteParsed = this._onWriteParsed.event)); + } + handleUserInput() { + this._didUserInput = !0; + } + writeSync(e, t) { + if (void 0 !== t && this._syncCalls > t) + return void (this._syncCalls = 0); + if ( + ((this._pendingData += e.length), + this._writeBuffer.push(e), + this._callbacks.push(void 0), + this._syncCalls++, + this._isSyncWriting) + ) + return; + let i; + for ( + this._isSyncWriting = !0; + (i = this._writeBuffer.shift()); + + ) { + this._action(i); + const e = this._callbacks.shift(); + e && e(); + } + ((this._pendingData = 0), + (this._bufferOffset = 2147483647), + (this._isSyncWriting = !1), + (this._syncCalls = 0)); + } + write(e, t) { + if (this._pendingData > 5e7) + throw new Error( + "write data discarded, use flow control to avoid losing data", + ); + if (!this._writeBuffer.length) { + if (((this._bufferOffset = 0), this._didUserInput)) + return ( + (this._didUserInput = !1), + (this._pendingData += e.length), + this._writeBuffer.push(e), + this._callbacks.push(t), + void this._innerWrite() + ); + setTimeout(() => this._innerWrite()); + } + ((this._pendingData += e.length), + this._writeBuffer.push(e), + this._callbacks.push(t)); + } + _innerWrite(e = 0, t = !0) { + const i = e || Date.now(); + for (; this._writeBuffer.length > this._bufferOffset; ) { + const e = this._writeBuffer[this._bufferOffset], + s = this._action(e, t); + if (s) { + const e = (e) => + Date.now() - i >= 12 + ? setTimeout(() => this._innerWrite(0, e)) + : this._innerWrite(i, e); + return void s + .catch( + (e) => ( + queueMicrotask(() => { + throw e; + }), + Promise.resolve(!1) + ), + ) + .then(e); + } + const r = this._callbacks[this._bufferOffset]; + if ( + (r && r(), + this._bufferOffset++, + (this._pendingData -= e.length), + Date.now() - i >= 12) + ) + break; + } + (this._writeBuffer.length > this._bufferOffset + ? (this._bufferOffset > 50 && + ((this._writeBuffer = this._writeBuffer.slice( + this._bufferOffset, + )), + (this._callbacks = this._callbacks.slice( + this._bufferOffset, + )), + (this._bufferOffset = 0)), + setTimeout(() => this._innerWrite())) + : ((this._writeBuffer.length = 0), + (this._callbacks.length = 0), + (this._pendingData = 0), + (this._bufferOffset = 0)), + this._onWriteParsed.fire()); + } + } + t.WriteBuffer = n; + }, + 5941: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.toRgbString = t.parseColor = void 0)); + const i = + /^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/, + s = /^[\da-f]+$/; + function r(e, t) { + const i = e.toString(16), + s = i.length < 2 ? "0" + i : i; + switch (t) { + case 4: + return i[0]; + case 8: + return s; + case 12: + return (s + s).slice(0, 3); + default: + return s + s; + } + } + ((t.parseColor = function (e) { + if (!e) return; + let t = e.toLowerCase(); + if (0 === t.indexOf("rgb:")) { + t = t.slice(4); + const e = i.exec(t); + if (e) { + const t = e[1] ? 15 : e[4] ? 255 : e[7] ? 4095 : 65535; + return [ + Math.round( + (parseInt(e[1] || e[4] || e[7] || e[10], 16) / t) * 255, + ), + Math.round( + (parseInt(e[2] || e[5] || e[8] || e[11], 16) / t) * 255, + ), + Math.round( + (parseInt(e[3] || e[6] || e[9] || e[12], 16) / t) * 255, + ), + ]; + } + } else if ( + 0 === t.indexOf("#") && + ((t = t.slice(1)), s.exec(t) && [3, 6, 9, 12].includes(t.length)) + ) { + const e = t.length / 3, + i = [0, 0, 0]; + for (let s = 0; s < 3; ++s) { + const r = parseInt(t.slice(e * s, e * s + e), 16); + i[s] = + 1 === e ? r << 4 : 2 === e ? r : 3 === e ? r >> 4 : r >> 8; + } + return i; + } + }), + (t.toRgbString = function (e, t = 16) { + const [i, s, n] = e; + return `rgb:${r(i, t)}/${r(s, t)}/${r(n, t)}`; + })); + }, + 5770: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.PAYLOAD_LIMIT = void 0), + (t.PAYLOAD_LIMIT = 1e7)); + }, + 6351: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.DcsHandler = t.DcsParser = void 0)); + const s = i(482), + r = i(8742), + n = i(5770), + o = []; + t.DcsParser = class { + constructor() { + ((this._handlers = Object.create(null)), + (this._active = o), + (this._ident = 0), + (this._handlerFb = () => {}), + (this._stack = { + paused: !1, + loopPosition: 0, + fallThrough: !1, + })); + } + dispose() { + ((this._handlers = Object.create(null)), + (this._handlerFb = () => {}), + (this._active = o)); + } + registerHandler(e, t) { + void 0 === this._handlers[e] && (this._handlers[e] = []); + const i = this._handlers[e]; + return ( + i.push(t), + { + dispose: () => { + const e = i.indexOf(t); + -1 !== e && i.splice(e, 1); + }, + } + ); + } + clearHandler(e) { + this._handlers[e] && delete this._handlers[e]; + } + setHandlerFallback(e) { + this._handlerFb = e; + } + reset() { + if (this._active.length) + for ( + let e = this._stack.paused + ? this._stack.loopPosition - 1 + : this._active.length - 1; + e >= 0; + --e + ) + this._active[e].unhook(!1); + ((this._stack.paused = !1), + (this._active = o), + (this._ident = 0)); + } + hook(e, t) { + if ( + (this.reset(), + (this._ident = e), + (this._active = this._handlers[e] || o), + this._active.length) + ) + for (let e = this._active.length - 1; e >= 0; e--) + this._active[e].hook(t); + else this._handlerFb(this._ident, "HOOK", t); + } + put(e, t, i) { + if (this._active.length) + for (let s = this._active.length - 1; s >= 0; s--) + this._active[s].put(e, t, i); + else + this._handlerFb( + this._ident, + "PUT", + (0, s.utf32ToString)(e, t, i), + ); + } + unhook(e, t = !0) { + if (this._active.length) { + let i = !1, + s = this._active.length - 1, + r = !1; + if ( + (this._stack.paused && + ((s = this._stack.loopPosition - 1), + (i = t), + (r = this._stack.fallThrough), + (this._stack.paused = !1)), + !r && !1 === i) + ) { + for ( + ; + s >= 0 && ((i = this._active[s].unhook(e)), !0 !== i); + s-- + ) + if (i instanceof Promise) + return ( + (this._stack.paused = !0), + (this._stack.loopPosition = s), + (this._stack.fallThrough = !1), + i + ); + s--; + } + for (; s >= 0; s--) + if (((i = this._active[s].unhook(!1)), i instanceof Promise)) + return ( + (this._stack.paused = !0), + (this._stack.loopPosition = s), + (this._stack.fallThrough = !0), + i + ); + } else this._handlerFb(this._ident, "UNHOOK", e); + ((this._active = o), (this._ident = 0)); + } + }; + const a = new r.Params(); + (a.addParam(0), + (t.DcsHandler = class { + constructor(e) { + ((this._handler = e), + (this._data = ""), + (this._params = a), + (this._hitLimit = !1)); + } + hook(e) { + ((this._params = e.length > 1 || e.params[0] ? e.clone() : a), + (this._data = ""), + (this._hitLimit = !1)); + } + put(e, t, i) { + this._hitLimit || + ((this._data += (0, s.utf32ToString)(e, t, i)), + this._data.length > n.PAYLOAD_LIMIT && + ((this._data = ""), (this._hitLimit = !0))); + } + unhook(e) { + let t = !1; + if (this._hitLimit) t = !1; + else if ( + e && + ((t = this._handler(this._data, this._params)), + t instanceof Promise) + ) + return t.then( + (e) => ( + (this._params = a), + (this._data = ""), + (this._hitLimit = !1), + e + ), + ); + return ( + (this._params = a), + (this._data = ""), + (this._hitLimit = !1), + t + ); + } + })); + }, + 2015: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.EscapeSequenceParser = + t.VT500_TRANSITION_TABLE = + t.TransitionTable = + void 0)); + const s = i(844), + r = i(8742), + n = i(6242), + o = i(6351); + class a { + constructor(e) { + this.table = new Uint8Array(e); + } + setDefault(e, t) { + this.table.fill((e << 4) | t); + } + add(e, t, i, s) { + this.table[(t << 8) | e] = (i << 4) | s; + } + addMany(e, t, i, s) { + for (let r = 0; r < e.length; r++) + this.table[(t << 8) | e[r]] = (i << 4) | s; + } + } + t.TransitionTable = a; + const h = 160; + t.VT500_TRANSITION_TABLE = (function () { + const e = new a(4095), + t = Array.apply(null, Array(256)).map((e, t) => t), + i = (e, i) => t.slice(e, i), + s = i(32, 127), + r = i(0, 24); + (r.push(25), r.push.apply(r, i(28, 32))); + const n = i(0, 14); + let o; + for (o in (e.setDefault(1, 0), e.addMany(s, 0, 2, 0), n)) + (e.addMany([24, 26, 153, 154], o, 3, 0), + e.addMany(i(128, 144), o, 3, 0), + e.addMany(i(144, 152), o, 3, 0), + e.add(156, o, 0, 0), + e.add(27, o, 11, 1), + e.add(157, o, 4, 8), + e.addMany([152, 158, 159], o, 0, 7), + e.add(155, o, 11, 3), + e.add(144, o, 11, 9)); + return ( + e.addMany(r, 0, 3, 0), + e.addMany(r, 1, 3, 1), + e.add(127, 1, 0, 1), + e.addMany(r, 8, 0, 8), + e.addMany(r, 3, 3, 3), + e.add(127, 3, 0, 3), + e.addMany(r, 4, 3, 4), + e.add(127, 4, 0, 4), + e.addMany(r, 6, 3, 6), + e.addMany(r, 5, 3, 5), + e.add(127, 5, 0, 5), + e.addMany(r, 2, 3, 2), + e.add(127, 2, 0, 2), + e.add(93, 1, 4, 8), + e.addMany(s, 8, 5, 8), + e.add(127, 8, 5, 8), + e.addMany([156, 27, 24, 26, 7], 8, 6, 0), + e.addMany(i(28, 32), 8, 0, 8), + e.addMany([88, 94, 95], 1, 0, 7), + e.addMany(s, 7, 0, 7), + e.addMany(r, 7, 0, 7), + e.add(156, 7, 0, 0), + e.add(127, 7, 0, 7), + e.add(91, 1, 11, 3), + e.addMany(i(64, 127), 3, 7, 0), + e.addMany(i(48, 60), 3, 8, 4), + e.addMany([60, 61, 62, 63], 3, 9, 4), + e.addMany(i(48, 60), 4, 8, 4), + e.addMany(i(64, 127), 4, 7, 0), + e.addMany([60, 61, 62, 63], 4, 0, 6), + e.addMany(i(32, 64), 6, 0, 6), + e.add(127, 6, 0, 6), + e.addMany(i(64, 127), 6, 0, 0), + e.addMany(i(32, 48), 3, 9, 5), + e.addMany(i(32, 48), 5, 9, 5), + e.addMany(i(48, 64), 5, 0, 6), + e.addMany(i(64, 127), 5, 7, 0), + e.addMany(i(32, 48), 4, 9, 5), + e.addMany(i(32, 48), 1, 9, 2), + e.addMany(i(32, 48), 2, 9, 2), + e.addMany(i(48, 127), 2, 10, 0), + e.addMany(i(48, 80), 1, 10, 0), + e.addMany(i(81, 88), 1, 10, 0), + e.addMany([89, 90, 92], 1, 10, 0), + e.addMany(i(96, 127), 1, 10, 0), + e.add(80, 1, 11, 9), + e.addMany(r, 9, 0, 9), + e.add(127, 9, 0, 9), + e.addMany(i(28, 32), 9, 0, 9), + e.addMany(i(32, 48), 9, 9, 12), + e.addMany(i(48, 60), 9, 8, 10), + e.addMany([60, 61, 62, 63], 9, 9, 10), + e.addMany(r, 11, 0, 11), + e.addMany(i(32, 128), 11, 0, 11), + e.addMany(i(28, 32), 11, 0, 11), + e.addMany(r, 10, 0, 10), + e.add(127, 10, 0, 10), + e.addMany(i(28, 32), 10, 0, 10), + e.addMany(i(48, 60), 10, 8, 10), + e.addMany([60, 61, 62, 63], 10, 0, 11), + e.addMany(i(32, 48), 10, 9, 12), + e.addMany(r, 12, 0, 12), + e.add(127, 12, 0, 12), + e.addMany(i(28, 32), 12, 0, 12), + e.addMany(i(32, 48), 12, 9, 12), + e.addMany(i(48, 64), 12, 0, 11), + e.addMany(i(64, 127), 12, 12, 13), + e.addMany(i(64, 127), 10, 12, 13), + e.addMany(i(64, 127), 9, 12, 13), + e.addMany(r, 13, 13, 13), + e.addMany(s, 13, 13, 13), + e.add(127, 13, 0, 13), + e.addMany([27, 156, 24, 26], 13, 14, 0), + e.add(h, 0, 2, 0), + e.add(h, 8, 5, 8), + e.add(h, 6, 0, 6), + e.add(h, 11, 0, 11), + e.add(h, 13, 13, 13), + e + ); + })(); + class c extends s.Disposable { + constructor(e = t.VT500_TRANSITION_TABLE) { + (super(), + (this._transitions = e), + (this._parseStack = { + state: 0, + handlers: [], + handlerPos: 0, + transition: 0, + chunkPos: 0, + }), + (this.initialState = 0), + (this.currentState = this.initialState), + (this._params = new r.Params()), + this._params.addParam(0), + (this._collect = 0), + (this.precedingCodepoint = 0), + (this._printHandlerFb = (e, t, i) => {}), + (this._executeHandlerFb = (e) => {}), + (this._csiHandlerFb = (e, t) => {}), + (this._escHandlerFb = (e) => {}), + (this._errorHandlerFb = (e) => e), + (this._printHandler = this._printHandlerFb), + (this._executeHandlers = Object.create(null)), + (this._csiHandlers = Object.create(null)), + (this._escHandlers = Object.create(null)), + this.register( + (0, s.toDisposable)(() => { + ((this._csiHandlers = Object.create(null)), + (this._executeHandlers = Object.create(null)), + (this._escHandlers = Object.create(null))); + }), + ), + (this._oscParser = this.register(new n.OscParser())), + (this._dcsParser = this.register(new o.DcsParser())), + (this._errorHandler = this._errorHandlerFb), + this.registerEscHandler({ final: "\\" }, () => !0)); + } + _identifier(e, t = [64, 126]) { + let i = 0; + if (e.prefix) { + if (e.prefix.length > 1) + throw new Error("only one byte as prefix supported"); + if (((i = e.prefix.charCodeAt(0)), (i && 60 > i) || i > 63)) + throw new Error("prefix must be in range 0x3c .. 0x3f"); + } + if (e.intermediates) { + if (e.intermediates.length > 2) + throw new Error( + "only two bytes as intermediates are supported", + ); + for (let t = 0; t < e.intermediates.length; ++t) { + const s = e.intermediates.charCodeAt(t); + if (32 > s || s > 47) + throw new Error( + "intermediate must be in range 0x20 .. 0x2f", + ); + ((i <<= 8), (i |= s)); + } + } + if (1 !== e.final.length) + throw new Error("final must be a single byte"); + const s = e.final.charCodeAt(0); + if (t[0] > s || s > t[1]) + throw new Error(`final must be in range ${t[0]} .. ${t[1]}`); + return ((i <<= 8), (i |= s), i); + } + identToString(e) { + const t = []; + for (; e; ) (t.push(String.fromCharCode(255 & e)), (e >>= 8)); + return t.reverse().join(""); + } + setPrintHandler(e) { + this._printHandler = e; + } + clearPrintHandler() { + this._printHandler = this._printHandlerFb; + } + registerEscHandler(e, t) { + const i = this._identifier(e, [48, 126]); + void 0 === this._escHandlers[i] && (this._escHandlers[i] = []); + const s = this._escHandlers[i]; + return ( + s.push(t), + { + dispose: () => { + const e = s.indexOf(t); + -1 !== e && s.splice(e, 1); + }, + } + ); + } + clearEscHandler(e) { + this._escHandlers[this._identifier(e, [48, 126])] && + delete this._escHandlers[this._identifier(e, [48, 126])]; + } + setEscHandlerFallback(e) { + this._escHandlerFb = e; + } + setExecuteHandler(e, t) { + this._executeHandlers[e.charCodeAt(0)] = t; + } + clearExecuteHandler(e) { + this._executeHandlers[e.charCodeAt(0)] && + delete this._executeHandlers[e.charCodeAt(0)]; + } + setExecuteHandlerFallback(e) { + this._executeHandlerFb = e; + } + registerCsiHandler(e, t) { + const i = this._identifier(e); + void 0 === this._csiHandlers[i] && (this._csiHandlers[i] = []); + const s = this._csiHandlers[i]; + return ( + s.push(t), + { + dispose: () => { + const e = s.indexOf(t); + -1 !== e && s.splice(e, 1); + }, + } + ); + } + clearCsiHandler(e) { + this._csiHandlers[this._identifier(e)] && + delete this._csiHandlers[this._identifier(e)]; + } + setCsiHandlerFallback(e) { + this._csiHandlerFb = e; + } + registerDcsHandler(e, t) { + return this._dcsParser.registerHandler(this._identifier(e), t); + } + clearDcsHandler(e) { + this._dcsParser.clearHandler(this._identifier(e)); + } + setDcsHandlerFallback(e) { + this._dcsParser.setHandlerFallback(e); + } + registerOscHandler(e, t) { + return this._oscParser.registerHandler(e, t); + } + clearOscHandler(e) { + this._oscParser.clearHandler(e); + } + setOscHandlerFallback(e) { + this._oscParser.setHandlerFallback(e); + } + setErrorHandler(e) { + this._errorHandler = e; + } + clearErrorHandler() { + this._errorHandler = this._errorHandlerFb; + } + reset() { + ((this.currentState = this.initialState), + this._oscParser.reset(), + this._dcsParser.reset(), + this._params.reset(), + this._params.addParam(0), + (this._collect = 0), + (this.precedingCodepoint = 0), + 0 !== this._parseStack.state && + ((this._parseStack.state = 2), + (this._parseStack.handlers = []))); + } + _preserveStack(e, t, i, s, r) { + ((this._parseStack.state = e), + (this._parseStack.handlers = t), + (this._parseStack.handlerPos = i), + (this._parseStack.transition = s), + (this._parseStack.chunkPos = r)); + } + parse(e, t, i) { + let s, + r = 0, + n = 0, + o = 0; + if (this._parseStack.state) + if (2 === this._parseStack.state) + ((this._parseStack.state = 0), + (o = this._parseStack.chunkPos + 1)); + else { + if (void 0 === i || 1 === this._parseStack.state) + throw ( + (this._parseStack.state = 1), + new Error( + "improper continuation due to previous async handler, giving up parsing", + ) + ); + const t = this._parseStack.handlers; + let n = this._parseStack.handlerPos - 1; + switch (this._parseStack.state) { + case 3: + if (!1 === i && n > -1) + for ( + ; + n >= 0 && ((s = t[n](this._params)), !0 !== s); + n-- + ) + if (s instanceof Promise) + return ((this._parseStack.handlerPos = n), s); + this._parseStack.handlers = []; + break; + case 4: + if (!1 === i && n > -1) + for (; n >= 0 && ((s = t[n]()), !0 !== s); n--) + if (s instanceof Promise) + return ((this._parseStack.handlerPos = n), s); + this._parseStack.handlers = []; + break; + case 6: + if ( + ((r = e[this._parseStack.chunkPos]), + (s = this._dcsParser.unhook(24 !== r && 26 !== r, i)), + s) + ) + return s; + (27 === r && (this._parseStack.transition |= 1), + this._params.reset(), + this._params.addParam(0), + (this._collect = 0)); + break; + case 5: + if ( + ((r = e[this._parseStack.chunkPos]), + (s = this._oscParser.end(24 !== r && 26 !== r, i)), + s) + ) + return s; + (27 === r && (this._parseStack.transition |= 1), + this._params.reset(), + this._params.addParam(0), + (this._collect = 0)); + } + ((this._parseStack.state = 0), + (o = this._parseStack.chunkPos + 1), + (this.precedingCodepoint = 0), + (this.currentState = 15 & this._parseStack.transition)); + } + for (let i = o; i < t; ++i) { + switch ( + ((r = e[i]), + (n = + this._transitions.table[ + (this.currentState << 8) | (r < 160 ? r : h) + ]), + n >> 4) + ) { + case 2: + for (let s = i + 1; ; ++s) { + if (s >= t || (r = e[s]) < 32 || (r > 126 && r < h)) { + (this._printHandler(e, i, s), (i = s - 1)); + break; + } + if (++s >= t || (r = e[s]) < 32 || (r > 126 && r < h)) { + (this._printHandler(e, i, s), (i = s - 1)); + break; + } + if (++s >= t || (r = e[s]) < 32 || (r > 126 && r < h)) { + (this._printHandler(e, i, s), (i = s - 1)); + break; + } + if (++s >= t || (r = e[s]) < 32 || (r > 126 && r < h)) { + (this._printHandler(e, i, s), (i = s - 1)); + break; + } + } + break; + case 3: + (this._executeHandlers[r] + ? this._executeHandlers[r]() + : this._executeHandlerFb(r), + (this.precedingCodepoint = 0)); + break; + case 0: + break; + case 1: + if ( + this._errorHandler({ + position: i, + code: r, + currentState: this.currentState, + collect: this._collect, + params: this._params, + abort: !1, + }).abort + ) + return; + break; + case 7: + const o = this._csiHandlers[(this._collect << 8) | r]; + let a = o ? o.length - 1 : -1; + for (; a >= 0 && ((s = o[a](this._params)), !0 !== s); a--) + if (s instanceof Promise) + return (this._preserveStack(3, o, a, n, i), s); + (a < 0 && + this._csiHandlerFb( + (this._collect << 8) | r, + this._params, + ), + (this.precedingCodepoint = 0)); + break; + case 8: + do { + switch (r) { + case 59: + this._params.addParam(0); + break; + case 58: + this._params.addSubParam(-1); + break; + default: + this._params.addDigit(r - 48); + } + } while (++i < t && (r = e[i]) > 47 && r < 60); + i--; + break; + case 9: + ((this._collect <<= 8), (this._collect |= r)); + break; + case 10: + const c = this._escHandlers[(this._collect << 8) | r]; + let l = c ? c.length - 1 : -1; + for (; l >= 0 && ((s = c[l]()), !0 !== s); l--) + if (s instanceof Promise) + return (this._preserveStack(4, c, l, n, i), s); + (l < 0 && this._escHandlerFb((this._collect << 8) | r), + (this.precedingCodepoint = 0)); + break; + case 11: + (this._params.reset(), + this._params.addParam(0), + (this._collect = 0)); + break; + case 12: + this._dcsParser.hook( + (this._collect << 8) | r, + this._params, + ); + break; + case 13: + for (let s = i + 1; ; ++s) + if ( + s >= t || + 24 === (r = e[s]) || + 26 === r || + 27 === r || + (r > 127 && r < h) + ) { + (this._dcsParser.put(e, i, s), (i = s - 1)); + break; + } + break; + case 14: + if (((s = this._dcsParser.unhook(24 !== r && 26 !== r)), s)) + return (this._preserveStack(6, [], 0, n, i), s); + (27 === r && (n |= 1), + this._params.reset(), + this._params.addParam(0), + (this._collect = 0), + (this.precedingCodepoint = 0)); + break; + case 4: + this._oscParser.start(); + break; + case 5: + for (let s = i + 1; ; s++) + if (s >= t || (r = e[s]) < 32 || (r > 127 && r < h)) { + (this._oscParser.put(e, i, s), (i = s - 1)); + break; + } + break; + case 6: + if (((s = this._oscParser.end(24 !== r && 26 !== r)), s)) + return (this._preserveStack(5, [], 0, n, i), s); + (27 === r && (n |= 1), + this._params.reset(), + this._params.addParam(0), + (this._collect = 0), + (this.precedingCodepoint = 0)); + } + this.currentState = 15 & n; + } + } + } + t.EscapeSequenceParser = c; + }, + 6242: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.OscHandler = t.OscParser = void 0)); + const s = i(5770), + r = i(482), + n = []; + ((t.OscParser = class { + constructor() { + ((this._state = 0), + (this._active = n), + (this._id = -1), + (this._handlers = Object.create(null)), + (this._handlerFb = () => {}), + (this._stack = { + paused: !1, + loopPosition: 0, + fallThrough: !1, + })); + } + registerHandler(e, t) { + void 0 === this._handlers[e] && (this._handlers[e] = []); + const i = this._handlers[e]; + return ( + i.push(t), + { + dispose: () => { + const e = i.indexOf(t); + -1 !== e && i.splice(e, 1); + }, + } + ); + } + clearHandler(e) { + this._handlers[e] && delete this._handlers[e]; + } + setHandlerFallback(e) { + this._handlerFb = e; + } + dispose() { + ((this._handlers = Object.create(null)), + (this._handlerFb = () => {}), + (this._active = n)); + } + reset() { + if (2 === this._state) + for ( + let e = this._stack.paused + ? this._stack.loopPosition - 1 + : this._active.length - 1; + e >= 0; + --e + ) + this._active[e].end(!1); + ((this._stack.paused = !1), + (this._active = n), + (this._id = -1), + (this._state = 0)); + } + _start() { + if ( + ((this._active = this._handlers[this._id] || n), + this._active.length) + ) + for (let e = this._active.length - 1; e >= 0; e--) + this._active[e].start(); + else this._handlerFb(this._id, "START"); + } + _put(e, t, i) { + if (this._active.length) + for (let s = this._active.length - 1; s >= 0; s--) + this._active[s].put(e, t, i); + else + this._handlerFb(this._id, "PUT", (0, r.utf32ToString)(e, t, i)); + } + start() { + (this.reset(), (this._state = 1)); + } + put(e, t, i) { + if (3 !== this._state) { + if (1 === this._state) + for (; t < i; ) { + const i = e[t++]; + if (59 === i) { + ((this._state = 2), this._start()); + break; + } + if (i < 48 || 57 < i) return void (this._state = 3); + (-1 === this._id && (this._id = 0), + (this._id = 10 * this._id + i - 48)); + } + 2 === this._state && i - t > 0 && this._put(e, t, i); + } + } + end(e, t = !0) { + if (0 !== this._state) { + if (3 !== this._state) + if ( + (1 === this._state && this._start(), this._active.length) + ) { + let i = !1, + s = this._active.length - 1, + r = !1; + if ( + (this._stack.paused && + ((s = this._stack.loopPosition - 1), + (i = t), + (r = this._stack.fallThrough), + (this._stack.paused = !1)), + !r && !1 === i) + ) { + for ( + ; + s >= 0 && ((i = this._active[s].end(e)), !0 !== i); + s-- + ) + if (i instanceof Promise) + return ( + (this._stack.paused = !0), + (this._stack.loopPosition = s), + (this._stack.fallThrough = !1), + i + ); + s--; + } + for (; s >= 0; s--) + if (((i = this._active[s].end(!1)), i instanceof Promise)) + return ( + (this._stack.paused = !0), + (this._stack.loopPosition = s), + (this._stack.fallThrough = !0), + i + ); + } else this._handlerFb(this._id, "END", e); + ((this._active = n), (this._id = -1), (this._state = 0)); + } + } + }), + (t.OscHandler = class { + constructor(e) { + ((this._handler = e), (this._data = ""), (this._hitLimit = !1)); + } + start() { + ((this._data = ""), (this._hitLimit = !1)); + } + put(e, t, i) { + this._hitLimit || + ((this._data += (0, r.utf32ToString)(e, t, i)), + this._data.length > s.PAYLOAD_LIMIT && + ((this._data = ""), (this._hitLimit = !0))); + } + end(e) { + let t = !1; + if (this._hitLimit) t = !1; + else if ( + e && + ((t = this._handler(this._data)), t instanceof Promise) + ) + return t.then( + (e) => ((this._data = ""), (this._hitLimit = !1), e), + ); + return ((this._data = ""), (this._hitLimit = !1), t); + } + })); + }, + 8742: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.Params = void 0)); + const i = 2147483647; + class s { + static fromArray(e) { + const t = new s(); + if (!e.length) return t; + for (let i = Array.isArray(e[0]) ? 1 : 0; i < e.length; ++i) { + const s = e[i]; + if (Array.isArray(s)) + for (let e = 0; e < s.length; ++e) t.addSubParam(s[e]); + else t.addParam(s); + } + return t; + } + constructor(e = 32, t = 32) { + if ( + ((this.maxLength = e), (this.maxSubParamsLength = t), t > 256) + ) + throw new Error( + "maxSubParamsLength must not be greater than 256", + ); + ((this.params = new Int32Array(e)), + (this.length = 0), + (this._subParams = new Int32Array(t)), + (this._subParamsLength = 0), + (this._subParamsIdx = new Uint16Array(e)), + (this._rejectDigits = !1), + (this._rejectSubDigits = !1), + (this._digitIsSub = !1)); + } + clone() { + const e = new s(this.maxLength, this.maxSubParamsLength); + return ( + e.params.set(this.params), + (e.length = this.length), + e._subParams.set(this._subParams), + (e._subParamsLength = this._subParamsLength), + e._subParamsIdx.set(this._subParamsIdx), + (e._rejectDigits = this._rejectDigits), + (e._rejectSubDigits = this._rejectSubDigits), + (e._digitIsSub = this._digitIsSub), + e + ); + } + toArray() { + const e = []; + for (let t = 0; t < this.length; ++t) { + e.push(this.params[t]); + const i = this._subParamsIdx[t] >> 8, + s = 255 & this._subParamsIdx[t]; + s - i > 0 && + e.push(Array.prototype.slice.call(this._subParams, i, s)); + } + return e; + } + reset() { + ((this.length = 0), + (this._subParamsLength = 0), + (this._rejectDigits = !1), + (this._rejectSubDigits = !1), + (this._digitIsSub = !1)); + } + addParam(e) { + if (((this._digitIsSub = !1), this.length >= this.maxLength)) + this._rejectDigits = !0; + else { + if (e < -1) + throw new Error("values lesser than -1 are not allowed"); + ((this._subParamsIdx[this.length] = + (this._subParamsLength << 8) | this._subParamsLength), + (this.params[this.length++] = e > i ? i : e)); + } + } + addSubParam(e) { + if (((this._digitIsSub = !0), this.length)) + if ( + this._rejectDigits || + this._subParamsLength >= this.maxSubParamsLength + ) + this._rejectSubDigits = !0; + else { + if (e < -1) + throw new Error("values lesser than -1 are not allowed"); + ((this._subParams[this._subParamsLength++] = e > i ? i : e), + this._subParamsIdx[this.length - 1]++); + } + } + hasSubParams(e) { + return ( + (255 & this._subParamsIdx[e]) - (this._subParamsIdx[e] >> 8) > 0 + ); + } + getSubParams(e) { + const t = this._subParamsIdx[e] >> 8, + i = 255 & this._subParamsIdx[e]; + return i - t > 0 ? this._subParams.subarray(t, i) : null; + } + getSubParamsAll() { + const e = {}; + for (let t = 0; t < this.length; ++t) { + const i = this._subParamsIdx[t] >> 8, + s = 255 & this._subParamsIdx[t]; + s - i > 0 && (e[t] = this._subParams.slice(i, s)); + } + return e; + } + addDigit(e) { + let t; + if ( + this._rejectDigits || + !(t = this._digitIsSub ? this._subParamsLength : this.length) || + (this._digitIsSub && this._rejectSubDigits) + ) + return; + const s = this._digitIsSub ? this._subParams : this.params, + r = s[t - 1]; + s[t - 1] = ~r ? Math.min(10 * r + e, i) : e; + } + } + t.Params = s; + }, + 5741: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.AddonManager = void 0), + (t.AddonManager = class { + constructor() { + this._addons = []; + } + dispose() { + for (let e = this._addons.length - 1; e >= 0; e--) + this._addons[e].instance.dispose(); + } + loadAddon(e, t) { + const i = { instance: t, dispose: t.dispose, isDisposed: !1 }; + (this._addons.push(i), + (t.dispose = () => this._wrappedAddonDispose(i)), + t.activate(e)); + } + _wrappedAddonDispose(e) { + if (e.isDisposed) return; + let t = -1; + for (let i = 0; i < this._addons.length; i++) + if (this._addons[i] === e) { + t = i; + break; + } + if (-1 === t) + throw new Error( + "Could not dispose an addon that has not been loaded", + ); + ((e.isDisposed = !0), + e.dispose.apply(e.instance), + this._addons.splice(t, 1)); + } + })); + }, + 8771: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.BufferApiView = void 0)); + const s = i(3785), + r = i(511); + t.BufferApiView = class { + constructor(e, t) { + ((this._buffer = e), (this.type = t)); + } + init(e) { + return ((this._buffer = e), this); + } + get cursorY() { + return this._buffer.y; + } + get cursorX() { + return this._buffer.x; + } + get viewportY() { + return this._buffer.ydisp; + } + get baseY() { + return this._buffer.ybase; + } + get length() { + return this._buffer.lines.length; + } + getLine(e) { + const t = this._buffer.lines.get(e); + if (t) return new s.BufferLineApiView(t); + } + getNullCell() { + return new r.CellData(); + } + }; + }, + 3785: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.BufferLineApiView = void 0)); + const s = i(511); + t.BufferLineApiView = class { + constructor(e) { + this._line = e; + } + get isWrapped() { + return this._line.isWrapped; + } + get length() { + return this._line.length; + } + getCell(e, t) { + if (!(e < 0 || e >= this._line.length)) + return t + ? (this._line.loadCell(e, t), t) + : this._line.loadCell(e, new s.CellData()); + } + translateToString(e, t, i) { + return this._line.translateToString(e, t, i); + } + }; + }, + 8285: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.BufferNamespaceApi = void 0)); + const s = i(8771), + r = i(8460), + n = i(844); + class o extends n.Disposable { + constructor(e) { + (super(), + (this._core = e), + (this._onBufferChange = this.register(new r.EventEmitter())), + (this.onBufferChange = this._onBufferChange.event), + (this._normal = new s.BufferApiView( + this._core.buffers.normal, + "normal", + )), + (this._alternate = new s.BufferApiView( + this._core.buffers.alt, + "alternate", + )), + this._core.buffers.onBufferActivate(() => + this._onBufferChange.fire(this.active), + )); + } + get active() { + if (this._core.buffers.active === this._core.buffers.normal) + return this.normal; + if (this._core.buffers.active === this._core.buffers.alt) + return this.alternate; + throw new Error("Active buffer is neither normal nor alternate"); + } + get normal() { + return this._normal.init(this._core.buffers.normal); + } + get alternate() { + return this._alternate.init(this._core.buffers.alt); + } + } + t.BufferNamespaceApi = o; + }, + 7975: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.ParserApi = void 0), + (t.ParserApi = class { + constructor(e) { + this._core = e; + } + registerCsiHandler(e, t) { + return this._core.registerCsiHandler(e, (e) => t(e.toArray())); + } + addCsiHandler(e, t) { + return this.registerCsiHandler(e, t); + } + registerDcsHandler(e, t) { + return this._core.registerDcsHandler(e, (e, i) => + t(e, i.toArray()), + ); + } + addDcsHandler(e, t) { + return this.registerDcsHandler(e, t); + } + registerEscHandler(e, t) { + return this._core.registerEscHandler(e, t); + } + addEscHandler(e, t) { + return this.registerEscHandler(e, t); + } + registerOscHandler(e, t) { + return this._core.registerOscHandler(e, t); + } + addOscHandler(e, t) { + return this.registerOscHandler(e, t); + } + })); + }, + 7090: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.UnicodeApi = void 0), + (t.UnicodeApi = class { + constructor(e) { + this._core = e; + } + register(e) { + this._core.unicodeService.register(e); + } + get versions() { + return this._core.unicodeService.versions; + } + get activeVersion() { + return this._core.unicodeService.activeVersion; + } + set activeVersion(e) { + this._core.unicodeService.activeVersion = e; + } + })); + }, + 744: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.BufferService = t.MINIMUM_ROWS = t.MINIMUM_COLS = void 0)); + const n = i(8460), + o = i(844), + a = i(5295), + h = i(2585); + ((t.MINIMUM_COLS = 2), (t.MINIMUM_ROWS = 1)); + let c = (t.BufferService = class extends o.Disposable { + get buffer() { + return this.buffers.active; + } + constructor(e) { + (super(), + (this.isUserScrolling = !1), + (this._onResize = this.register(new n.EventEmitter())), + (this.onResize = this._onResize.event), + (this._onScroll = this.register(new n.EventEmitter())), + (this.onScroll = this._onScroll.event), + (this.cols = Math.max(e.rawOptions.cols || 0, t.MINIMUM_COLS)), + (this.rows = Math.max(e.rawOptions.rows || 0, t.MINIMUM_ROWS)), + (this.buffers = this.register(new a.BufferSet(e, this)))); + } + resize(e, t) { + ((this.cols = e), + (this.rows = t), + this.buffers.resize(e, t), + this._onResize.fire({ cols: e, rows: t })); + } + reset() { + (this.buffers.reset(), (this.isUserScrolling = !1)); + } + scroll(e, t = !1) { + const i = this.buffer; + let s; + ((s = this._cachedBlankLine), + (s && + s.length === this.cols && + s.getFg(0) === e.fg && + s.getBg(0) === e.bg) || + ((s = i.getBlankLine(e, t)), (this._cachedBlankLine = s)), + (s.isWrapped = t)); + const r = i.ybase + i.scrollTop, + n = i.ybase + i.scrollBottom; + if (0 === i.scrollTop) { + const e = i.lines.isFull; + (n === i.lines.length - 1 + ? e + ? i.lines.recycle().copyFrom(s) + : i.lines.push(s.clone()) + : i.lines.splice(n + 1, 0, s.clone()), + e + ? this.isUserScrolling && + (i.ydisp = Math.max(i.ydisp - 1, 0)) + : (i.ybase++, this.isUserScrolling || i.ydisp++)); + } else { + const e = n - r + 1; + (i.lines.shiftElements(r + 1, e - 1, -1), + i.lines.set(n, s.clone())); + } + (this.isUserScrolling || (i.ydisp = i.ybase), + this._onScroll.fire(i.ydisp)); + } + scrollLines(e, t, i) { + const s = this.buffer; + if (e < 0) { + if (0 === s.ydisp) return; + this.isUserScrolling = !0; + } else e + s.ydisp >= s.ybase && (this.isUserScrolling = !1); + const r = s.ydisp; + ((s.ydisp = Math.max(Math.min(s.ydisp + e, s.ybase), 0)), + r !== s.ydisp && (t || this._onScroll.fire(s.ydisp))); + } + }); + t.BufferService = c = s([r(0, h.IOptionsService)], c); + }, + 7994: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CharsetService = void 0), + (t.CharsetService = class { + constructor() { + ((this.glevel = 0), (this._charsets = [])); + } + reset() { + ((this.charset = void 0), + (this._charsets = []), + (this.glevel = 0)); + } + setgLevel(e) { + ((this.glevel = e), (this.charset = this._charsets[e])); + } + setgCharset(e, t) { + ((this._charsets[e] = t), + this.glevel === e && (this.charset = t)); + } + })); + }, + 1753: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CoreMouseService = void 0)); + const n = i(2585), + o = i(8460), + a = i(844), + h = { + NONE: { events: 0, restrict: () => !1 }, + X10: { + events: 1, + restrict: (e) => + 4 !== e.button && + 1 === e.action && + ((e.ctrl = !1), (e.alt = !1), (e.shift = !1), !0), + }, + VT200: { events: 19, restrict: (e) => 32 !== e.action }, + DRAG: { + events: 23, + restrict: (e) => 32 !== e.action || 3 !== e.button, + }, + ANY: { events: 31, restrict: (e) => !0 }, + }; + function c(e, t) { + let i = (e.ctrl ? 16 : 0) | (e.shift ? 4 : 0) | (e.alt ? 8 : 0); + return ( + 4 === e.button + ? ((i |= 64), (i |= e.action)) + : ((i |= 3 & e.button), + 4 & e.button && (i |= 64), + 8 & e.button && (i |= 128), + 32 === e.action + ? (i |= 32) + : 0 !== e.action || t || (i |= 3)), + i + ); + } + const l = String.fromCharCode, + d = { + DEFAULT: (e) => { + const t = [c(e, !1) + 32, e.col + 32, e.row + 32]; + return t[0] > 255 || t[1] > 255 || t[2] > 255 + ? "" + : `${l(t[0])}${l(t[1])}${l(t[2])}`; + }, + SGR: (e) => { + const t = 0 === e.action && 4 !== e.button ? "m" : "M"; + return `[<${c(e, !0)};${e.col};${e.row}${t}`; + }, + SGR_PIXELS: (e) => { + const t = 0 === e.action && 4 !== e.button ? "m" : "M"; + return `[<${c(e, !0)};${e.x};${e.y}${t}`; + }, + }; + let _ = (t.CoreMouseService = class extends a.Disposable { + constructor(e, t) { + (super(), + (this._bufferService = e), + (this._coreService = t), + (this._protocols = {}), + (this._encodings = {}), + (this._activeProtocol = ""), + (this._activeEncoding = ""), + (this._lastEvent = null), + (this._onProtocolChange = this.register(new o.EventEmitter())), + (this.onProtocolChange = this._onProtocolChange.event)); + for (const e of Object.keys(h)) this.addProtocol(e, h[e]); + for (const e of Object.keys(d)) this.addEncoding(e, d[e]); + this.reset(); + } + addProtocol(e, t) { + this._protocols[e] = t; + } + addEncoding(e, t) { + this._encodings[e] = t; + } + get activeProtocol() { + return this._activeProtocol; + } + get areMouseEventsActive() { + return 0 !== this._protocols[this._activeProtocol].events; + } + set activeProtocol(e) { + if (!this._protocols[e]) + throw new Error(`unknown protocol "${e}"`); + ((this._activeProtocol = e), + this._onProtocolChange.fire(this._protocols[e].events)); + } + get activeEncoding() { + return this._activeEncoding; + } + set activeEncoding(e) { + if (!this._encodings[e]) + throw new Error(`unknown encoding "${e}"`); + this._activeEncoding = e; + } + reset() { + ((this.activeProtocol = "NONE"), + (this.activeEncoding = "DEFAULT"), + (this._lastEvent = null)); + } + triggerMouseEvent(e) { + if ( + e.col < 0 || + e.col >= this._bufferService.cols || + e.row < 0 || + e.row >= this._bufferService.rows + ) + return !1; + if (4 === e.button && 32 === e.action) return !1; + if (3 === e.button && 32 !== e.action) return !1; + if (4 !== e.button && (2 === e.action || 3 === e.action)) + return !1; + if ( + (e.col++, + e.row++, + 32 === e.action && + this._lastEvent && + this._equalEvents( + this._lastEvent, + e, + "SGR_PIXELS" === this._activeEncoding, + )) + ) + return !1; + if (!this._protocols[this._activeProtocol].restrict(e)) return !1; + const t = this._encodings[this._activeEncoding](e); + return ( + t && + ("DEFAULT" === this._activeEncoding + ? this._coreService.triggerBinaryEvent(t) + : this._coreService.triggerDataEvent(t, !0)), + (this._lastEvent = e), + !0 + ); + } + explainEvents(e) { + return { + down: !!(1 & e), + up: !!(2 & e), + drag: !!(4 & e), + move: !!(8 & e), + wheel: !!(16 & e), + }; + } + _equalEvents(e, t, i) { + if (i) { + if (e.x !== t.x) return !1; + if (e.y !== t.y) return !1; + } else { + if (e.col !== t.col) return !1; + if (e.row !== t.row) return !1; + } + return ( + e.button === t.button && + e.action === t.action && + e.ctrl === t.ctrl && + e.alt === t.alt && + e.shift === t.shift + ); + } + }); + t.CoreMouseService = _ = s( + [r(0, n.IBufferService), r(1, n.ICoreService)], + _, + ); + }, + 6975: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.CoreService = void 0)); + const n = i(1439), + o = i(8460), + a = i(844), + h = i(2585), + c = Object.freeze({ insertMode: !1 }), + l = Object.freeze({ + applicationCursorKeys: !1, + applicationKeypad: !1, + bracketedPasteMode: !1, + origin: !1, + reverseWraparound: !1, + sendFocus: !1, + wraparound: !0, + }); + let d = (t.CoreService = class extends a.Disposable { + constructor(e, t, i) { + (super(), + (this._bufferService = e), + (this._logService = t), + (this._optionsService = i), + (this.isCursorInitialized = !1), + (this.isCursorHidden = !1), + (this._onData = this.register(new o.EventEmitter())), + (this.onData = this._onData.event), + (this._onUserInput = this.register(new o.EventEmitter())), + (this.onUserInput = this._onUserInput.event), + (this._onBinary = this.register(new o.EventEmitter())), + (this.onBinary = this._onBinary.event), + (this._onRequestScrollToBottom = this.register( + new o.EventEmitter(), + )), + (this.onRequestScrollToBottom = + this._onRequestScrollToBottom.event), + (this.modes = (0, n.clone)(c)), + (this.decPrivateModes = (0, n.clone)(l))); + } + reset() { + ((this.modes = (0, n.clone)(c)), + (this.decPrivateModes = (0, n.clone)(l))); + } + triggerDataEvent(e, t = !1) { + if (this._optionsService.rawOptions.disableStdin) return; + const i = this._bufferService.buffer; + (t && + this._optionsService.rawOptions.scrollOnUserInput && + i.ybase !== i.ydisp && + this._onRequestScrollToBottom.fire(), + t && this._onUserInput.fire(), + this._logService.debug(`sending data "${e}"`, () => + e.split("").map((e) => e.charCodeAt(0)), + ), + this._onData.fire(e)); + } + triggerBinaryEvent(e) { + this._optionsService.rawOptions.disableStdin || + (this._logService.debug(`sending binary "${e}"`, () => + e.split("").map((e) => e.charCodeAt(0)), + ), + this._onBinary.fire(e)); + } + }); + t.CoreService = d = s( + [ + r(0, h.IBufferService), + r(1, h.ILogService), + r(2, h.IOptionsService), + ], + d, + ); + }, + 9074: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.DecorationService = void 0)); + const s = i(8055), + r = i(8460), + n = i(844), + o = i(6106); + let a = 0, + h = 0; + class c extends n.Disposable { + get decorations() { + return this._decorations.values(); + } + constructor() { + (super(), + (this._decorations = new o.SortedList((e) => + null == e ? void 0 : e.marker.line, + )), + (this._onDecorationRegistered = this.register( + new r.EventEmitter(), + )), + (this.onDecorationRegistered = + this._onDecorationRegistered.event), + (this._onDecorationRemoved = this.register( + new r.EventEmitter(), + )), + (this.onDecorationRemoved = this._onDecorationRemoved.event), + this.register((0, n.toDisposable)(() => this.reset()))); + } + registerDecoration(e) { + if (e.marker.isDisposed) return; + const t = new l(e); + if (t) { + const e = t.marker.onDispose(() => t.dispose()); + (t.onDispose(() => { + t && + (this._decorations.delete(t) && + this._onDecorationRemoved.fire(t), + e.dispose()); + }), + this._decorations.insert(t), + this._onDecorationRegistered.fire(t)); + } + return t; + } + reset() { + for (const e of this._decorations.values()) e.dispose(); + this._decorations.clear(); + } + *getDecorationsAtCell(e, t, i) { + var s, r, n; + let o = 0, + a = 0; + for (const h of this._decorations.getKeyIterator(t)) + ((o = null !== (s = h.options.x) && void 0 !== s ? s : 0), + (a = + o + + (null !== (r = h.options.width) && void 0 !== r ? r : 1)), + e >= o && + e < a && + (!i || + (null !== (n = h.options.layer) && void 0 !== n + ? n + : "bottom") === i) && + (yield h)); + } + forEachDecorationAtCell(e, t, i, s) { + this._decorations.forEachByKey(t, (t) => { + var r, n, o; + ((a = null !== (r = t.options.x) && void 0 !== r ? r : 0), + (h = + a + + (null !== (n = t.options.width) && void 0 !== n ? n : 1)), + e >= a && + e < h && + (!i || + (null !== (o = t.options.layer) && void 0 !== o + ? o + : "bottom") === i) && + s(t)); + }); + } + } + t.DecorationService = c; + class l extends n.Disposable { + get isDisposed() { + return this._isDisposed; + } + get backgroundColorRGB() { + return ( + null === this._cachedBg && + (this.options.backgroundColor + ? (this._cachedBg = s.css.toColor( + this.options.backgroundColor, + )) + : (this._cachedBg = void 0)), + this._cachedBg + ); + } + get foregroundColorRGB() { + return ( + null === this._cachedFg && + (this.options.foregroundColor + ? (this._cachedFg = s.css.toColor( + this.options.foregroundColor, + )) + : (this._cachedFg = void 0)), + this._cachedFg + ); + } + constructor(e) { + (super(), + (this.options = e), + (this.onRenderEmitter = this.register(new r.EventEmitter())), + (this.onRender = this.onRenderEmitter.event), + (this._onDispose = this.register(new r.EventEmitter())), + (this.onDispose = this._onDispose.event), + (this._cachedBg = null), + (this._cachedFg = null), + (this.marker = e.marker), + this.options.overviewRulerOptions && + !this.options.overviewRulerOptions.position && + (this.options.overviewRulerOptions.position = "full")); + } + dispose() { + (this._onDispose.fire(), super.dispose()); + } + } + }, + 4348: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.InstantiationService = t.ServiceCollection = void 0)); + const s = i(2585), + r = i(8343); + class n { + constructor(...e) { + this._entries = new Map(); + for (const [t, i] of e) this.set(t, i); + } + set(e, t) { + const i = this._entries.get(e); + return (this._entries.set(e, t), i); + } + forEach(e) { + for (const [t, i] of this._entries.entries()) e(t, i); + } + has(e) { + return this._entries.has(e); + } + get(e) { + return this._entries.get(e); + } + } + ((t.ServiceCollection = n), + (t.InstantiationService = class { + constructor() { + ((this._services = new n()), + this._services.set(s.IInstantiationService, this)); + } + setService(e, t) { + this._services.set(e, t); + } + getService(e) { + return this._services.get(e); + } + createInstance(e, ...t) { + const i = (0, r.getServiceDependencies)(e).sort( + (e, t) => e.index - t.index, + ), + s = []; + for (const t of i) { + const i = this._services.get(t.id); + if (!i) + throw new Error( + `[createInstance] ${e.name} depends on UNKNOWN service ${t.id}.`, + ); + s.push(i); + } + const n = i.length > 0 ? i[0].index : t.length; + if (t.length !== n) + throw new Error( + `[createInstance] First service dependency of ${e.name} at position ${n + 1} conflicts with ${t.length} static arguments`, + ); + return new e(...[...t, ...s]); + } + })); + }, + 7866: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.traceCall = t.setTraceLogger = t.LogService = void 0)); + const n = i(844), + o = i(2585), + a = { + trace: o.LogLevelEnum.TRACE, + debug: o.LogLevelEnum.DEBUG, + info: o.LogLevelEnum.INFO, + warn: o.LogLevelEnum.WARN, + error: o.LogLevelEnum.ERROR, + off: o.LogLevelEnum.OFF, + }; + let h, + c = (t.LogService = class extends n.Disposable { + get logLevel() { + return this._logLevel; + } + constructor(e) { + (super(), + (this._optionsService = e), + (this._logLevel = o.LogLevelEnum.OFF), + this._updateLogLevel(), + this.register( + this._optionsService.onSpecificOptionChange( + "logLevel", + () => this._updateLogLevel(), + ), + ), + (h = this)); + } + _updateLogLevel() { + this._logLevel = a[this._optionsService.rawOptions.logLevel]; + } + _evalLazyOptionalParams(e) { + for (let t = 0; t < e.length; t++) + "function" == typeof e[t] && (e[t] = e[t]()); + } + _log(e, t, i) { + (this._evalLazyOptionalParams(i), + e.call( + console, + (this._optionsService.options.logger ? "" : "xterm.js: ") + + t, + ...i, + )); + } + trace(e, ...t) { + var i, s; + this._logLevel <= o.LogLevelEnum.TRACE && + this._log( + null !== + (s = + null === (i = this._optionsService.options.logger) || + void 0 === i + ? void 0 + : i.trace.bind( + this._optionsService.options.logger, + )) && void 0 !== s + ? s + : console.log, + e, + t, + ); + } + debug(e, ...t) { + var i, s; + this._logLevel <= o.LogLevelEnum.DEBUG && + this._log( + null !== + (s = + null === (i = this._optionsService.options.logger) || + void 0 === i + ? void 0 + : i.debug.bind( + this._optionsService.options.logger, + )) && void 0 !== s + ? s + : console.log, + e, + t, + ); + } + info(e, ...t) { + var i, s; + this._logLevel <= o.LogLevelEnum.INFO && + this._log( + null !== + (s = + null === (i = this._optionsService.options.logger) || + void 0 === i + ? void 0 + : i.info.bind(this._optionsService.options.logger)) && + void 0 !== s + ? s + : console.info, + e, + t, + ); + } + warn(e, ...t) { + var i, s; + this._logLevel <= o.LogLevelEnum.WARN && + this._log( + null !== + (s = + null === (i = this._optionsService.options.logger) || + void 0 === i + ? void 0 + : i.warn.bind(this._optionsService.options.logger)) && + void 0 !== s + ? s + : console.warn, + e, + t, + ); + } + error(e, ...t) { + var i, s; + this._logLevel <= o.LogLevelEnum.ERROR && + this._log( + null !== + (s = + null === (i = this._optionsService.options.logger) || + void 0 === i + ? void 0 + : i.error.bind( + this._optionsService.options.logger, + )) && void 0 !== s + ? s + : console.error, + e, + t, + ); + } + }); + ((t.LogService = c = s([r(0, o.IOptionsService)], c)), + (t.setTraceLogger = function (e) { + h = e; + }), + (t.traceCall = function (e, t, i) { + if ("function" != typeof i.value) + throw new Error("not supported"); + const s = i.value; + i.value = function (...e) { + if (h.logLevel !== o.LogLevelEnum.TRACE) + return s.apply(this, e); + h.trace( + `GlyphRenderer#${s.name}(${e.map((e) => JSON.stringify(e)).join(", ")})`, + ); + const t = s.apply(this, e); + return (h.trace(`GlyphRenderer#${s.name} return`, t), t); + }; + })); + }, + 7302: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.OptionsService = t.DEFAULT_OPTIONS = void 0)); + const s = i(8460), + r = i(844), + n = i(6114); + t.DEFAULT_OPTIONS = { + cols: 80, + rows: 24, + cursorBlink: !1, + cursorStyle: "block", + cursorWidth: 1, + cursorInactiveStyle: "outline", + customGlyphs: !0, + drawBoldTextInBrightColors: !0, + fastScrollModifier: "alt", + fastScrollSensitivity: 5, + fontFamily: "courier-new, courier, monospace", + fontSize: 15, + fontWeight: "normal", + fontWeightBold: "bold", + ignoreBracketedPasteMode: !1, + lineHeight: 1, + letterSpacing: 0, + linkHandler: null, + logLevel: "info", + logger: null, + scrollback: 1e3, + scrollOnUserInput: !0, + scrollSensitivity: 1, + screenReaderMode: !1, + smoothScrollDuration: 0, + macOptionIsMeta: !1, + macOptionClickForcesSelection: !1, + minimumContrastRatio: 1, + disableStdin: !1, + allowProposedApi: !1, + allowTransparency: !1, + tabStopWidth: 8, + theme: {}, + rightClickSelectsWord: n.isMac, + windowOptions: {}, + windowsMode: !1, + windowsPty: {}, + wordSeparator: " ()[]{}',\"`", + altClickMovesCursor: !0, + convertEol: !1, + termName: "xterm", + cancelEvents: !1, + overviewRulerWidth: 0, + }; + const o = [ + "normal", + "bold", + "100", + "200", + "300", + "400", + "500", + "600", + "700", + "800", + "900", + ]; + class a extends r.Disposable { + constructor(e) { + (super(), + (this._onOptionChange = this.register(new s.EventEmitter())), + (this.onOptionChange = this._onOptionChange.event)); + const i = Object.assign({}, t.DEFAULT_OPTIONS); + for (const t in e) + if (t in i) + try { + const s = e[t]; + i[t] = this._sanitizeAndValidateOption(t, s); + } catch (e) { + console.error(e); + } + ((this.rawOptions = i), + (this.options = Object.assign({}, i)), + this._setupOptions()); + } + onSpecificOptionChange(e, t) { + return this.onOptionChange((i) => { + i === e && t(this.rawOptions[e]); + }); + } + onMultipleOptionChange(e, t) { + return this.onOptionChange((i) => { + -1 !== e.indexOf(i) && t(); + }); + } + _setupOptions() { + const e = (e) => { + if (!(e in t.DEFAULT_OPTIONS)) + throw new Error(`No option with key "${e}"`); + return this.rawOptions[e]; + }, + i = (e, i) => { + if (!(e in t.DEFAULT_OPTIONS)) + throw new Error(`No option with key "${e}"`); + ((i = this._sanitizeAndValidateOption(e, i)), + this.rawOptions[e] !== i && + ((this.rawOptions[e] = i), this._onOptionChange.fire(e))); + }; + for (const t in this.rawOptions) { + const s = { get: e.bind(this, t), set: i.bind(this, t) }; + Object.defineProperty(this.options, t, s); + } + } + _sanitizeAndValidateOption(e, i) { + switch (e) { + case "cursorStyle": + if ( + (i || (i = t.DEFAULT_OPTIONS[e]), + !(function (e) { + return "block" === e || "underline" === e || "bar" === e; + })(i)) + ) + throw new Error(`"${i}" is not a valid value for ${e}`); + break; + case "wordSeparator": + i || (i = t.DEFAULT_OPTIONS[e]); + break; + case "fontWeight": + case "fontWeightBold": + if ("number" == typeof i && 1 <= i && i <= 1e3) break; + i = o.includes(i) ? i : t.DEFAULT_OPTIONS[e]; + break; + case "cursorWidth": + i = Math.floor(i); + case "lineHeight": + case "tabStopWidth": + if (i < 1) + throw new Error(`${e} cannot be less than 1, value: ${i}`); + break; + case "minimumContrastRatio": + i = Math.max(1, Math.min(21, Math.round(10 * i) / 10)); + break; + case "scrollback": + if ((i = Math.min(i, 4294967295)) < 0) + throw new Error(`${e} cannot be less than 0, value: ${i}`); + break; + case "fastScrollSensitivity": + case "scrollSensitivity": + if (i <= 0) + throw new Error( + `${e} cannot be less than or equal to 0, value: ${i}`, + ); + break; + case "rows": + case "cols": + if (!i && 0 !== i) + throw new Error(`${e} must be numeric, value: ${i}`); + break; + case "windowsPty": + i = null != i ? i : {}; + } + return i; + } + } + t.OptionsService = a; + }, + 2660: function (e, t, i) { + var s = + (this && this.__decorate) || + function (e, t, i, s) { + var r, + n = arguments.length, + o = + n < 3 + ? t + : null === s + ? (s = Object.getOwnPropertyDescriptor(t, i)) + : s; + if ( + "object" == typeof Reflect && + "function" == typeof Reflect.decorate + ) + o = Reflect.decorate(e, t, i, s); + else + for (var a = e.length - 1; a >= 0; a--) + (r = e[a]) && + (o = (n < 3 ? r(o) : n > 3 ? r(t, i, o) : r(t, i)) || o); + return (n > 3 && o && Object.defineProperty(t, i, o), o); + }, + r = + (this && this.__param) || + function (e, t) { + return function (i, s) { + t(i, s, e); + }; + }; + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.OscLinkService = void 0)); + const n = i(2585); + let o = (t.OscLinkService = class { + constructor(e) { + ((this._bufferService = e), + (this._nextId = 1), + (this._entriesWithId = new Map()), + (this._dataByLinkId = new Map())); + } + registerLink(e) { + const t = this._bufferService.buffer; + if (void 0 === e.id) { + const i = t.addMarker(t.ybase + t.y), + s = { data: e, id: this._nextId++, lines: [i] }; + return ( + i.onDispose(() => this._removeMarkerFromLink(s, i)), + this._dataByLinkId.set(s.id, s), + s.id + ); + } + const i = e, + s = this._getEntryIdKey(i), + r = this._entriesWithId.get(s); + if (r) return (this.addLineToLink(r.id, t.ybase + t.y), r.id); + const n = t.addMarker(t.ybase + t.y), + o = { + id: this._nextId++, + key: this._getEntryIdKey(i), + data: i, + lines: [n], + }; + return ( + n.onDispose(() => this._removeMarkerFromLink(o, n)), + this._entriesWithId.set(o.key, o), + this._dataByLinkId.set(o.id, o), + o.id + ); + } + addLineToLink(e, t) { + const i = this._dataByLinkId.get(e); + if (i && i.lines.every((e) => e.line !== t)) { + const e = this._bufferService.buffer.addMarker(t); + (i.lines.push(e), + e.onDispose(() => this._removeMarkerFromLink(i, e))); + } + } + getLinkData(e) { + var t; + return null === (t = this._dataByLinkId.get(e)) || void 0 === t + ? void 0 + : t.data; + } + _getEntryIdKey(e) { + return `${e.id};;${e.uri}`; + } + _removeMarkerFromLink(e, t) { + const i = e.lines.indexOf(t); + -1 !== i && + (e.lines.splice(i, 1), + 0 === e.lines.length && + (void 0 !== e.data.id && this._entriesWithId.delete(e.key), + this._dataByLinkId.delete(e.id))); + } + }); + t.OscLinkService = o = s([r(0, n.IBufferService)], o); + }, + 8343: (e, t) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.createDecorator = + t.getServiceDependencies = + t.serviceRegistry = + void 0)); + const i = "di$target", + s = "di$dependencies"; + ((t.serviceRegistry = new Map()), + (t.getServiceDependencies = function (e) { + return e[s] || []; + }), + (t.createDecorator = function (e) { + if (t.serviceRegistry.has(e)) return t.serviceRegistry.get(e); + const r = function (e, t, n) { + if (3 !== arguments.length) + throw new Error( + "@IServiceName-decorator can only be used to decorate a parameter", + ); + !(function (e, t, r) { + t[i] === t + ? t[s].push({ id: e, index: r }) + : ((t[s] = [{ id: e, index: r }]), (t[i] = t)); + })(r, e, n); + }; + return ((r.toString = () => e), t.serviceRegistry.set(e, r), r); + })); + }, + 2585: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.IDecorationService = + t.IUnicodeService = + t.IOscLinkService = + t.IOptionsService = + t.ILogService = + t.LogLevelEnum = + t.IInstantiationService = + t.ICharsetService = + t.ICoreService = + t.ICoreMouseService = + t.IBufferService = + void 0)); + const s = i(8343); + var r; + ((t.IBufferService = (0, s.createDecorator)("BufferService")), + (t.ICoreMouseService = (0, s.createDecorator)("CoreMouseService")), + (t.ICoreService = (0, s.createDecorator)("CoreService")), + (t.ICharsetService = (0, s.createDecorator)("CharsetService")), + (t.IInstantiationService = (0, s.createDecorator)( + "InstantiationService", + )), + (function (e) { + ((e[(e.TRACE = 0)] = "TRACE"), + (e[(e.DEBUG = 1)] = "DEBUG"), + (e[(e.INFO = 2)] = "INFO"), + (e[(e.WARN = 3)] = "WARN"), + (e[(e.ERROR = 4)] = "ERROR"), + (e[(e.OFF = 5)] = "OFF")); + })(r || (t.LogLevelEnum = r = {})), + (t.ILogService = (0, s.createDecorator)("LogService")), + (t.IOptionsService = (0, s.createDecorator)("OptionsService")), + (t.IOscLinkService = (0, s.createDecorator)("OscLinkService")), + (t.IUnicodeService = (0, s.createDecorator)("UnicodeService")), + (t.IDecorationService = (0, s.createDecorator)( + "DecorationService", + ))); + }, + 1480: (e, t, i) => { + (Object.defineProperty(t, "__esModule", { value: !0 }), + (t.UnicodeService = void 0)); + const s = i(8460), + r = i(225); + t.UnicodeService = class { + constructor() { + ((this._providers = Object.create(null)), + (this._active = ""), + (this._onChange = new s.EventEmitter()), + (this.onChange = this._onChange.event)); + const e = new r.UnicodeV6(); + (this.register(e), + (this._active = e.version), + (this._activeProvider = e)); + } + dispose() { + this._onChange.dispose(); + } + get versions() { + return Object.keys(this._providers); + } + get activeVersion() { + return this._active; + } + set activeVersion(e) { + if (!this._providers[e]) + throw new Error(`unknown Unicode version "${e}"`); + ((this._active = e), + (this._activeProvider = this._providers[e]), + this._onChange.fire(e)); + } + register(e) { + this._providers[e.version] = e; + } + wcwidth(e) { + return this._activeProvider.wcwidth(e); + } + getStringCellWidth(e) { + let t = 0; + const i = e.length; + for (let s = 0; s < i; ++s) { + let r = e.charCodeAt(s); + if (55296 <= r && r <= 56319) { + if (++s >= i) return t + this.wcwidth(r); + const n = e.charCodeAt(s); + 56320 <= n && n <= 57343 + ? (r = 1024 * (r - 55296) + n - 56320 + 65536) + : (t += this.wcwidth(n)); + } + t += this.wcwidth(r); + } + return t; + } + }; + }, + }, + t = {}; + function i(s) { + var r = t[s]; + if (void 0 !== r) return r.exports; + var n = (t[s] = { exports: {} }); + return (e[s].call(n.exports, n, n.exports, i), n.exports); + } + var s = {}; + return ( + (() => { + var e = s; + (Object.defineProperty(e, "__esModule", { value: !0 }), + (e.Terminal = void 0)); + const t = i(9042), + r = i(3236), + n = i(844), + o = i(5741), + a = i(8285), + h = i(7975), + c = i(7090), + l = ["cols", "rows"]; + class d extends n.Disposable { + constructor(e) { + (super(), + (this._core = this.register(new r.Terminal(e))), + (this._addonManager = this.register(new o.AddonManager())), + (this._publicOptions = Object.assign({}, this._core.options))); + const t = (e) => this._core.options[e], + i = (e, t) => { + (this._checkReadonlyOptions(e), (this._core.options[e] = t)); + }; + for (const e in this._core.options) { + const s = { get: t.bind(this, e), set: i.bind(this, e) }; + Object.defineProperty(this._publicOptions, e, s); + } + } + _checkReadonlyOptions(e) { + if (l.includes(e)) + throw new Error( + `Option "${e}" can only be set in the constructor`, + ); + } + _checkProposedApi() { + if (!this._core.optionsService.rawOptions.allowProposedApi) + throw new Error( + "You must set the allowProposedApi option to true to use proposed API", + ); + } + get onBell() { + return this._core.onBell; + } + get onBinary() { + return this._core.onBinary; + } + get onCursorMove() { + return this._core.onCursorMove; + } + get onData() { + return this._core.onData; + } + get onKey() { + return this._core.onKey; + } + get onLineFeed() { + return this._core.onLineFeed; + } + get onRender() { + return this._core.onRender; + } + get onResize() { + return this._core.onResize; + } + get onScroll() { + return this._core.onScroll; + } + get onSelectionChange() { + return this._core.onSelectionChange; + } + get onTitleChange() { + return this._core.onTitleChange; + } + get onWriteParsed() { + return this._core.onWriteParsed; + } + get element() { + return this._core.element; + } + get parser() { + return ( + this._parser || (this._parser = new h.ParserApi(this._core)), + this._parser + ); + } + get unicode() { + return (this._checkProposedApi(), new c.UnicodeApi(this._core)); + } + get textarea() { + return this._core.textarea; + } + get rows() { + return this._core.rows; + } + get cols() { + return this._core.cols; + } + get buffer() { + return ( + this._buffer || + (this._buffer = this.register( + new a.BufferNamespaceApi(this._core), + )), + this._buffer + ); + } + get markers() { + return (this._checkProposedApi(), this._core.markers); + } + get modes() { + const e = this._core.coreService.decPrivateModes; + let t = "none"; + switch (this._core.coreMouseService.activeProtocol) { + case "X10": + t = "x10"; + break; + case "VT200": + t = "vt200"; + break; + case "DRAG": + t = "drag"; + break; + case "ANY": + t = "any"; + } + return { + applicationCursorKeysMode: e.applicationCursorKeys, + applicationKeypadMode: e.applicationKeypad, + bracketedPasteMode: e.bracketedPasteMode, + insertMode: this._core.coreService.modes.insertMode, + mouseTrackingMode: t, + originMode: e.origin, + reverseWraparoundMode: e.reverseWraparound, + sendFocusMode: e.sendFocus, + wraparoundMode: e.wraparound, + }; + } + get options() { + return this._publicOptions; + } + set options(e) { + for (const t in e) this._publicOptions[t] = e[t]; + } + blur() { + this._core.blur(); + } + focus() { + this._core.focus(); + } + resize(e, t) { + (this._verifyIntegers(e, t), this._core.resize(e, t)); + } + open(e) { + this._core.open(e); + } + attachCustomKeyEventHandler(e) { + this._core.attachCustomKeyEventHandler(e); + } + registerLinkProvider(e) { + return this._core.registerLinkProvider(e); + } + registerCharacterJoiner(e) { + return ( + this._checkProposedApi(), + this._core.registerCharacterJoiner(e) + ); + } + deregisterCharacterJoiner(e) { + (this._checkProposedApi(), this._core.deregisterCharacterJoiner(e)); + } + registerMarker(e = 0) { + return (this._verifyIntegers(e), this._core.registerMarker(e)); + } + registerDecoration(e) { + var t, i, s; + return ( + this._checkProposedApi(), + this._verifyPositiveIntegers( + null !== (t = e.x) && void 0 !== t ? t : 0, + null !== (i = e.width) && void 0 !== i ? i : 0, + null !== (s = e.height) && void 0 !== s ? s : 0, + ), + this._core.registerDecoration(e) + ); + } + hasSelection() { + return this._core.hasSelection(); + } + select(e, t, i) { + (this._verifyIntegers(e, t, i), this._core.select(e, t, i)); + } + getSelection() { + return this._core.getSelection(); + } + getSelectionPosition() { + return this._core.getSelectionPosition(); + } + clearSelection() { + this._core.clearSelection(); + } + selectAll() { + this._core.selectAll(); + } + selectLines(e, t) { + (this._verifyIntegers(e, t), this._core.selectLines(e, t)); + } + dispose() { + super.dispose(); + } + scrollLines(e) { + (this._verifyIntegers(e), this._core.scrollLines(e)); + } + scrollPages(e) { + (this._verifyIntegers(e), this._core.scrollPages(e)); + } + scrollToTop() { + this._core.scrollToTop(); + } + scrollToBottom() { + this._core.scrollToBottom(); + } + scrollToLine(e) { + (this._verifyIntegers(e), this._core.scrollToLine(e)); + } + clear() { + this._core.clear(); + } + write(e, t) { + this._core.write(e, t); + } + writeln(e, t) { + (this._core.write(e), this._core.write("\r\n", t)); + } + paste(e) { + this._core.paste(e); + } + refresh(e, t) { + (this._verifyIntegers(e, t), this._core.refresh(e, t)); + } + reset() { + this._core.reset(); + } + clearTextureAtlas() { + this._core.clearTextureAtlas(); + } + loadAddon(e) { + this._addonManager.loadAddon(this, e); + } + static get strings() { + return t; + } + _verifyIntegers(...e) { + for (const t of e) + if (t === 1 / 0 || isNaN(t) || t % 1 != 0) + throw new Error("This API only accepts integers"); + } + _verifyPositiveIntegers(...e) { + for (const t of e) + if (t && (t === 1 / 0 || isNaN(t) || t % 1 != 0 || t < 0)) + throw new Error("This API only accepts positive integers"); + } + } + e.Terminal = d; + })(), + s + ); + })(), +); +//# sourceMappingURL=xterm.js.map