updated codestyle
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Make-Without-sqlite3 (push) Successful in 6s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-CMake-Without-sqlite3 (push) Successful in 9s
Prepare Build and Testing executable binary / Prepare-Build-Testing-With-Meson-Without-sqlite3 (push) Successful in 7s

This commit is contained in:
wt committed 2025-11-18 11:48:46 +07:00
1 parent 193779bd13
commit 36aa1bea2a
10 files changed
+15967 -1547

No files matched your search

+757 -1083
View File
File diff suppressed because it is too large. Load diff
+196 -107
View File
@@ -24,23 +24,27 @@
#define cJSON__h #define cJSON__h
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C" {
{
#endif #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__ #define __WINDOWS__
#endif #endif
#ifdef __WINDOWS__ #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_HIDE_SYMBOLS - Define this in the case where you don't want to ever
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) dllexport symbols CJSON_EXPORT_SYMBOLS - Define this on library build when you
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol 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 setting default visibility to hidden by adding
-fvisibility=hidden (for gcc) -fvisibility=hidden (for gcc)
@@ -48,15 +52,18 @@ or
-xldscope=hidden (for sun cc) -xldscope=hidden (for sun cc)
to CFLAGS 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_CDECL __cdecl
#define CJSON_STDCALL __stdcall #define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */ /* export symbols by default, this is necessary for copy pasting the C and
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) * header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && \
!defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS #define CJSON_EXPORT_SYMBOLS
#endif #endif
@@ -71,7 +78,8 @@ then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJ
#define CJSON_CDECL #define CJSON_CDECL
#define CJSON_STDCALL #define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) #if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__SUNPRO_C)) && \
defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type #define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else #else
#define CJSON_PUBLIC(type) type #define CJSON_PUBLIC(type) type
@@ -100,12 +108,13 @@ then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJ
#define cJSON_StringIsConst 512 #define cJSON_StringIsConst 512
/* The cJSON structure: */ /* The cJSON structure: */
typedef struct cJSON typedef struct cJSON {
{ /* next/prev allow you to walk array/object chains. Alternatively, use
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ * GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next; struct cJSON *next;
struct cJSON *prev; struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ /* An array or object item will have a child pointer pointing to a chain of
* the items in the array/object. */
struct cJSON *child; struct cJSON *child;
/* The type of the item, as above. */ /* The type of the item, as above. */
@@ -118,84 +127,114 @@ typedef struct cJSON
/* The item's number, if type==cJSON_Number */ /* The item's number, if type==cJSON_Number */
double valuedouble; double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ /* The item's name string, if this item is the child of, or is in the list of
* subitems of an object. */
char *string; char *string;
} cJSON; } cJSON;
typedef struct cJSON_Hooks typedef struct cJSON_Hooks {
{ /* malloc/free are CDECL on Windows regardless of the default calling
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ * convention of the compiler, so ensure the hooks allow passing those
* functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz); void *(CJSON_CDECL *malloc_fn)(size_t sz);
void (CJSON_CDECL *free_fn)(void *ptr); void(CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks; } cJSON_Hooks;
typedef int cJSON_bool; typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. /* Limits how deeply nested arrays/objects can be before cJSON rejects to parse
* This is to prevent stack overflows. */ * them. This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT #ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000 #define CJSON_NESTING_LIMIT 1000
#endif #endif
/* Limits the length of circular references can be before cJSON rejects to parse them. /* Limits the length of circular references can be before cJSON rejects to parse
* This is to prevent stack overflows. */ * them. This is to prevent stack overflows. */
#ifndef CJSON_CIRCULAR_LIMIT #ifndef CJSON_CIRCULAR_LIMIT
#define CJSON_CIRCULAR_LIMIT 10000 #define CJSON_CIRCULAR_LIMIT 10000
#endif #endif
/* returns the version of cJSON as a string */ /* 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 */ /* 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. */ /* Memory Management: the caller is always responsible to free the results from
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ * 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_Parse(const char *value);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); CJSON_PUBLIC(cJSON *)
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ cJSON_ParseWithLength(const char *value, size_t buffer_length);
/* 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(). */ /* ParseWithOpts allows you to require (and check) that the JSON is null
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); * terminated, and to retrieve the pointer to the final byte parsed. */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); /* 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. */ /* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */ /* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); 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 */ /* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); * at the final size. guessing well reduces reallocation. fmt=0 gives
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ * unformatted, =1 gives formatted */
/* 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(char *)
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); 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. */ /* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
/* Returns the number of items in an array (or object). */ /* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); 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); CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */ /* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); cJSON_GetObjectItem(const cJSON *const object, const char *const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); CJSON_PUBLIC(cJSON *)
/* 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_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); CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */ /* Check item type and return its value */
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON *const item);
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON *const item);
/* These functions check the type of an item */ /* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(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_IsFalse(const cJSON *const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(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_IsBool(const cJSON *const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(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_IsNumber(const cJSON *const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(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_IsArray(const cJSON *const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(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_IsRaw(const cJSON *const item);
/* These calls create a cJSON item of the appropriate type. */ /* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); 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); CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items. /* 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_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *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_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. */ /* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); CJSON_PUBLIC(cJSON_bool)
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before /* Use this when string is definitely const (i.e. a literal, or as good as), and
* writing to `item->string` */ * will definitely survive the cJSON object. WARNING: When this function was
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); * used, make sure to always check that (item->type & cJSON_StringIsConst) is
/* 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. */ * zero before writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); CJSON_PUBLIC(cJSON_bool)
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); 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. */ /* 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(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(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_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); 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. */ /* 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_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); cJSON_InsertItemInArray(
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); cJSON *array, int which,
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); 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 */ /* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); 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 /* Duplicate will create a new, identical cJSON item to the one you pass, in new
* need to be released. With recurse!=0, it will duplicate any children connected to the item. * memory that will need to be released. With recurse!=0, it will duplicate any
* The item->next and ->prev pointers are always zero on return from Duplicate. */ * children connected to the item. The item->next and ->prev pointers are always
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. * zero on return from Duplicate. */
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ /* Recursively compare two cJSON items for equality. If either a or b is NULL or
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); * 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. /* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from
* The input pointer json cannot point to a read-only address area, such as a string constant, * strings. The input pointer json cannot point to a read-only address area,
* but should point to a readable and writable address area. */ * such as a string constant, but should point to a readable and writable
* address area. */
CJSON_PUBLIC(void) cJSON_Minify(char *json); CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time. /* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */ * 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_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); cJSON_AddNullToObject(cJSON *const object, const char *const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); cJSON_AddTrueToObject(cJSON *const object, const char *const name);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); cJSON_AddFalseToObject(cJSON *const object, const char *const name);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); CJSON_PUBLIC(cJSON *)
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); cJSON_AddBoolToObject(cJSON *const object, const char *const name,
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(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. */ /* When assigning an integer value, it needs to be propagated to valuedouble
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) * too. */
#define cJSON_SetIntValue(object, number) \
((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */ /* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) #define cJSON_SetNumberValue(object, number) \
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); /* 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*/ /* If the object is not a boolean type this does nothing and returns
#define cJSON_SetBoolValue(object, boolValue) ( \ * cJSON_Invalid else it returns the new type*/
(object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ #define cJSON_SetBoolValue(object, boolValue) \
(object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ ((object != NULL && ((object)->type & (cJSON_False | cJSON_True))) \
cJSON_Invalid\ ? (object)->type = ((object)->type & (~(cJSON_False | cJSON_True))) | \
) ((boolValue) ? cJSON_True : cJSON_False) \
: cJSON_Invalid)
/* Macro for iterating over an array or object */ /* 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_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object); CJSON_PUBLIC(void) cJSON_free(void *object);
+43 -26
View File
@@ -1,13 +1,13 @@
#include "terminal.h"
#include <cJSON.h>
#include <errno.h>
#include <mongoose.h>
#include <signal.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <errno.h> #include <sys/wait.h>
#include <mongoose.h>
#include <cJSON.h>
#include "terminal.h"
#define HTTP_PORT "8888" #define HTTP_PORT "8888"
#define STATIC_DIR "./static/" #define STATIC_DIR "./static/"
@@ -28,7 +28,8 @@ static void log_request(struct mg_connection *c, struct mg_http_message *hm) {
// Проверяем, жив ли дочерний процесс // Проверяем, жив ли дочерний процесс
static bool is_process_alive(pid_t pid) { static bool is_process_alive(pid_t pid) {
if (pid <= 0) return false; if (pid <= 0)
return false;
int status; int status;
pid_t result = waitpid(pid, &status, WNOHANG); pid_t result = waitpid(pid, &status, WNOHANG);
@@ -50,8 +51,10 @@ static bool is_process_alive(pid_t pid) {
} }
// Перезапускаем терминальную сессию // Перезапускаем терминальную сессию
static void restart_terminal_session(struct mg_connection *c, struct client_data *cd) { static void restart_terminal_session(struct mg_connection *c,
if (!cd) return; struct client_data *cd) {
if (!cd)
return;
printf("Restarting terminal session...\n"); printf("Restarting terminal session...\n");
@@ -62,20 +65,25 @@ static void restart_terminal_session(struct mg_connection *c, struct client_data
// Создаем новую сессию // Создаем новую сессию
const char *shell = getenv("SHELL"); const char *shell = getenv("SHELL");
if (!shell) shell = "/bin/bash"; if (!shell)
shell = "/bin/bash";
if (create_terminal_session(&cd->term, shell) == 0) { if (create_terminal_session(&cd->term, shell) == 0) {
cd->terminal_ready = true; cd->terminal_ready = true;
mg_ws_send(c, "\r\n*** Terminal restarted ***\r\n", 29, WEBSOCKET_OP_TEXT); mg_ws_send(c, "\r\n*** Terminal restarted ***\r\n", 29, WEBSOCKET_OP_TEXT);
} else { } else {
mg_ws_send(c, "\r\n*** Failed to restart terminal ***\r\n", 37, WEBSOCKET_OP_TEXT); mg_ws_send(c, "\r\n*** Failed to restart terminal ***\r\n", 37,
WEBSOCKET_OP_TEXT);
cd->terminal_ready = false; cd->terminal_ready = false;
} }
} }
// Обработчик WebSocket сообщений // Обработчик WebSocket сообщений
static void handle_websocket_message(struct mg_connection *c, struct mg_ws_message *wm, struct client_data *cd) { static void handle_websocket_message(struct mg_connection *c,
if (!cd) return; struct mg_ws_message *wm,
struct client_data *cd) {
if (!cd)
return;
if (wm->data.len == 0) { if (wm->data.len == 0) {
return; return;
@@ -119,7 +127,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (mg_match(hm->uri, mg_str("/ws"), nullptr)) { if (mg_match(hm->uri, mg_str("/ws"), nullptr)) {
// Проверяем, нет ли уже активного соединения // Проверяем, нет ли уже активного соединения
if (c->fn_data != NULL) { if (c->fn_data != NULL) {
printf("WebSocket connection already exists for this connection, cleaning up...\n"); printf("WebSocket connection already exists for this connection, "
"cleaning up...\n");
struct client_data *old_cd = (struct client_data *)c->fn_data; struct client_data *old_cd = (struct client_data *)c->fn_data;
destroy_terminal_session(&old_cd->term); destroy_terminal_session(&old_cd->term);
free(old_cd); free(old_cd);
@@ -129,17 +138,20 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
// Upgrade до WebSocket // Upgrade до WebSocket
struct client_data *cd = calloc(1, sizeof(struct client_data)); struct client_data *cd = calloc(1, sizeof(struct client_data));
if (!cd) { if (!cd) {
mg_http_reply(c, 500, "Content-Type: text/plain\r\n", "Memory allocation failed"); mg_http_reply(c, 500, "Content-Type: text/plain\r\n",
"Memory allocation failed");
return; return;
} }
// Создаем терминальную сессию // Создаем терминальную сессию
const char *shell = getenv("SHELL"); const char *shell = getenv("SHELL");
if (!shell) shell = "/bin/bash"; if (!shell)
shell = "/bin/bash";
printf("Creating new terminal session with shell: %s\n", shell); printf("Creating new terminal session with shell: %s\n", shell);
if (create_terminal_session(&cd->term, shell) != 0) { if (create_terminal_session(&cd->term, shell) != 0) {
mg_http_reply(c, 500, "Content-Type: text/plain\r\n", "Failed to create terminal session"); mg_http_reply(c, 500, "Content-Type: text/plain\r\n",
"Failed to create terminal session");
free(cd); free(cd);
return; return;
} }
@@ -148,7 +160,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
c->fn_data = cd; c->fn_data = cd;
// Upgrade to WebSocket // Upgrade to WebSocket
struct mg_str *ws_proto = mg_http_get_header(hm, "Sec-WebSocket-Protocol"); struct mg_str *ws_proto =
mg_http_get_header(hm, "Sec-WebSocket-Protocol");
if (ws_proto != NULL) { if (ws_proto != NULL) {
mg_ws_upgrade(c, hm, ws_proto->buf); mg_ws_upgrade(c, hm, ws_proto->buf);
} else { } else {
@@ -159,22 +172,22 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
} else if (mg_match(hm->uri, mg_str("/"), nullptr)) { } else if (mg_match(hm->uri, mg_str("/"), nullptr)) {
// Главная страница // Главная страница
struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR};
mg_http_serve_file(c, hm, "./static/index.html", &opts); mg_http_serve_file(c, hm, "./static/index.html", &opts);
} else if (mg_match(hm->uri, mg_str("/xterm.js"), nullptr)) { } else if (mg_match(hm->uri, mg_str("/xterm.js"), nullptr)) {
// xterm.js // xterm.js
struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR};
mg_http_serve_file(c, hm, "./static/xterm.js", &opts); mg_http_serve_file(c, hm, "./static/xterm.js", &opts);
} else if (mg_match(hm->uri, mg_str("/xterm.css"), nullptr)) { } else if (mg_match(hm->uri, mg_str("/xterm.css"), nullptr)) {
// xterm.css // xterm.css
struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR};
mg_http_serve_file(c, hm, "./static/xterm.css", &opts); mg_http_serve_file(c, hm, "./static/xterm.css", &opts);
} else if (mg_match(hm->uri, mg_str("/xterm-addon-fit.js"), nullptr)) { } else if (mg_match(hm->uri, mg_str("/xterm-addon-fit.js"), nullptr)) {
// xterm-addon-fit.js // xterm-addon-fit.js
struct mg_http_serve_opts opts = { .root_dir = STATIC_DIR }; struct mg_http_serve_opts opts = {.root_dir = STATIC_DIR};
mg_http_serve_file(c, hm, "./static/xterm-addon-fit.js", &opts); mg_http_serve_file(c, hm, "./static/xterm-addon-fit.js", &opts);
} else { } else {
@@ -185,7 +198,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
printf("WebSocket connection opened\n"); printf("WebSocket connection opened\n");
struct client_data *cd = (struct client_data *)c->fn_data; struct client_data *cd = (struct client_data *)c->fn_data;
if (cd) { if (cd) {
mg_ws_send(c, "Terminal ready - type 'exit' to restart session\r\n", 49, WEBSOCKET_OP_TEXT); mg_ws_send(c, "Terminal ready - type 'exit' to restart session\r\n", 49,
WEBSOCKET_OP_TEXT);
} }
} else if (ev == MG_EV_WS_MSG) { } else if (ev == MG_EV_WS_MSG) {
// Сообщение от WebSocket клиента // Сообщение от WebSocket клиента
@@ -205,7 +219,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
// Проверяем данные от терминала и отправляем через WebSocket // Проверяем данные от терминала и отправляем через WebSocket
struct mg_connection *conn; struct mg_connection *conn;
for (conn = mgr.conns; conn != NULL; conn = conn->next) { for (conn = mgr.conns; conn != NULL; conn = conn->next) {
if (!conn->is_websocket) continue; if (!conn->is_websocket)
continue;
struct client_data *cd = (struct client_data *)conn->fn_data; struct client_data *cd = (struct client_data *)conn->fn_data;
if (cd && cd->terminal_ready) { if (cd && cd->terminal_ready) {
@@ -218,7 +233,8 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
// Читаем данные из терминала // Читаем данные из терминала
char buffer[1024]; char buffer[1024];
ssize_t bytes_read = read_from_terminal(&cd->term, buffer, sizeof(buffer)); ssize_t bytes_read =
read_from_terminal(&cd->term, buffer, sizeof(buffer));
if (bytes_read > 0) { if (bytes_read > 0) {
mg_ws_send(conn, buffer, bytes_read, WEBSOCKET_OP_BINARY); mg_ws_send(conn, buffer, bytes_read, WEBSOCKET_OP_BINARY);
} else if (bytes_read == 0) { } else if (bytes_read == 0) {
@@ -271,7 +287,8 @@ int main(void) {
// Проверяем существование статической директории // Проверяем существование статической директории
if (!directory_exists(STATIC_DIR)) { if (!directory_exists(STATIC_DIR)) {
fprintf(stderr, "Static directory '%s' not found! Creating it...\n", STATIC_DIR); fprintf(stderr, "Static directory '%s' not found! Creating it...\n",
STATIC_DIR);
if (mkdir(STATIC_DIR, 0755) != 0) { if (mkdir(STATIC_DIR, 0755) != 0) {
fprintf(stderr, "Failed to create static directory\n"); fprintf(stderr, "Failed to create static directory\n");
return 1; return 1;
+91 -263
View File
File diff suppressed because it is too large. Load diff
+14 -14
View File
@@ -1,17 +1,18 @@
#include "terminal.h" #include "terminal.h"
#include <errno.h>
#include <fcntl.h>
#include <pty.h>
#include <signal.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <pty.h> #include <unistd.h>
#include <utmp.h> #include <utmp.h>
#include <signal.h>
#include <errno.h>
int create_terminal_session(struct terminal_session *session, const char *shell) { int create_terminal_session(struct terminal_session *session,
const char *shell) {
// Создаем pty // Создаем pty
int master, slave; int master, slave;
char slave_name[64]; char slave_name[64];
@@ -100,7 +101,8 @@ void destroy_terminal_session(struct terminal_session *session) {
printf("Terminal session destroyed\n"); printf("Terminal session destroyed\n");
} }
ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_t size) { ssize_t read_from_terminal(struct terminal_session *session, char *buffer,
size_t size) {
if (!session || !session->active) { if (!session || !session->active) {
return -1; return -1;
} }
@@ -123,7 +125,8 @@ ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_
return bytes_read; return bytes_read;
} }
ssize_t write_to_terminal(struct terminal_session *session, const char *data, size_t size) { ssize_t write_to_terminal(struct terminal_session *session, const char *data,
size_t size) {
if (!session || !session->active) { if (!session || !session->active) {
return -1; return -1;
} }
@@ -137,17 +140,14 @@ ssize_t write_to_terminal(struct terminal_session *session, const char *data, si
return bytes_written; return bytes_written;
} }
int resize_terminal(struct terminal_session *session, uint16_t rows, uint16_t cols) { int resize_terminal(struct terminal_session *session, uint16_t rows,
uint16_t cols) {
if (!session || !session->active) { if (!session || !session->active) {
return -1; return -1;
} }
struct winsize ws = { struct winsize ws = {
.ws_row = rows, .ws_row = rows, .ws_col = cols, .ws_xpixel = 0, .ws_ypixel = 0};
.ws_col = cols,
.ws_xpixel = 0,
.ws_ypixel = 0
};
if (ioctl(session->master_pty, TIOCSWINSZ, &ws) == -1) { if (ioctl(session->master_pty, TIOCSWINSZ, &ws) == -1) {
perror("ioctl TIOCSWINSZ failed"); perror("ioctl TIOCSWINSZ failed");
+10 -6
View File
@@ -1,10 +1,10 @@
#ifndef TERMINAL_H #ifndef TERMINAL_H
#define TERMINAL_H #define TERMINAL_H
#include <signal.h>
#include <stdbool.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include <sys/types.h> #include <sys/types.h>
@@ -16,10 +16,14 @@ struct terminal_session {
}; };
// Функции для работы с терминалом // Функции для работы с терминалом
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); void destroy_terminal_session(struct terminal_session *session);
ssize_t read_from_terminal(struct terminal_session *session, char *buffer, size_t size); ssize_t read_from_terminal(struct terminal_session *session, char *buffer,
ssize_t write_to_terminal(struct terminal_session *session, const char *data, size_t size); size_t size);
int resize_terminal(struct terminal_session *session, uint16_t rows, uint16_t cols); 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 #endif
+53 -34
View File
@@ -1,8 +1,8 @@
<!DOCTYPE html> <!doctype html>
<html> <html>
<head> <head>
<title>Web Terminal</title> <title>Web Terminal</title>
<link rel="stylesheet" href="xterm.css"> <link rel="stylesheet" href="xterm.css" />
<style> <style>
body { body {
margin: 0; margin: 0;
@@ -30,12 +30,18 @@
margin-bottom: 10px; margin-bottom: 10px;
} }
.connected { background-color: #2d5a2d; } .connected {
.disconnected { background-color: #5a2d2d; } background-color: #2d5a2d;
.connecting { background-color: #5a5a2d; } }
.disconnected {
background-color: #5a2d2d;
}
.connecting {
background-color: #5a5a2d;
}
</style> </style>
</head> </head>
<body> <body>
<h1>Web Terminal</h1> <h1>Web Terminal</h1>
<div class="status connecting" id="status">Connecting...</div> <div class="status connecting" id="status">Connecting...</div>
<div id="terminal-container"></div> <div id="terminal-container"></div>
@@ -48,10 +54,10 @@
this.terminal = new Terminal({ this.terminal = new Terminal({
cursorBlink: true, cursorBlink: true,
theme: { theme: {
background: '#000000', background: "#000000",
foreground: '#ffffff', foreground: "#ffffff",
cursor: '#ffffff' cursor: "#ffffff",
} },
}); });
this.fitAddon = new FitAddon.FitAddon(); this.fitAddon = new FitAddon.FitAddon();
@@ -66,12 +72,13 @@
} }
init() { init() {
const terminalContainer = document.getElementById('terminal-container'); const terminalContainer =
document.getElementById("terminal-container");
this.terminal.open(terminalContainer); this.terminal.open(terminalContainer);
this.fitAddon.fit(); this.fitAddon.fit();
this.terminal.writeln('Welcome to Web Terminal'); this.terminal.writeln("Welcome to Web Terminal");
this.terminal.writeln('Connecting to server...'); this.terminal.writeln("Connecting to server...");
this.connect(); this.connect();
@@ -83,13 +90,13 @@
}); });
// Handle resize // Handle resize
window.addEventListener('resize', () => { window.addEventListener("resize", () => {
this.fitAddon.fit(); this.fitAddon.fit();
this.sendResize(); this.sendResize();
}); });
// Handle page unload // Handle page unload
window.addEventListener('beforeunload', () => { window.addEventListener("beforeunload", () => {
if (this.ws) { if (this.ws) {
this.ws.close(); this.ws.close();
} }
@@ -97,23 +104,24 @@
} }
connect() { connect() {
this.updateStatus('Connecting...', 'connecting'); this.updateStatus("Connecting...", "connecting");
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; const protocol =
window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}/ws`; const wsUrl = `${protocol}//${window.location.host}/ws`;
this.ws = new WebSocket(wsUrl); this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => { this.ws.onopen = () => {
console.log('WebSocket connected'); console.log("WebSocket connected");
this.reconnectAttempts = 0; this.reconnectAttempts = 0;
this.updateStatus('Connected', 'connected'); this.updateStatus("Connected", "connected");
this.terminal.clear(); this.terminal.clear();
this.sendResize(); this.sendResize();
}; };
this.ws.onmessage = (event) => { this.ws.onmessage = (event) => {
if (typeof event.data === 'string') { if (typeof event.data === "string") {
this.terminal.write(event.data); this.terminal.write(event.data);
} else { } else {
// Handle binary data // Handle binary data
@@ -127,25 +135,36 @@
}; };
this.ws.onclose = (event) => { this.ws.onclose = (event) => {
console.log('WebSocket disconnected:', event.code, event.reason); console.log(
this.updateStatus('Disconnected', 'disconnected'); "WebSocket disconnected:",
event.code,
event.reason,
);
this.updateStatus("Disconnected", "disconnected");
if (this.reconnectAttempts < this.maxReconnectAttempts) { if (
this.reconnectAttempts < this.maxReconnectAttempts
) {
this.reconnectAttempts++; this.reconnectAttempts++;
const delay = this.reconnectDelay * this.reconnectAttempts; const delay =
this.terminal.write(`\r\nConnection lost. Reconnecting in ${delay/1000}s...\r\n`); this.reconnectDelay * this.reconnectAttempts;
this.terminal.write(
`\r\nConnection lost. Reconnecting in ${delay / 1000}s...\r\n`,
);
setTimeout(() => { setTimeout(() => {
this.connect(); this.connect();
}, delay); }, delay);
} else { } else {
this.terminal.write('\r\nFailed to reconnect. Please refresh the page.\r\n'); this.terminal.write(
"\r\nFailed to reconnect. Please refresh the page.\r\n",
);
} }
}; };
this.ws.onerror = (error) => { this.ws.onerror = (error) => {
console.error('WebSocket error:', error); console.error("WebSocket error:", error);
this.updateStatus('Connection Error', 'disconnected'); this.updateStatus("Connection Error", "disconnected");
}; };
} }
@@ -154,23 +173,23 @@
const dimensions = this.terminal; const dimensions = this.terminal;
const resizeMsg = { const resizeMsg = {
cols: dimensions.cols, cols: dimensions.cols,
rows: dimensions.rows rows: dimensions.rows,
}; };
this.ws.send(JSON.stringify(resizeMsg)); this.ws.send(JSON.stringify(resizeMsg));
} }
} }
updateStatus(text, className) { updateStatus(text, className) {
const status = document.getElementById('status'); const status = document.getElementById("status");
status.textContent = text; status.textContent = text;
status.className = `status ${className}`; status.className = `status ${className}`;
} }
} }
// Initialize terminal when page loads // Initialize terminal when page loads
document.addEventListener('DOMContentLoaded', () => { document.addEventListener("DOMContentLoaded", () => {
new WebTerminal(); new WebTerminal();
}); });
</script> </script>
</body> </body>
</html> </html>
+72 -1
View File
@@ -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})())); !(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 //# sourceMappingURL=xterm-addon-fit.js.map
+34 -12
View File
@@ -79,7 +79,7 @@
.xterm .composition-view { .xterm .composition-view {
/* TODO: Composition position got messed up somewhere */ /* TODO: Composition position got messed up somewhere */
background: #000; background: #000;
color: #FFF; color: #fff;
display: none; display: none;
position: absolute; position: absolute;
white-space: nowrap; white-space: nowrap;
@@ -166,21 +166,41 @@
opacity: 1 !important; opacity: 1 !important;
} }
.xterm-underline-1 { text-decoration: underline; } .xterm-underline-1 {
.xterm-underline-2 { text-decoration: double underline; } text-decoration: underline;
.xterm-underline-3 { text-decoration: wavy underline; } }
.xterm-underline-4 { text-decoration: dotted underline; } .xterm-underline-2 {
.xterm-underline-5 { text-decoration: dashed underline; } 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 { .xterm-overline {
text-decoration: overline; text-decoration: overline;
} }
.xterm-overline.xterm-underline-1 { text-decoration: overline underline; } .xterm-overline.xterm-underline-1 {
.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; } text-decoration: overline 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-2 {
.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; } 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 { .xterm-strikethrough {
text-decoration: line-through; text-decoration: line-through;
@@ -191,7 +211,9 @@
position: absolute; position: absolute;
} }
.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { .xterm-screen
.xterm-decoration-container
.xterm-decoration.xterm-decoration-top-layer {
z-index: 7; z-index: 7;
} }
+14697 -1
View File
File diff suppressed because it is too large. Load diff