repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/routing.rs | crates/openapi/src/routes/routing.rs | #[cfg(feature = "v1")]
/// Routing - Create
///
/// Create a routing config
#[utoipa::path(
post,
path = "/routing",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing config created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v2")]
/// Routing - Create
///
/// Create a routing algorithm
#[utoipa::path(
post,
path = "/v2/routing-algorithms",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v1")]
/// Routing - Activate config
///
/// Activate a routing config
#[utoipa::path(
post,
path = "/routing/{routing_algorithm_id}/activate",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Routing config activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Routing",
operation_id = "Activate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm
#[utoipa::path(
get,
path = "/routing/{routing_algorithm_id}",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Successfully fetched routing config", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v2")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm with its algorithm id
#[utoipa::path(
get,
path = "/v2/routing-algorithms/{id}",
params(
("id" = String, Path, description = "The unique identifier for a routing algorithm"),
),
responses(
(status = 200, description = "Successfully fetched routing algorithm", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing algorithm with its algorithm id",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v1")]
/// Routing - List
///
/// List all routing configs
#[utoipa::path(
get,
path = "/routing",
params(
("limit" = Option<u16>, Query, description = "The number of records to be returned"),
("offset" = Option<u8>, Query, description = "The record offset from which to start gathering of results"),
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully fetched routing configs", body = RoutingKind),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "List routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn list_routing_configs() {}
#[cfg(feature = "v1")]
/// Routing - Deactivate
///
/// Deactivates a routing config
#[utoipa::path(
post,
path = "/routing/deactivate",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Deactivate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v1")]
/// Routing - Update Default Config
///
/// Update default fallback config
#[utoipa::path(
post,
path = "/routing/default",
request_body = Vec<RoutableConnectorChoice>,
responses(
(status = 200, description = "Successfully updated default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Update default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default Config
///
/// Retrieve default fallback config
#[utoipa::path(
get,
path = "/routing/default",
responses(
(status = 200, description = "Successfully retrieved default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Routing",
operation_id = "Retrieve default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Config
///
/// Retrieve active config
#[utoipa::path(
get,
path = "/routing/active",
params(
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve active config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default For Profile
///
/// Retrieve default config for profiles
#[utoipa::path(
get,
path = "/routing/default/profile",
responses(
(status = 200, description = "Successfully retrieved default config", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "Retrieve default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config_for_profiles() {}
#[cfg(feature = "v1")]
/// Routing - Update Default For Profile
///
/// Update default config for profiles
#[utoipa::path(
post,
path = "/routing/default/profile/{profile_id}",
request_body = Vec<RoutableConnectorChoice>,
params(
("profile_id" = String, Path, description = "The unique identifier for a profile"),
),
responses(
(status = 200, description = "Successfully updated default config for profile", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config_for_profile() {}
#[cfg(feature = "v1")]
/// Routing - Toggle success based dynamic routing for profile
///
/// Create a success based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle success based dynamic routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_success_based_routing() {}
#[cfg(feature = "v1")]
/// Routing - Auth Rate Based
///
/// Create a success based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/create",
request_body = SuccessBasedRoutingConfig,
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be created"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create success based dynamic routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn create_success_based_routing() {}
#[cfg(feature = "v1")]
/// Routing - Update success based dynamic routing config for profile
///
/// Update success based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Success based routing algorithm id which was last activated to update the config"),
),
request_body = SuccessBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update success based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn success_based_routing_update_configs() {}
#[cfg(feature = "v1")]
/// Routing - Toggle elimination routing for profile
///
/// Create a elimination based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/elimination/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for elimination based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle elimination routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_elimination_routing() {}
#[cfg(feature = "v1")]
/// Routing - Elimination
///
/// Create a elimination based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/elimination/create",
request_body = EliminationRoutingConfig,
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be created"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for elimination based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create elimination routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn create_elimination_routing() {}
#[cfg(feature = "v1")]
/// Routing - Toggle Contract routing for profile
///
/// Create a Contract based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for contract based routing"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle contract routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_setup_config() {}
#[cfg(feature = "v1")]
/// Routing - Update contract based dynamic routing config for profile
///
/// Update contract based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Contract based routing algorithm id which was last activated to update the config"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update contract based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_update_configs() {}
#[cfg(feature = "v1")]
/// Routing - Evaluate
///
/// Evaluate routing rules
#[utoipa::path(
post,
path = "/routing/evaluate",
request_body = OpenRouterDecideGatewayRequest,
responses(
(status = 200, description = "Routing rules evaluated successfully", body = DecideGatewayResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Evaluate routing rules",
security(("api_key" = []))
)]
pub async fn call_decide_gateway_open_router() {}
#[cfg(feature = "v1")]
/// Routing - Feedback
///
/// Update gateway scores for dynamic routing
#[utoipa::path(
post,
path = "/routing/feedback",
request_body = UpdateScorePayload,
responses(
(status = 200, description = "Gateway score updated successfully", body = UpdateScoreResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update gateway scores",
security(("api_key" = []))
)]
pub async fn call_update_gateway_score_open_router() {}
#[cfg(feature = "v1")]
/// Routing - Rule Evaluate
///
/// Evaluate routing rules
#[utoipa::path(
post,
path = "/routing/rule/evaluate",
request_body = RoutingEvaluateRequest,
responses(
(status = 200, description = "Routing rules evaluated successfully", body = RoutingEvaluateResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Evaluate routing rules (alternative)",
security(("api_key" = []))
)]
pub async fn evaluate_routing_rule() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/webhook_events.rs | crates/openapi/src/routes/webhook_events.rs | /// Events - List
///
/// List all Events associated with a Merchant Account or Profile.
#[utoipa::path(
post,
path = "/events/{merchant_id}",
params(
(
"merchant_id" = String,
Path,
description = "The unique identifier for the Merchant Account."
),
),
request_body(
content = EventListConstraints,
description = "The constraints that can be applied when listing Events.",
examples (
("example" = (
value = json!({
"created_after": "2023-01-01T00:00:00",
"created_before": "2023-01-31T23:59:59",
"limit": 5,
"offset": 0,
"object_id": "{{object_id}}",
"profile_id": "{{profile_id}}",
"event_classes": ["payments", "refunds"],
"event_types": ["payment_succeeded"],
"is_delivered": true
})
)),
)
),
responses(
(status = 200, description = "List of Events retrieved successfully", body = TotalEventsResponse),
),
tag = "Event",
operation_id = "List all Events associated with a Merchant Account or Profile",
security(("admin_api_key" = []))
)]
pub fn list_initial_webhook_delivery_attempts() {}
/// Events - List
///
/// List all Events associated with a Profile.
#[utoipa::path(
post,
path = "/events/profile/list",
request_body(
content = EventListConstraints,
description = "The constraints that can be applied when listing Events.",
examples (
("example" = (
value = json!({
"created_after": "2023-01-01T00:00:00",
"created_before": "2023-01-31T23:59:59",
"limit": 5,
"offset": 0,
"object_id": "{{object_id}}",
"profile_id": "{{profile_id}}",
"event_classes": ["payments", "refunds"],
"event_types": ["payment_succeeded"],
"is_delivered": true
})
)),
)
),
responses(
(status = 200, description = "List of Events retrieved successfully", body = TotalEventsResponse),
),
tag = "Event",
operation_id = "List all Events associated with a Profile",
security(("jwt_key" = []))
)]
pub fn list_initial_webhook_delivery_attempts_with_jwtauth() {}
/// Events - Delivery Attempt List
///
/// List all delivery attempts for the specified Event.
#[utoipa::path(
get,
path = "/events/{merchant_id}/{event_id}/attempts",
params(
("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),
("event_id" = String, Path, description = "The unique identifier for the Event"),
),
responses(
(status = 200, description = "List of delivery attempts retrieved successfully", body = Vec<EventRetrieveResponse>),
),
tag = "Event",
operation_id = "List all delivery attempts for an Event",
security(("admin_api_key" = []))
)]
pub fn list_webhook_delivery_attempts() {}
/// Events - Manual Retry
///
/// Manually retry the delivery of the specified Event.
#[utoipa::path(
post,
path = "/events/{merchant_id}/{event_id}/retry",
params(
("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),
("event_id" = String, Path, description = "The unique identifier for the Event"),
),
responses(
(
status = 200,
description = "The delivery of the Event was attempted. \
Check the `response` field in the response payload to identify the status of the delivery attempt.",
body = EventRetrieveResponse
),
),
tag = "Event",
operation_id = "Manually retry the delivery of an Event",
security(("admin_api_key" = []))
)]
pub fn retry_webhook_delivery_attempt() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/customers.rs | crates/openapi/src/routes/customers.rs | /// Customers - Create
///
/// Creates a customer object and stores the customer details to be reused for future payments.
/// Incase the customer already exists in the system, this API will respond with the customer details.
#[utoipa::path(
post,
path = "/customers",
request_body (
content = CustomerRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
responses(
(status = 200, description = "Customer Created", body = CustomerResponse),
(status = 400, description = "Invalid data")
),
tag = "Customers",
operation_id = "Create a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_create() {}
/// Customers - Retrieve
///
/// Retrieves a customer's details.
#[utoipa::path(
get,
path = "/customers/{customer_id}",
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer Retrieved", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Retrieve a Customer",
security(("api_key" = []), ("ephemeral_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_retrieve() {}
/// Customers - Update
///
/// Updates the customer's details in a customer object.
#[utoipa::path(
post,
path = "/customers/{customer_id}",
request_body (
content = CustomerUpdateRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Updated", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Update a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_update() {}
/// Customers - Delete
///
/// Delete a customer record.
#[utoipa::path(
delete,
path = "/customers/{customer_id}",
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Deleted", body = CustomerDeleteResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Delete a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_delete() {}
/// Customers - List
///
/// Lists all the customers for a particular merchant id.
#[utoipa::path(
get,
path = "/customers/list",
params (("offset" = Option<u32>, Query, description = "Offset for pagination"),
("limit" = Option<u16>, Query, description = "Limit for pagination")),
responses(
(status = 200, description = "Customers retrieved", body = Vec<CustomerResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Customers",
operation_id = "List all Customers for a Merchant",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_list() {}
/// Customers - Create
///
/// Creates a customer object and stores the customer details to be reused for future payments.
/// Incase the customer already exists in the system, this API will respond with the customer details.
#[utoipa::path(
post,
path = "/v2/customers",
request_body (
content = CustomerRequest,
examples (( "Create a customer with name and email" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
responses(
(status = 200, description = "Customer Created", body = CustomerResponse),
(status = 400, description = "Invalid data")
),
tag = "Customers",
operation_id = "Create a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_create() {}
/// Customers - Retrieve
///
/// Retrieves a customer's details.
#[utoipa::path(
get,
path = "/v2/customers/{id}",
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer Retrieved", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Retrieve a Customer",
security(("api_key" = []), ("ephemeral_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_retrieve() {}
/// Customers - Update
///
/// Updates the customer's details in a customer object.
#[utoipa::path(
post,
path = "/v2/customers/{id}",
request_body (
content = CustomerUpdateRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Updated", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Update a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_update() {}
/// Customers - Delete
///
/// Delete a customer record.
#[utoipa::path(
delete,
path = "/v2/customers/{id}",
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Deleted", body = CustomerDeleteResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Delete a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_delete() {}
/// Customers - List
///
/// Lists all the customers for a particular merchant id.
#[utoipa::path(
get,
path = "/v2/customers/list",
responses(
(status = 200, description = "Customers retrieved", body = Vec<CustomerResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Customers",
operation_id = "List all Customers for a Merchant",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_list() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/poll.rs | crates/openapi/src/routes/poll.rs | /// Poll - Retrieve Poll Status
#[utoipa::path(
get,
path = "/poll/status/{poll_id}",
params(
("poll_id" = String, Path, description = "The identifier for poll")
),
responses(
(status = 200, description = "The poll status was retrieved successfully", body = PollResponse),
(status = 404, description = "Poll not found")
),
tag = "Poll",
operation_id = "Retrieve Poll Status",
security(("publishable_key" = []))
)]
pub async fn retrieve_poll_status() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/disputes.rs | crates/openapi/src/routes/disputes.rs | /// Disputes - Retrieve Dispute
/// Retrieves a dispute
#[utoipa::path(
get,
path = "/disputes/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute"),
("force_sync" = Option<bool>, Query, description = "Decider to enable or disable the connector call for dispute retrieve request"),
),
responses(
(status = 200, description = "The dispute was retrieved successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Retrieve a Dispute",
security(("api_key" = []))
)]
pub async fn retrieve_dispute() {}
/// Disputes - List Disputes
/// Lists all the Disputes for a merchant
#[utoipa::path(
get,
path = "/disputes/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes",
security(("api_key" = []))
)]
pub async fn retrieve_disputes_list() {}
/// Disputes - List Disputes for The Given Profiles
/// Lists all the Disputes for a merchant
#[utoipa::path(
get,
path = "/disputes/profile/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes for The given Profiles",
security(("api_key" = []))
)]
pub async fn retrieve_disputes_list_profile() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/revenue_recovery.rs | crates/openapi/src/routes/revenue_recovery.rs | #[cfg(feature = "v2")]
/// Revenue Recovery - Retrieve
///
/// Retrieve the Revenue Recovery Payment Info
#[utoipa::path(
get,
path = "/v2/process-trackers/revenue-recovery-workflow/{revenue_recovery_id}",
params(
("recovery_recovery_id" = String, Path, description = "The payment intent id"),
),
responses(
(status = 200, description = "Revenue Recovery Info Retrieved Successfully", body = RevenueRecoveryResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Revenue Recovery",
operation_id = "Retrieve Revenue Recovery Info",
security(("jwt_key" = []))
)]
pub async fn revenue_recovery_pt_retrieve_api() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/profile_acquirer.rs | crates/openapi/src/routes/profile_acquirer.rs | #[cfg(feature = "v1")]
/// Profile Acquirer - Create
///
/// Create a new Profile Acquirer for accessing our APIs from your servers.
#[utoipa::path(
post,
path = "/profile_acquirers",
request_body = ProfileAcquirerCreate,
responses(
(status = 200, description = "Profile Acquirer created", body = ProfileAcquirerResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile Acquirer",
operation_id = "Create a Profile Acquirer",
security(("api_key" = []))
)]
pub async fn profile_acquirer_create() { /* … */
}
#[cfg(feature = "v1")]
/// Profile Acquirer - Update
///
/// Update a Profile Acquirer for accessing our APIs from your servers.
#[utoipa::path(
post,
path = "/profile_acquirers/{profile_id}/{profile_acquirer_id}",
params (
("profile_id" = String, Path, description = "The unique identifier for the Profile"),
("profile_acquirer_id" = String, Path, description = "The unique identifier for the Profile Acquirer")
),
request_body = ProfileAcquirerUpdate,
responses(
(status = 200, description = "Profile Acquirer updated", body = ProfileAcquirerResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile Acquirer",
operation_id = "Update a Profile Acquirer",
security(("api_key" = []))
)]
pub async fn profile_acquirer_update() { /* … */
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/payment_link.rs | crates/openapi/src/routes/payment_link.rs | /// Payments Link - Retrieve
///
/// To retrieve the properties of a Payment Link. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payment_link/{payment_link_id}",
params(
("payment_link_id" = String, Path, description = "The identifier for payment link"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
),
responses(
(status = 200, description = "Gets details regarding payment link", body = RetrievePaymentLinkResponse),
(status = 404, description = "No payment link found")
),
tag = "Payments",
operation_id = "Retrieve a Payment Link",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn payment_link_retrieve() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/three_ds_decision_rule.rs | crates/openapi/src/routes/three_ds_decision_rule.rs | /// 3DS Decision - Execute
#[utoipa::path(
post,
path = "/three_ds_decision/execute",
request_body = ThreeDsDecisionRuleExecuteRequest,
responses(
(status = 200, description = "3DS Decision Rule Executed Successfully", body = ThreeDsDecisionRuleExecuteResponse),
(status = 400, description = "Bad Request")
),
tag = "3DS Decision Rule",
operation_id = "Execute 3DS Decision Rule",
security(("api_key" = []))
)]
pub fn three_ds_decision_rule_execute() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/platform.rs | crates/openapi/src/routes/platform.rs | #[cfg(feature = "v1")]
/// Platform - Create
///
/// Create a new platform account
#[utoipa::path(
post,
path = "/user/create_platform",
request_body(
content = PlatformAccountCreateRequest,
description = "Create a platform account with organization_name",
examples(
(
"Create a platform account with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
)
)
),
responses(
(
status = 200,
description = "Platform Account Created",
body = PlatformAccountCreateResponse,
examples(
(
"Successful Platform Account Creation" = (
description = "Return values for a successfully created platform account",
value = json!({
"org_id": "org_abc",
"org_name": "organization_abc",
"org_type": "platform",
"merchant_id": "merchant_abc",
"merchant_account_type": "platform"
})
)
)
)
),
(status = 400, description = "Invalid data")
),
tag = "Platform",
operation_id = "Create a Platform Account",
security(("jwt_key" = []))
)]
pub async fn create_platform_account() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/organization.rs | crates/openapi/src/routes/organization.rs | #[cfg(feature = "v1")]
/// Organization - Create
///
/// Create a new organization
#[utoipa::path(
post,
path = "/organization",
request_body(
content = OrganizationCreateRequest,
examples(
(
"Create an organization with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
),
)
),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Create an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_create() {}
#[cfg(feature = "v1")]
/// Organization - Retrieve
///
/// Retrieve an existing organization
#[utoipa::path(
get,
path = "/organization/{id}",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Retrieve an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_retrieve() {}
#[cfg(feature = "v1")]
/// Organization - Update
///
/// Create a new organization for .
#[utoipa::path(
put,
path = "/organization/{id}",
request_body(
content = OrganizationUpdateRequest,
examples(
(
"Update organization_name of the organization" = (
value = json!({"organization_name": "organization_abcd"})
)
),
)
),
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Update an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_update() {}
#[cfg(feature = "v2")]
/// Organization - Create
///
/// Create a new organization
#[utoipa::path(
post,
path = "/v2/organizations",
request_body(
content = OrganizationCreateRequest,
examples(
(
"Create an organization with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
),
)
),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Create an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_create() {}
#[cfg(feature = "v2")]
/// Organization - Retrieve
///
/// Retrieve an existing organization
#[utoipa::path(
get,
path = "/v2/organizations/{id}",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Retrieve an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_retrieve() {}
#[cfg(feature = "v2")]
/// Organization - Update
///
/// Create a new organization for .
#[utoipa::path(
put,
path = "/v2/organizations/{id}",
request_body(
content = OrganizationUpdateRequest,
examples(
(
"Update organization_name of the organization" = (
value = json!({"organization_name": "organization_abcd"})
)
),
)
),
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Update an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_update() {}
#[cfg(feature = "v2")]
/// Organization - Merchant Account - List
///
/// List merchant accounts for an Organization
#[utoipa::path(
get,
path = "/v2/organizations/{id}/merchant-accounts",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Merchant Account list retrieved successfully", body = Vec<MerchantAccountResponse>),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "List Merchant Accounts",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_list() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/merchant_account.rs | crates/openapi/src/routes/merchant_account.rs | #[cfg(feature = "v1")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
#[utoipa::path(
post,
path = "/accounts",
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({"merchant_id": "merchant_abc"})
)
),
(
"Create a merchant account with webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details" : {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
(
"Create a merchant account with return url" = (
value = json!({"merchant_id": "merchant_abc",
"return_url": "https://example.com"})
)
)
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v2")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
///
/// Before creating the merchant account, it is mandatory to create an organization.
#[utoipa::path(
post,
path = "/v2/merchant-accounts",
params(
(
"X-Organization-Id" = String, Header,
description = "Organization ID for which the merchant account has to be created.",
example = json!({"X-Organization-Id": "org_abcdefghijklmnop"})
),
),
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({
"merchant_name": "Cloth Store",
})
)
),
(
"Create a merchant account with merchant details" = (
value = json!({
"merchant_name": "Cloth Store",
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
}
})
)
),
(
"Create a merchant account with metadata" = (
value = json!({
"merchant_name": "Cloth Store",
"metadata": {
"key_1": "John Doe",
"key_2": "Trends"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v1")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn retrieve_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}",
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_retrieve() {}
#[cfg(feature = "v1")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
post,
path = "/accounts/{account_id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details": {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
("Update return url" = (
value = json!({
"merchant_id": "merchant_abc",
"return_url": "https://example.com"
})
)))),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn update_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
put,
path = "/v2/merchant-accounts/{id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update Merchant Details" = (
value = json!({
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
}
})
)
),
)),
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_update() {}
#[cfg(feature = "v1")]
/// Merchant Account - Delete
///
/// Delete a *merchant* account
#[utoipa::path(
delete,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Deleted", body = MerchantAccountDeleteResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Delete a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn delete_merchant_account() {}
#[cfg(feature = "v1")]
/// Merchant Account - KV Status
///
/// Toggle KV mode for the Merchant Account
#[utoipa::path(
post,
path = "/accounts/{account_id}/kv",
request_body (
content = ToggleKVRequest,
examples (
("Enable KV for Merchant" = (
value = json!({
"kv_enabled": "true"
})
)),
("Disable KV for Merchant" = (
value = json!({
"kv_enabled": "false"
})
)))
),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "KV mode is enabled/disabled for Merchant Account", body = ToggleKVResponse),
(status = 400, description = "Invalid data"),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Enable/Disable KV for a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_kv_status() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/accounts/{account_id}/profile/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors for The given Profile",
security(("admin_api_key" = []))
)]
pub async fn payment_connector_list_profile() {}
#[cfg(feature = "v2")]
/// Merchant Account - Profile List
///
/// List profiles for an Merchant
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}/profiles",
params (("id" = String, Path, description = "The unique identifier for the Merchant")),
responses(
(status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "List Profiles",
security(("admin_api_key" = []))
)]
pub async fn profiles_list() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/relay.rs | crates/openapi/src/routes/relay.rs | /// Relay - Create
///
/// Creates a relay request.
#[utoipa::path(
post,
path = "/relay",
request_body(
content = RelayRequest,
examples((
"Create a relay request" = (
value = json!({
"connector_resource_id": "7256228702616471803954",
"connector_id": "mca_5apGeP94tMts6rg3U3kR",
"type": "refund",
"data": {
"refund": {
"amount": 6540,
"currency": "USD"
}
}
})
)
))
),
responses(
(status = 200, description = "Relay request", body = RelayResponse),
(status = 400, description = "Invalid data")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
("X-Idempotency-Key" = String, Header, description = "Idempotency Key for relay request")
),
tag = "Relay",
operation_id = "Relay Request",
security(("api_key" = []))
)]
pub async fn relay() {}
/// Relay - Retrieve
///
/// Retrieves a relay details.
#[utoipa::path(
get,
path = "/relay/{relay_id}",
params (("relay_id" = String, Path, description = "The unique identifier for the Relay"), ("X-Profile-Id" = String, Header, description = "Profile ID for authentication")),
responses(
(status = 200, description = "Relay Retrieved", body = RelayResponse),
(status = 404, description = "Relay details was not found")
),
tag = "Relay",
operation_id = "Retrieve a Relay details",
security(("api_key" = []), ("ephemeral_key" = []))
)]
pub async fn relay_retrieve() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/merchant_connector_account.rs | crates/openapi/src/routes/merchant_connector_account.rs | /// Merchant Connector - Create
///
/// Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/account/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account")
),
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_create() {}
/// Connector Account - Create
///
/// Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/connector-accounts",
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_create() {}
/// Merchant Connector - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Connector Account - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/account/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorListResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors",
security(("api_key" = []))
)]
pub async fn connector_list() {}
/// Merchant Connector - Update
///
/// To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_update() {}
/// Connector Account - Update
///
/// To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/connector-accounts/{id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_update() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v1")]
#[utoipa::path(
delete,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/payment_method.rs | crates/openapi/src/routes/payment_method.rs | /// PaymentMethods - Create
///
/// Creates and stores a payment method against a customer.
/// In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/payment_methods",
request_body (
content = PaymentMethodCreate,
examples (( "Save a card" =(
value =json!( {
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "25",
"card_holder_name": "John Doe"
},
"customer_id": "{{customer_id}}"
})
)))
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data")
),
tag = "Payment Methods",
operation_id = "Create a Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn create_payment_method_api() {}
/// List payment methods for a Merchant
///
/// Lists the applicable payment methods for a particular Merchant ID.
/// Use the client secret and publishable key authorization to list all relevant payment methods of the merchant for the payment corresponding to the client secret.
#[utoipa::path(
get,
path = "/account/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = PaymentMethodListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Merchant",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn list_payment_method_api() {}
/// List payment methods for a Customer
///
/// Lists all the applicable payment methods for a particular Customer ID.
#[utoipa::path(
get,
path = "/customers/{customer_id}/payment_methods",
params (
("customer_id" = String, Path, description = "The unique identifier for the customer account"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn list_customer_payment_method_api() {}
/// List customer saved payment methods for a Payment
///
/// Lists all the applicable payment methods for a particular payment tied to the `client_secret`.
#[utoipa::path(
get,
path = "/customers/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List Customer Payment Methods via Client Secret",
security(("publishable_key" = []))
)]
pub async fn list_customer_payment_method_api_client() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Retrieve a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
/// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.
#[utoipa::path(
post,
path = "/payment_methods/{method_id}/update",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
request_body = PaymentMethodUpdate,
responses(
(status = 200, description = "Payment Method updated", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Update a Payment method",
security(("api_key" = []), ("publishable_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method deleted", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Delete a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Set Default Payment Method for Customer
///
/// Set the Payment Method as Default for the Customer.
#[utoipa::path(
post,
path = "/{customer_id}/payment_methods/{payment_method_id}/default",
params (
("customer_id" = String,Path, description ="The unique identifier for the Customer"),
("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
(status = 400, description = "Payment Method has already been set as default for that customer"),
(status = 404, description = "Payment Method not found for the customer")
),
tag = "Payment Methods",
operation_id = "Set the Payment Method as Default",
security(("ephemeral_key" = []))
)]
pub async fn default_payment_method_set_api() {}
/// Payment Method - Create Intent
///
/// Creates a payment method for customer with billing information and other metadata.
#[utoipa::path(
post,
path = "/v2/payment-methods/create-intent",
request_body(
content = PaymentMethodIntentCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_intent_api() {}
/// Payment Method - Confirm Intent
///
/// Update a payment method with customer's payment method related information.
#[utoipa::path(
post,
path = "/v2/payment-methods/{id}/confirm-intent",
request_body(
content = PaymentMethodIntentConfirm,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Confirm Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn confirm_payment_method_intent_api() {}
/// Payment Method - Create
///
/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/v2/payment-methods",
request_body(
content = PaymentMethodCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_api() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Retrieve Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
#[utoipa::path(
patch,
path = "/v2/payment-methods/{id}/update-saved-payment-method",
request_body(
content = PaymentMethodUpdate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Update", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Update Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Delete Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Check Network Token Status
///
/// Check the status of a network token for a saved payment method
#[utoipa::path(
get,
path = "/v2/payment-methods/{payment_method_id}/check-network-token-status",
params (
("payment_method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Network Token Status Retrieved", body = NetworkTokenStatusCheckResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Check Network Token Status",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn network_token_status_check_api() {}
/// Payment Method - List Customer Saved Payment Methods
///
/// List the payment methods saved for a customer
#[utoipa::path(
get,
path = "/v2/customers/{id}/saved-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the customer"),
),
responses(
(status = 200, description = "Payment Methods Retrieved", body = CustomerPaymentMethodsListResponse),
(status = 404, description = "Customer Not Found"),
),
tag = "Payment Methods",
operation_id = "List Customer Saved Payment Methods",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn list_customer_payment_method_api() {}
/// Payment Method Session - Create
///
/// Create a payment method session for a customer
/// This is used to list the saved payment methods for the customer
/// The customer can also add a new payment method using this session
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/payment-method-sessions",
request_body(
content = PaymentMethodSessionRequest,
examples (( "Create a payment method session with customer_id" = (
value =json!( {
"customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz"
})
)))
),
responses(
(status = 200, description = "Create the payment method session", body = PaymentMethodSessionResponse),
(status = 400, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Create a payment method session",
security(("api_key" = []))
)]
pub fn payment_method_session_create() {}
/// Payment Method Session - Retrieve
///
/// Retrieve the payment method session
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodSessionResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Retrieve the payment method session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_retrieve() {}
/// Payment Method Session - List Payment Methods
///
/// List payment methods for the given payment method session.
/// This endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer.
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}/list-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponseForSession),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "List Payment methods for a Payment Method Session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_list_payment_methods() {}
/// Payment Method Session - Update a saved payment method
///
/// Update a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/payment-method-sessions/{id}/update-saved-payment-method",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionUpdateSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
"payment_method_data": {
"card": {
"card_holder_name": "Narayan Bhat"
}
}
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Update a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_update_saved_payment_method() {}
/// Payment Method Session - Delete a saved payment method
///
/// Delete a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionDeleteSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodDeleteResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Delete a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_delete_saved_payment_method() {}
/// Card network tokenization - Create using raw card data
///
/// Create a card network token for a customer and store it as a payment method.
/// This API expects raw card details for creating a network token with the card networks.
#[utoipa::path(
post,
path = "/payment_methods/tokenize-card",
request_body = CardNetworkTokenizeRequest,
responses(
(status = 200, description = "Payment Method Created", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_api() {}
/// Card network tokenization - Create using existing payment method
///
/// Create a card network token for a customer for an existing payment method.
/// This API expects an existing payment method ID for a card.
#[utoipa::path(
post,
path = "/payment_methods/{id}/tokenize-card",
request_body = CardNetworkTokenizeRequest,
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Updated", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token using Payment Method ID",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_using_pm_api() {}
/// Payment Method Session - Confirm a payment method session
///
/// **Confirms a payment method session object with the payment method data**
#[utoipa::path(
post,
path = "/v2/payment-method-sessions/{id}/confirm",
params (("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentMethodSessionConfirmRequest,
examples(
(
"Confirm the payment method session with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment Method created", body = PaymentMethodResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payment Method Session",
operation_id = "Confirm the payment method session",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payment_method_session_confirm() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/payouts.rs | crates/openapi/src/routes/payouts.rs | /// Payouts - Create
#[utoipa::path(
post,
path = "/payouts/create",
request_body=PayoutsCreateRequest,
responses(
(status = 200, description = "Payout created", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Create a Payout",
security(("api_key" = []))
)]
pub async fn payouts_create() {}
/// Payouts - Retrieve
#[utoipa::path(
get,
path = "/payouts/{payout_id}",
params(
("payout_id" = String, Path, description = "The identifier for payout"),
("force_sync" = Option<bool>, Query, description = "Sync with the connector to get the payout details (defaults to false)")
),
responses(
(status = 200, description = "Payout retrieved", body = PayoutCreateResponse),
(status = 404, description = "Payout does not exist in our records")
),
tag = "Payouts",
operation_id = "Retrieve a Payout",
security(("api_key" = []))
)]
pub async fn payouts_retrieve() {}
/// Payouts - Update
#[utoipa::path(
post,
path = "/payouts/{payout_id}",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutUpdateRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Update a Payout",
security(("api_key" = []))
)]
pub async fn payouts_update() {}
/// Payouts - Cancel
#[utoipa::path(
post,
path = "/payouts/{payout_id}/cancel",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutCancelRequest,
responses(
(status = 200, description = "Payout cancelled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Cancel a Payout",
security(("api_key" = []))
)]
pub async fn payouts_cancel() {}
/// Payouts - Fulfill
#[utoipa::path(
post,
path = "/payouts/{payout_id}/fulfill",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutFulfillRequest,
responses(
(status = 200, description = "Payout fulfilled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Fulfill a Payout",
security(("api_key" = []))
)]
pub async fn payouts_fulfill() {}
/// Payouts - List
#[utoipa::path(
get,
path = "/payouts/list",
params(
("customer_id" = String, Query, description = "The identifier for customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = String, Query, description = "limit on the number of objects to return"),
("created" = String, Query, description = "The time at which payout is created"),
("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
),
responses(
(status = 200, description = "Payouts listed", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "List payouts using generic constraints",
security(("api_key" = []))
)]
pub async fn payouts_list() {}
/// Payouts - List for the Given Profiles
#[utoipa::path(
get,
path = "/payouts/profile/list",
params(
("customer_id" = String, Query, description = "The identifier for customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = String, Query, description = "limit on the number of objects to return"),
("created" = String, Query, description = "The time at which payout is created"),
("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
),
responses(
(status = 200, description = "Payouts listed", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "List payouts using generic constraints for the given Profiles",
security(("api_key" = []))
)]
pub async fn payouts_list_profile() {}
/// Payouts - List available filters
#[utoipa::path(
post,
path = "/payouts/filter",
request_body=TimeRange,
responses(
(status = 200, description = "Filters listed", body = PayoutListFilters)
),
tag = "Payouts",
operation_id = "List available payout filters",
security(("api_key" = []))
)]
pub async fn payouts_list_filters() {}
/// Payouts - List using filters
#[utoipa::path(
post,
path = "/payouts/list",
request_body=PayoutListFilterConstraints,
responses(
(status = 200, description = "Payouts filtered", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "Filter payouts using specific constraints",
security(("api_key" = []))
)]
pub async fn payouts_list_by_filter() {}
/// Payouts - List using filters for the given Profiles
#[utoipa::path(
post,
path = "/payouts/list",
request_body=PayoutListFilterConstraints,
responses(
(status = 200, description = "Payouts filtered", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "Filter payouts using specific constraints for the given Profiles",
security(("api_key" = []))
)]
pub async fn payouts_list_by_filter_profile() {}
/// Payouts - Confirm
#[utoipa::path(
post,
path = "/payouts/{payout_id}/confirm",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutConfirmRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Confirm a Payout",
security(("api_key" = []))
)]
pub async fn payouts_confirm() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/gsm.rs | crates/openapi/src/routes/gsm.rs | /// Gsm - Create
///
/// Creates a GSM (Global Status Mapping) Rule. A GSM rule is used to map a connector's error message/error code combination during a particular payments flow/sub-flow to Hyperswitch's unified status/error code/error message combination. It is also used to decide the next action in the flow - retry/requeue/do_default
#[utoipa::path(
post,
path = "/gsm",
request_body(
content = GsmCreateRequest,
),
responses(
(status = 200, description = "Gsm created", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Create Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn create_gsm_rule() {}
/// Gsm - Get
///
/// Retrieves a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/get",
request_body(
content = GsmRetrieveRequest,
),
responses(
(status = 200, description = "Gsm retrieved", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Retrieve Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn get_gsm_rule() {}
/// Gsm - Update
///
/// Updates a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/update",
request_body(
content = GsmUpdateRequest,
),
responses(
(status = 200, description = "Gsm updated", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Update Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn update_gsm_rule() {}
/// Gsm - Delete
///
/// Deletes a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/delete",
request_body(
content = GsmDeleteRequest,
),
responses(
(status = 200, description = "Gsm deleted", body = GsmDeleteResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Delete Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn delete_gsm_rule() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/subscriptions.rs | crates/openapi/src/routes/subscriptions.rs | use serde_json::json;
/// Subscription - Create and Confirm
///
/// Creates and confirms a subscription in a single request.
#[utoipa::path(
post,
path = "/subscriptions",
request_body(
content = CreateAndConfirmSubscriptionRequest,
examples((
"Create and confirm subscription" = (
value = json!({
"item_price_id": "standard-plan-USD-Monthly",
"customer_id": "cust_123456789",
"description": "Hello this is description",
"merchant_reference_id": "mer_ref_123456789",
"shipping": {
"address": {
"state": "zsaasdas",
"city": "Banglore",
"country": "US",
"line1": "sdsdfsdf",
"line2": "hsgdbhd",
"line3": "alsksoe",
"zip": "571201",
"first_name": "joseph",
"last_name": "doe"
},
"phone": {
"number": "123456789",
"country_code": "+1"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "123456789",
"country_code": "+1"
}
},
"payment_details": {
"payment_type": "setup_mandate",
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4000000000000002",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "CLBRW dffdg",
"card_cvc": "737"
}
},
"authentication_type": "no_three_ds",
"setup_future_usage": "off_session",
"capture_method": "automatic",
"return_url": "https://google.com",
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
}
})
)
))
),
responses(
(status = 200, description = "Subscription created and confirmed successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid subscription data"),
(status = 404, description = "Customer or plan not found")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
tag = "Subscriptions",
operation_id = "Create and Confirm Subscription",
security(("api_key" = []))
)]
pub async fn create_and_confirm_subscription() {}
/// Subscription - Create
///
/// Creates a subscription that requires separate confirmation.
#[utoipa::path(
post,
path = "/subscriptions/create",
request_body(
content = CreateSubscriptionRequest,
examples((
"Create subscription" = (
value = json!({
"customer_id": "cust_123456789",
"item_price_id": "standard-plan-USD-Monthly",
"payment_details": {
"authentication_type": "no_three_ds",
"setup_future_usage": "off_session",
"capture_method": "automatic",
"return_url": "https://google.com"
}
})
)
))
),
responses(
(status = 200, description = "Subscription created successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid subscription data"),
(status = 404, description = "Customer or plan not found")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
tag = "Subscriptions",
operation_id = "Create Subscription",
security(("api_key" = []))
)]
pub async fn create_subscription() {}
/// Subscription - Confirm
///
/// Confirms a previously created subscription.
#[utoipa::path(
post,
path = "/subscriptions/{subscription_id}/confirm",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
request_body(
content = ConfirmSubscriptionRequest,
examples((
"Confirm subscription" = (
value = json!({
"payment_details": {
"shipping": {
"address": {
"state": "zsaasdas",
"city": "Banglore",
"country": "US",
"line1": "sdsdfsdf",
"line2": "hsgdbhd",
"line3": "alsksoe",
"zip": "571201",
"first_name": "joseph",
"last_name": "doe"
},
"phone": {
"number": "123456789",
"country_code": "+1"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "123456789",
"country_code": "+1"
}
},
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4111111111111111",
"card_exp_month": "03",
"card_exp_year": "2030",
"card_holder_name": "CLBRW dffdg",
"card_cvc": "737"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
}
})
)
))
),
responses(
(status = 200, description = "Subscription confirmed successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid confirmation data"),
(status = 404, description = "Subscription not found"),
(status = 409, description = "Subscription already confirmed")
),
tag = "Subscriptions",
operation_id = "Confirm Subscription",
security(("api_key" = []), ("client_secret" = []))
)]
pub async fn confirm_subscription() {}
/// Subscription - Retrieve
///
/// Retrieves subscription details by ID.
#[utoipa::path(
get,
path = "/subscriptions/{subscription_id}",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
responses(
(status = 200, description = "Subscription retrieved successfully", body = SubscriptionResponse),
(status = 404, description = "Subscription not found")
),
tag = "Subscriptions",
operation_id = "Retrieve Subscription",
security(("api_key" = []))
)]
pub async fn get_subscription() {}
/// Subscription - Update
///
/// Updates an existing subscription.
#[utoipa::path(
put,
path = "/subscriptions/{subscription_id}/update",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
request_body(
content = UpdateSubscriptionRequest,
examples((
"Update subscription" = (
value = json!({
"plan_id":"cbdemo_enterprise-suite",
"item_price_id":"cbdemo_enterprise-suite-monthly"
})
)
))
),
responses(
(status = 200, description = "Subscription updated successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid update data"),
(status = 404, description = "Subscription not found")
),
tag = "Subscriptions",
operation_id = "Update Subscription",
security(("api_key" = []))
)]
pub async fn update_subscription() {}
/// Subscription - Get Items
///
/// Retrieves available subscription items.
#[utoipa::path(
get,
path = "/subscriptions/items",
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
("limit" = Option<u32>, Query, description = "Number of items to retrieve"),
("offset" = Option<u32>, Query, description = "Number of items to skip"),
("product_id" = Option<String>, Query, description = "Filter by product ID"),
("item_type" = SubscriptionItemType, Query, description = "Filter by subscription item type plan or addon")
),
responses(
(status = 200, description = "List of available subscription items", body = Vec<GetSubscriptionItemsResponse>),
(status = 400, description = "Invalid query parameters")
),
tag = "Subscriptions",
operation_id = "Get Subscription Items",
security(("api_key" = []), ("client_secret" = []))
)]
pub async fn get_subscription_items() {}
/// Subscription - Get Estimate
///
/// Gets pricing estimate for a subscription.
#[utoipa::path(
get,
path = "/subscriptions/estimate",
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
("plan_id" = String, Query, description = "Plan ID for estimation"),
("customer_id" = Option<String>, Query, description = "Customer ID for personalized pricing"),
("coupon_id" = Option<String>, Query, description = "Coupon ID to apply discount"),
("trial_days" = Option<u32>, Query, description = "Number of trial days")
),
responses(
(status = 200, description = "Estimate retrieved successfully", body = EstimateSubscriptionResponse),
(status = 400, description = "Invalid estimation parameters"),
(status = 404, description = "Plan not found")
),
tag = "Subscriptions",
operation_id = "Get Subscription Estimate",
security(("api_key" = []))
)]
pub async fn get_estimate() {}
/// Subscription - Pause Subscription
///
/// Pause the subscription
#[utoipa::path(
post,
path = "/subscriptions/{subscription_id}/pause",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
request_body(
content = PauseSubscriptionRequest,
examples((
"Pause subscription" = (
value = json!({
"pause_option": "immediately"
})
)
))
),
responses(
(status = 200, description = "Subscription paused successfully", body = PauseSubscriptionResponse),
(status = 400, description = "Invalid pause data"),
(status = 404, description = "Subscription not found")
),
tag = "Subscriptions",
operation_id = "Pause Subscription",
security(("api_key" = []))
)]
pub async fn pause_subscription() {}
/// Subscription - Resume Subscription
///
/// Resume the subscription
#[utoipa::path(
post,
path = "/subscriptions/{subscription_id}/resume",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
request_body(
content = ResumeSubscriptionRequest,
examples((
"Resume subscription" = (
value = json!({
"resume_option": "immediately",
"unpaid_invoices_handling": "schedule_payment_collection"
})
)
))
),
responses(
(status = 200, description = "Subscription resumed successfully", body = ResumeSubscriptionResponse),
(status = 400, description = "Invalid resume data"),
(status = 404, description = "Subscription not found")
),
tag = "Subscriptions",
operation_id = "Resume Subscription",
security(("api_key" = []))
)]
pub async fn resume_subscription() {}
/// Subscription - Cancel Subscription
///
/// Cancel the subscription
#[utoipa::path(
post,
path = "/subscriptions/{subscription_id}/cancel",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
request_body(
content = CancelSubscriptionRequest,
examples((
"Cancel subscription" = (
value = json!({
"cancel_option": "immediately",
"unbilled_charges_option": "invoice",
"credit_option_for_current_term_charges": "prorate",
"refundable_credits_handling": "schedule_refund"
})
)
))
),
responses(
(status = 200, description = "Subscription cancelled successfully", body = CancelSubscriptionResponse),
(status = 400, description = "Invalid cancel data"),
(status = 404, description = "Subscription not found")
),
tag = "Subscriptions",
operation_id = "Cancel Subscription",
security(("api_key" = []))
)]
pub async fn cancel_subscription() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/authentication.rs | crates/openapi/src/routes/authentication.rs | /// Authentication - Create
///
/// Create a new authentication for accessing our APIs from your servers.
///
#[utoipa::path(
post,
path = "/authentication",
request_body = AuthenticationCreateRequest,
responses(
(status = 200, description = "Authentication created", body = AuthenticationResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Create an Authentication",
security(("api_key" = []))
)]
pub async fn authentication_create() {}
/// Authentication - Eligibility
///
/// Check if an authentication is eligible for a specific merchant.
///
#[utoipa::path(
post,
path = "/authentication/{authentication_id}/eligibility",
request_body = AuthenticationEligibilityRequest,
responses(
(status = 200, description = "Authentication eligibility checked", body = AuthenticationEligibilityResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Check Authentication Eligibility",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn authentication_eligibility() {}
/// Authentication - Authenticate
///
/// Authenticate an authentication for accessing our APIs from your servers.
///
#[utoipa::path(
post,
path = "/authentication/{authentication_id}/authenticate",
request_body = AuthenticationAuthenticateRequest,
responses(
(status = 200, description = "Authentication authenticated", body = AuthenticationAuthenticateResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Authenticate an Authentication",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn authentication_authenticate() {}
/// Authentication - Redirect
///
/// Redirect an authentication for accessing our APIs from your servers.
///
#[utoipa::path(
post,
path = "/authentication/{authentication_id}/redirect",
request_body = AuthenticationSyncPostUpdateRequest,
responses(
(status = 200, description = "Authentication redirect"),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Redirect an Authentication",
security()
)]
pub async fn authentication_redirect() {}
/// Authentication - Sync
///
/// Sync an authentication for accessing our APIs from your servers.
///
#[utoipa::path(
post,
path = "/authentication/{authentication_id}/sync",
request_body = AuthenticationSyncRequest,
responses(
(status = 200, description = "Authentication sync", body = AuthenticationSyncResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Sync an Authentication",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn authentication_sync() {}
/// Authentication - Enable Authn Methods Token
///
/// Enable authn methods token for an authentication.
///
#[utoipa::path(
post,
path = "/authentication/{authentication_id}/enabled_authn_methods_token",
request_body = AuthenticationSessionTokenRequest,
responses(
(status = 200, description = "Authentication enabled authn methods token", body = AuthenticationSessionResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Enable Authentication Authn Methods Token",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn authentication_enabled_authn_methods_token() {}
/// Authentication - POST Eligibility Check
///
#[utoipa::path(
post,
path = "/authentication/{authentication_id}/eligibility-check",
request_body = AuthenticationEligibilityCheckRequest,
responses(
(status = 200, description = "Eligibility Performed for the Authentication", body = AuthenticationEligibilityCheckResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Submit Eligibility for an Authentication",
security(("publishable_key" = []))
)]
pub async fn authentication_eligibility_check() {}
/// Authentication - GET Eligibility Check
///
#[utoipa::path(
get,
path = "/authentication/{authentication_id}/eligibility-check",
request_body = AuthenticationRetrieveEligibilityCheckRequest,
responses(
(status = 200, description = "Retrieved Eligibility check data for the Authentication", body = AuthenticationRetrieveEligibilityCheckResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Retrieve Eligibility Check data for an Authentication",
security(("api_key" = []))
)]
pub async fn authentication_retrieve_eligibility_check() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/proxy.rs | crates/openapi/src/routes/proxy.rs | #[cfg(feature = "v2")]
///Proxy
///
/// Create a proxy request
#[utoipa::path(
post,
path = "/proxy",
request_body(
content = ProxyRequest,
examples((
"Create a proxy request" = (
value = json!({
"request_body": {
"source": {
"type": "card",
"number": "{{$card_number}}",
"expiry_month": "{{$card_exp_month}}",
"expiry_year": "{{$card_exp_year}}",
"billing_address": {
"address_line1": "123 High St.",
"city": "London",
"country": "GB"
}
},
"amount": 6540,
"currency": "USD",
"reference": "ORD-5023-4E89",
"capture": true
},
"destination_url": "https://api.example.com/payments",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer sk_test_example"
},
"token": "pm_0196ea5a42a67583863d5b1253d62931",
"token_type": "PaymentMethodId",
"method": "POST"
})
)
))
),
responses(
(status = 200, description = "Proxy request", body = ProxyResponse),
(status = 400, description = "Invalid data")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
),
tag = "Proxy",
operation_id = "Proxy Request",
security(("api_key" = []))
)]
pub async fn proxy_core() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/payments.rs | crates/openapi/src/routes/payments.rs | /// Payments - Create
///
/// Creates a payment resource, which represents a customer's intent to pay.
/// This endpoint is the starting point for various payment flows:
///
#[utoipa::path(
post,
path = "/payments",
request_body(
content = PaymentsCreateRequest,
examples(
(
"01. Create a payment with minimal fields" = (
value = json!({"amount": 6540,"currency": "USD"})
)
),
(
"02. Create a payment with customer details and metadata" = (
value = json!({
"amount": 6540,
"currency": "USD",
"payment_id": "abcdefghijklmnopqrstuvwxyz",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"phone": "9123456789",
"email": "john@example.com"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
}
})
)
),
(
"03. Create a 3DS payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds"
})
)
),
(
"04. Create a manual capture payment (basic)" = (
value = json!({
"amount": 6540,
"currency": "USD",
"capture_method": "manual"
})
)
),
(
"05. Create a setup mandate payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 6540,
"currency": "USD"
}
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
})
)
),
(
"06. Create a recurring payment with mandate_id" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"authentication_type": "no_three_ds",
"mandate_id": "{{mandate_id}}",
"off_session": true
})
)
),
(
"07. Create a payment and save the card" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session"
})
)
),
(
"08. Create a payment using an already saved card's token" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"client_secret": "{{client_secret}}",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"card_cvc": "123"
})
)
),
(
"09. Create a payment with billing details" = (
value = json!({
"amount": 6540,
"currency": "USD",
"customer": {
"id": "cus_abcdefgh"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
}
})
)
),
(
"10. Create a Stripe Split Payments CIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"confirm": true,
"capture_method": "automatic",
"amount_to_capture": 200,
"customer_id": "StripeCustomer123",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"authentication_type": "no_three_ds",
"return_url": "https://hyperswitch.io",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "09",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9999999999",
"country_code": "+91"
}
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 100,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
(
"11. Create a Stripe Split Payments MIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"customer_id": "StripeCustomer123",
"description": "Subsequent Mandate Test Payment (MIT from New CIT Demo)",
"confirm": true,
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_123456789"
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 11,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi,
examples(
("01. Response for minimal payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_syxxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"client_secret": "pay_syxxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:00:00Z",
"amount_capturable": 6540,
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:15:00Z"
})
)),
("02. Response for payment with customer details (requires payment method)" = (
value = json!({
"payment_id": "pay_custmeta_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
},
"client_secret": "pay_custmeta_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:05:00Z",
"ephemeral_key": {
"customer_id": "cus_abcdefgh",
"secret": "epk_ephemeralxxxxxxxxxxxx"
},
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:20:00Z"
})
)),
("03. Response for 3DS payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_3ds_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds",
"client_secret": "pay_3ds_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:10:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:25:00Z"
})
)),
("04. Response for basic manual capture payment (requires payment method)" = (
value = json!({
"payment_id": "pay_manualcap_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"capture_method": "manual",
"client_secret": "pay_manualcap_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:15:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:30:00Z"
})
)),
("05. Response for successful setup mandate payment" = (
value = json!({
"payment_id": "pay_mandatesetup_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"mandate_id": "man_xxxxxxxxxxxx",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" }
},
"mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } }
},
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_mandatesetup_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:20:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("06. Response for successful recurring payment with mandate_id" = (
value = json!({
"payment_id": "pay_recurring_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer",
"mandate_id": "{{mandate_id}}",
"off_session": true,
"payment_method": "card",
"authentication_type": "no_three_ds",
"client_secret": "pay_recurring_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:22:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("07. Response for successful payment with card saved" = (
value = json!({
"payment_id": "pay_savecard_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_savecard_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:25:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx",
"payment_token": null // Assuming payment_token is for subsequent use, not in this response.
})
)),
("08. Response for successful payment using saved card token" = (
value = json!({
"payment_id": "pay_token_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"client_secret": "pay_token_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:27:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("09. Response for payment with billing details (requires payment method)" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("10. Response for the CIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("11. Response for the MIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
))
)
),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi),
),
tag = "Payments",
operation_id = "Create a Payment",
security(("api_key" = [])),
)]
pub fn payments_create() {}
/// Payments - Retrieve
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment"),
("force_sync" = Option<bool>, Query, description = "Decider to enable or disable the connector call for retrieve request"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("expand_attempts" = Option<bool>, Query, description = "If enabled provides list of attempts linked to payment intent"),
("expand_captures" = Option<bool>, Query, description = "If enabled provides list of captures linked to latest attempt"),
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_retrieve() {}
/// Payments - Update
///
/// To update the properties of a *PaymentIntent* object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created
#[utoipa::path(
post,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsUpdateRequest,
examples(
(
"Update the payment amount" = (
value = json!({
"amount": 7654,
}
)
)
),
(
"Update the shipping address" = (
value = json!(
{
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
},
}
)
)
)
)
),
responses(
(status = 200, description = "Payment updated", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Update a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_update() {}
/// Payments - Confirm
///
/// Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor.
///
/// Expected status transitions after confirmation:
/// - `succeeded`: If authorization is successful and `capture_method` is `automatic`.
/// - `requires_capture`: If authorization is successful and `capture_method` is `manual`.
/// - `failed`: If authorization fails.
#[utoipa::path(
post,
path = "/payments/{payment_id}/confirm",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsConfirmRequest,
examples(
(
"Confirm a payment with payment method data" = (
value = json!({
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
}
)
)
)
)
),
responses(
(status = 200, description = "Payment confirmed", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Confirm a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_confirm() {}
/// Payments - Capture
///
/// Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state.
///
/// Upon successful capture, the payment status usually transitions to `succeeded`.
/// The `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.
///
/// A payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.
///
#[utoipa::path(
post,
path = "/payments/{payment_id}/capture",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body (
content = PaymentsCaptureRequest,
examples(
(
"Capture the full amount" = (
value = json!({})
)
),
(
"Capture partial amount" = (
value = json!({"amount_to_capture": 654})
)
),
)
),
responses(
(status = 200, description = "Payment captured", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Capture a Payment",
security(("api_key" = []))
)]
pub fn payments_capture() {}
#[cfg(feature = "v1")]
/// Payments - Session token
///
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/profile.rs | crates/openapi/src/routes/profile.rs | // ******************************************** V1 profile routes ******************************************** //
#[cfg(feature = "v1")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "The unique identifier for the merchant account")
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with minimal fields" = (
value = json!({})
)
),
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Profile Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v1")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v1")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("api_key" = []))
)]
pub async fn profile_retrieve() {}
// ******************************************** Common profile routes ******************************************** //
/// Profile - Delete
///
/// Delete the *profile*
#[utoipa::path(
delete,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profiles Deleted", body = bool),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Delete the Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_delete() {}
/// Profile - List
///
/// Lists all the *profiles* under a merchant
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "Merchant Identifier"),
),
responses(
(status = 200, description = "Profiles Retrieved", body = Vec<ProfileResponse>)
),
tag = "Profile",
operation_id = "List Profiles",
security(("api_key" = []))
)]
pub async fn profile_list() {}
// ******************************************** V2 profile routes ******************************************** //
#[cfg(feature = "v2")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/v2/profiles",
params(
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Account Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v2")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
put,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v2")]
/// Profile - Activate routing algorithm
///
/// Activates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/activate-routing-algorithm",
request_body ( content = RoutingAlgorithmId,
examples( (
"Activate a routing algorithm" = (
value = json!({
"routing_algorithm_id": "routing_algorithm_123"
})
)
))),
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Routing Algorithm is activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Profile",
operation_id = "Activates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v2")]
/// Profile - Deactivate routing algorithm
///
/// Deactivates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/deactivate-routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = " Deactivates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v2")]
/// Profile - Update Default Fallback Routing Algorithm
///
/// Update the default fallback routing algorithm for the profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/fallback-routing",
request_body = Vec<RoutableConnectorChoice>,
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully updated the default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = "Update the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_retrieve() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Active Routing Algorithm
///_
/// Retrieve active routing algorithm under the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"),
("offset" = Option<u8>, Query, description = "The record offset of the algorithm from which to start gathering the results")),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Profile",
operation_id = "Retrieve the active routing algorithm under the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Default Fallback Routing Algorithm
///
/// Retrieve the default fallback routing algorithm for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/fallback-routing",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully retrieved default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Profile",
operation_id = "Retrieve the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
/// Profile - Connector Accounts List
///
/// List Connector Accounts for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/connector-accounts",
params(
("id" = String, Path, description = "The unique identifier for the business profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Business Profile",
operation_id = "List all Merchant Connectors for Profile",
security(("admin_api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn connector_list() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/tokenization.rs | crates/openapi/src/routes/tokenization.rs | use serde_json::json;
use utoipa::OpenApi;
/// Tokenization - Create
///
/// Create a token with customer_id
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/tokenize",
request_body(
content = GenericTokenizationRequest,
examples(("Create a token with customer_id" = (
value = json!({
"customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8",
"token_request": {
"payment_method_data": {
"card": {
"card_holder_name": "test name"
}
}
}
})
)))
),
responses(
(status = 200, description = "Token created successfully", body = GenericTokenizationResponse),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 500, description = "Internal server error")
),
tag = "Tokenization",
operation_id = "create_token_vault_api",
security(("ephemeral_key" = []),("api_key" = []))
)]
pub async fn create_token_vault_api() {}
/// Tokenization - Delete
///
/// Delete a token entry with customer_id and session_id
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/tokenize/{id}",
request_body(
content = DeleteTokenDataRequest,
examples(("Delete a token entry with customer_id and session_id" = (
value = json!({
"customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8",
"session_id": "12345_pms_01926c58bc6e77c09e809964e72af8c8",
})
)))
),
responses(
(status = 200, description = "Token deleted successfully", body = DeleteTokenDataResponse),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 500, description = "Internal server error")
),
tag = "Tokenization",
operation_id = "delete_tokenized_data_api",
security(("ephemeral_key" = []),("api_key" = []))
)]
pub async fn delete_tokenized_data_api() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/consts.rs | crates/pm_auth/src/consts.rs | pub const REQUEST_TIME_OUT: u64 = 30; // will timeout after the mentioned limit
pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; // timeout error code
pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; // error message for timed out request
pub const NO_ERROR_CODE: &str = "No error code";
pub const NO_ERROR_MESSAGE: &str = "No error message";
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/lib.rs | crates/pm_auth/src/lib.rs | pub mod connector;
pub mod consts;
pub mod core;
pub mod types;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/connector.rs | crates/pm_auth/src/connector.rs | pub mod plaid;
pub use self::plaid::Plaid;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/core.rs | crates/pm_auth/src/core.rs | pub mod errors;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/types.rs | crates/pm_auth/src/types.rs | pub mod api;
use std::marker::PhantomData;
use api::auth_service::{BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate};
use api_models::enums as api_enums;
use common_enums::{CountryAlpha2, PaymentMethod, PaymentMethodType};
use common_utils::{id_type, types};
use masking::Secret;
#[derive(Debug, Clone)]
pub struct PaymentAuthRouterData<F, Request, Response> {
pub flow: PhantomData<F>,
pub merchant_id: Option<id_type::MerchantId>,
pub connector: Option<String>,
pub request: Request,
pub response: Result<Response, ErrorResponse>,
pub connector_auth_type: ConnectorAuthType,
pub connector_http_status_code: Option<u16>,
}
#[derive(Debug, Clone)]
pub struct LinkTokenRequest {
pub client_name: String,
pub country_codes: Option<Vec<String>>,
pub language: Option<String>,
pub user_info: Option<id_type::CustomerId>,
pub client_platform: Option<api_enums::ClientPlatform>,
pub android_package_name: Option<String>,
pub redirect_uri: Option<String>,
}
#[derive(Debug, Clone)]
pub struct LinkTokenResponse {
pub link_token: String,
}
pub type LinkTokenRouterData =
PaymentAuthRouterData<LinkToken, LinkTokenRequest, LinkTokenResponse>;
#[derive(Debug, Clone)]
pub struct ExchangeTokenRequest {
pub public_token: String,
}
#[derive(Debug, Clone)]
pub struct ExchangeTokenResponse {
pub access_token: String,
}
impl From<ExchangeTokenResponse> for api_models::pm_auth::ExchangeTokenCreateResponse {
fn from(value: ExchangeTokenResponse) -> Self {
Self {
access_token: value.access_token,
}
}
}
pub type ExchangeTokenRouterData =
PaymentAuthRouterData<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
#[derive(Debug, Clone)]
pub struct BankAccountCredentialsRequest {
pub access_token: Secret<String>,
pub optional_ids: Option<BankAccountOptionalIDs>,
}
#[derive(Debug, Clone)]
pub struct BankAccountOptionalIDs {
pub ids: Vec<Secret<String>>,
}
#[derive(Debug, Clone)]
pub struct BankAccountCredentialsResponse {
pub credentials: Vec<BankAccountDetails>,
}
#[derive(Debug, Clone)]
pub struct BankAccountDetails {
pub account_name: Option<String>,
pub account_details: PaymentMethodTypeDetails,
pub payment_method_type: PaymentMethodType,
pub payment_method: PaymentMethod,
pub account_id: Secret<String>,
pub account_type: Option<String>,
pub balance: Option<types::FloatMajorUnit>,
}
#[derive(Debug, Clone)]
pub enum PaymentMethodTypeDetails {
Ach(BankAccountDetailsAch),
Bacs(BankAccountDetailsBacs),
Sepa(BankAccountDetailsSepa),
}
#[derive(Debug, Clone)]
pub struct BankAccountDetailsAch {
pub account_number: Secret<String>,
pub routing_number: Secret<String>,
}
#[derive(Debug, Clone)]
pub struct BankAccountDetailsBacs {
pub account_number: Secret<String>,
pub sort_code: Secret<String>,
}
#[derive(Debug, Clone)]
pub struct BankAccountDetailsSepa {
pub iban: Secret<String>,
pub bic: Secret<String>,
}
pub type BankDetailsRouterData = PaymentAuthRouterData<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
>;
#[derive(Debug, Clone)]
pub struct RecipientCreateRequest {
pub name: String,
pub account_data: RecipientAccountData,
pub address: Option<RecipientCreateAddress>,
}
#[derive(Debug, Clone)]
pub struct RecipientCreateResponse {
pub recipient_id: String,
}
#[derive(Debug, Clone)]
pub enum RecipientAccountData {
Iban(Secret<String>),
Bacs {
sort_code: Secret<String>,
account_number: Secret<String>,
},
FasterPayments {
sort_code: Secret<String>,
account_number: Secret<String>,
},
Sepa(Secret<String>),
SepaInstant(Secret<String>),
Elixir {
account_number: Secret<String>,
iban: Secret<String>,
},
Bankgiro(Secret<String>),
Plusgiro(Secret<String>),
}
#[derive(Debug, Clone)]
pub struct RecipientCreateAddress {
pub street: String,
pub city: String,
pub postal_code: String,
pub country: CountryAlpha2,
}
pub type RecipientCreateRouterData =
PaymentAuthRouterData<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>;
pub type PaymentAuthLinkTokenType =
dyn api::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>;
pub type PaymentAuthExchangeTokenType =
dyn api::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>;
pub type PaymentAuthBankAccountDetailsType = dyn api::ConnectorIntegration<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
>;
pub type PaymentInitiationRecipientCreateType =
dyn api::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>;
#[derive(Clone, Debug, strum::EnumString, strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum PaymentMethodAuthConnectors {
Plaid,
}
#[derive(Debug, Clone)]
pub struct ResponseRouterData<Flow, R, Request, Response> {
pub response: R,
pub data: PaymentAuthRouterData<Flow, Request, Response>,
pub http_code: u16,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
pub reason: Option<String>,
pub status_code: u16,
}
impl ErrorResponse {
fn get_not_implemented() -> Self {
Self {
code: "IR_00".to_string(),
message: "This API is under development and will be made available soon.".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
}
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub enum MerchantAccountData {
Iban {
iban: Secret<String>,
name: String,
},
Bacs {
account_number: Secret<String>,
sort_code: Secret<String>,
name: String,
},
FasterPayments {
account_number: Secret<String>,
sort_code: Secret<String>,
name: String,
},
Sepa {
iban: Secret<String>,
name: String,
},
SepaInstant {
iban: Secret<String>,
name: String,
},
Elixir {
account_number: Secret<String>,
iban: Secret<String>,
name: String,
},
Bankgiro {
number: Secret<String>,
name: String,
},
Plusgiro {
number: Secret<String>,
name: String,
},
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MerchantRecipientData {
ConnectorRecipientId(Secret<String>),
WalletId(Secret<String>),
AccountData(MerchantAccountData),
}
#[derive(Default, Debug, Clone, serde::Deserialize)]
pub enum ConnectorAuthType {
BodyKey {
client_id: Secret<String>,
secret: Secret<String>,
},
#[default]
NoKey,
}
#[derive(Clone, Debug)]
pub struct Response {
pub headers: Option<http::HeaderMap>,
pub response: bytes::Bytes,
pub status_code: u16,
}
#[derive(serde::Deserialize, Clone)]
pub struct AuthServiceQueryParam {
pub client_secret: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/connector/plaid.rs | crates/pm_auth/src/connector/plaid.rs | pub mod transformers;
use std::fmt::Debug;
use common_utils::{
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use masking::{Mask, Maskable};
use transformers as plaid;
use crate::{
core::errors,
types::{
self as auth_types,
api::{
auth_service::{
self, BankAccountCredentials, ExchangeToken, LinkToken, RecipientCreate,
},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
},
},
};
#[derive(Debug, Clone)]
pub struct Plaid;
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Plaid
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &auth_types::PaymentAuthRouterData<Flow, Request, Response>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
"Content-Type".to_string(),
self.get_content_type().to_string().into(),
)];
let mut auth = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut auth);
Ok(header)
}
}
impl ConnectorCommon for Plaid {
fn id(&self) -> &'static str {
"plaid"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, _connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str {
"https://sandbox.plaid.com"
}
fn get_auth_header(
&self,
auth_type: &auth_types::ConnectorAuthType,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = plaid::PlaidAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let client_id = auth.client_id.into_masked();
let secret = auth.secret.into_masked();
Ok(vec![
("PLAID-CLIENT-ID".to_string(), client_id),
("PLAID-SECRET".to_string(), secret),
])
}
fn build_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
let response: plaid::PlaidErrorResponse =
res.response
.parse_struct("PlaidErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(auth_types::ErrorResponse {
status_code: res.status_code,
code: crate::consts::NO_ERROR_CODE.to_string(),
message: response.error_message,
reason: response.display_message,
})
}
}
impl auth_service::AuthService for Plaid {}
impl auth_service::PaymentInitiationRecipientCreate for Plaid {}
impl auth_service::PaymentInitiation for Plaid {}
impl auth_service::AuthServiceLinkToken for Plaid {}
impl ConnectorIntegration<LinkToken, auth_types::LinkTokenRequest, auth_types::LinkTokenResponse>
for Plaid
{
fn get_headers(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/link/token/create"
))
}
fn get_request_body(
&self,
req: &auth_types::LinkTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidLinkTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::LinkTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthLinkTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthLinkTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthLinkTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::LinkTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::LinkTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidLinkTokenResponse = res
.response
.parse_struct("PlaidLinkTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::LinkTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceExchangeToken for Plaid {}
impl
ConnectorIntegration<
ExchangeToken,
auth_types::ExchangeTokenRequest,
auth_types::ExchangeTokenResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/item/public_token/exchange"
))
}
fn get_request_body(
&self,
req: &auth_types::ExchangeTokenRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidExchangeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::ExchangeTokenRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthExchangeTokenType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthExchangeTokenType::get_headers(
self, req, connectors,
)?)
.set_body(auth_types::PaymentAuthExchangeTokenType::get_request_body(
self, req,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::ExchangeTokenRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ExchangeTokenRouterData, errors::ConnectorError> {
let response: plaid::PlaidExchangeTokenResponse = res
.response
.parse_struct("PlaidExchangeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::ExchangeTokenRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl auth_service::AuthServiceBankAccountCredentials for Plaid {}
impl
ConnectorIntegration<
BankAccountCredentials,
auth_types::BankAccountCredentialsRequest,
auth_types::BankAccountCredentialsResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/auth/get"))
}
fn get_request_body(
&self,
req: &auth_types::BankDetailsRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidBankAccountCredentialsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::BankDetailsRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentAuthBankAccountDetailsType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(auth_types::PaymentAuthBankAccountDetailsType::get_headers(
self, req, connectors,
)?)
.set_body(
auth_types::PaymentAuthBankAccountDetailsType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::BankDetailsRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::BankDetailsRouterData, errors::ConnectorError> {
let response: plaid::PlaidBankAccountCredentialsResponse = res
.response
.parse_struct("PlaidBankAccountCredentialsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
<auth_types::BankDetailsRouterData>::try_from(auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
impl
ConnectorIntegration<
RecipientCreate,
auth_types::RecipientCreateRequest,
auth_types::RecipientCreateResponse,
> for Plaid
{
fn get_headers(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"/payment_initiation/recipient/create"
))
}
fn get_request_body(
&self,
req: &auth_types::RecipientCreateRouterData,
) -> errors::CustomResult<RequestContent, errors::ConnectorError> {
let req_obj = plaid::PlaidRecipientCreateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &auth_types::RecipientCreateRouterData,
connectors: &auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&auth_types::PaymentInitiationRecipientCreateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(
auth_types::PaymentInitiationRecipientCreateType::get_headers(
self, req, connectors,
)?,
)
.set_body(
auth_types::PaymentInitiationRecipientCreateType::get_request_body(self, req)?,
)
.build(),
))
}
fn handle_response(
&self,
data: &auth_types::RecipientCreateRouterData,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::RecipientCreateRouterData, errors::ConnectorError> {
let response: plaid::PlaidRecipientCreateResponse = res
.response
.parse_struct("PlaidRecipientCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(<auth_types::RecipientCreateRouterData>::from(
auth_types::ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
))
}
fn get_error_response(
&self,
res: auth_types::Response,
) -> errors::CustomResult<auth_types::ErrorResponse, errors::ConnectorError> {
self.build_error_response(res)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/connector/plaid/transformers.rs | crates/pm_auth/src/connector/plaid/transformers.rs | use std::collections::HashMap;
use common_enums::{PaymentMethod, PaymentMethodType};
use common_utils::{id_type, types as util_types};
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{core::errors, types};
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenRequest {
client_name: String,
country_codes: Vec<String>,
language: String,
products: Vec<String>,
user: User,
android_package_name: Option<String>,
redirect_uri: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct User {
pub client_user_id: id_type::CustomerId,
}
impl TryFrom<&types::LinkTokenRouterData> for PlaidLinkTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::LinkTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
client_name: item.request.client_name.clone(),
country_codes: item.request.country_codes.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country_codes",
},
)?,
language: item.request.language.clone().unwrap_or("en".to_string()),
products: vec!["auth".to_string()],
user: User {
client_user_id: item.request.user_info.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "country_codes",
},
)?,
},
android_package_name: match item.request.client_platform {
Some(api_models::enums::ClientPlatform::Android) => {
item.request.android_package_name.clone()
}
Some(api_models::enums::ClientPlatform::Ios)
| Some(api_models::enums::ClientPlatform::Web)
| Some(api_models::enums::ClientPlatform::Unknown)
| None => None,
},
redirect_uri: match item.request.client_platform {
Some(api_models::enums::ClientPlatform::Ios) => item.request.redirect_uri.clone(),
Some(api_models::enums::ClientPlatform::Android)
| Some(api_models::enums::ClientPlatform::Web)
| Some(api_models::enums::ClientPlatform::Unknown)
| None => None,
},
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidLinkTokenResponse {
link_token: String,
}
impl<F, T>
TryFrom<types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>>
for types::PaymentAuthRouterData<F, T, types::LinkTokenResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<F, PlaidLinkTokenResponse, T, types::LinkTokenResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::LinkTokenResponse {
link_token: item.response.link_token,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidExchangeTokenRequest {
public_token: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidExchangeTokenResponse {
pub access_token: String,
}
impl<F, T>
TryFrom<
types::ResponseRouterData<F, PlaidExchangeTokenResponse, T, types::ExchangeTokenResponse>,
> for types::PaymentAuthRouterData<F, T, types::ExchangeTokenResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
PlaidExchangeTokenResponse,
T,
types::ExchangeTokenResponse,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::ExchangeTokenResponse {
access_token: item.response.access_token,
}),
..item.data
})
}
}
impl TryFrom<&types::ExchangeTokenRouterData> for PlaidExchangeTokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::ExchangeTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
public_token: item.request.public_token.clone(),
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateRequest {
pub name: String,
#[serde(flatten)]
pub account_data: PlaidRecipientAccountData,
pub address: Option<PlaidRecipientCreateAddress>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateResponse {
pub recipient_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum PlaidRecipientAccountData {
Iban(Secret<String>),
Bacs {
sort_code: Secret<String>,
account: Secret<String>,
},
}
impl TryFrom<&types::RecipientAccountData> for PlaidRecipientAccountData {
type Error = errors::ConnectorError;
fn try_from(item: &types::RecipientAccountData) -> Result<Self, Self::Error> {
match item {
types::RecipientAccountData::Iban(iban) => Ok(Self::Iban(iban.clone())),
types::RecipientAccountData::Bacs {
sort_code,
account_number,
} => Ok(Self::Bacs {
sort_code: sort_code.clone(),
account: account_number.clone(),
}),
types::RecipientAccountData::FasterPayments { .. }
| types::RecipientAccountData::Sepa(_)
| types::RecipientAccountData::SepaInstant(_)
| types::RecipientAccountData::Elixir { .. }
| types::RecipientAccountData::Bankgiro(_)
| types::RecipientAccountData::Plusgiro(_) => {
Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Invalid payment method selected. Only Iban, Bacs Supported",
})
}
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct PlaidRecipientCreateAddress {
pub street: String,
pub city: String,
pub postal_code: String,
pub country: String,
}
impl From<&types::RecipientCreateAddress> for PlaidRecipientCreateAddress {
fn from(item: &types::RecipientCreateAddress) -> Self {
Self {
street: item.street.clone(),
city: item.city.clone(),
postal_code: item.postal_code.clone(),
country: common_enums::CountryAlpha2::to_string(&item.country),
}
}
}
impl TryFrom<&types::RecipientCreateRouterData> for PlaidRecipientCreateRequest {
type Error = errors::ConnectorError;
fn try_from(item: &types::RecipientCreateRouterData) -> Result<Self, Self::Error> {
Ok(Self {
name: item.request.name.clone(),
account_data: PlaidRecipientAccountData::try_from(&item.request.account_data)?,
address: item
.request
.address
.as_ref()
.map(PlaidRecipientCreateAddress::from),
})
}
}
impl<F, T>
From<
types::ResponseRouterData<
F,
PlaidRecipientCreateResponse,
T,
types::RecipientCreateResponse,
>,
> for types::PaymentAuthRouterData<F, T, types::RecipientCreateResponse>
{
fn from(
item: types::ResponseRouterData<
F,
PlaidRecipientCreateResponse,
T,
types::RecipientCreateResponse,
>,
) -> Self {
Self {
response: Ok(types::RecipientCreateResponse {
recipient_id: item.response.recipient_id,
}),
..item.data
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidBankAccountCredentialsRequest {
access_token: String,
options: Option<BankAccountCredentialsOptions>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsResponse {
pub accounts: Vec<PlaidBankAccountCredentialsAccounts>,
pub numbers: PlaidBankAccountCredentialsNumbers,
// pub item: PlaidBankAccountCredentialsItem,
pub request_id: String,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct BankAccountCredentialsOptions {
account_ids: Vec<String>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsAccounts {
pub account_id: String,
pub name: String,
pub subtype: Option<String>,
pub balances: Option<PlaidBankAccountCredentialsBalances>,
}
#[derive(Debug, Deserialize, PartialEq)]
pub struct PlaidBankAccountCredentialsBalances {
pub available: Option<util_types::FloatMajorUnit>,
pub current: Option<util_types::FloatMajorUnit>,
pub limit: Option<util_types::FloatMajorUnit>,
pub iso_currency_code: Option<String>,
pub unofficial_currency_code: Option<String>,
pub last_updated_datetime: Option<String>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsNumbers {
pub ach: Vec<PlaidBankAccountCredentialsACH>,
pub eft: Vec<PlaidBankAccountCredentialsEFT>,
pub international: Vec<PlaidBankAccountCredentialsInternational>,
pub bacs: Vec<PlaidBankAccountCredentialsBacs>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsItem {
pub item_id: String,
pub institution_id: Option<String>,
pub webhook: Option<String>,
pub error: Option<PlaidErrorResponse>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsACH {
pub account_id: String,
pub account: String,
pub routing: String,
pub wire_routing: Option<String>,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsEFT {
pub account_id: String,
pub account: String,
pub institution: String,
pub branch: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsInternational {
pub account_id: String,
pub iban: String,
pub bic: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct PlaidBankAccountCredentialsBacs {
pub account_id: String,
pub account: String,
pub sort_code: String,
}
impl TryFrom<&types::BankDetailsRouterData> for PlaidBankAccountCredentialsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::BankDetailsRouterData) -> Result<Self, Self::Error> {
let options = item.request.optional_ids.as_ref().map(|bank_account_ids| {
let ids = bank_account_ids
.ids
.iter()
.map(|id| id.peek().to_string())
.collect::<Vec<_>>();
BankAccountCredentialsOptions { account_ids: ids }
});
Ok(Self {
access_token: item.request.access_token.peek().to_string(),
options,
})
}
}
impl<F, T>
TryFrom<
types::ResponseRouterData<
F,
PlaidBankAccountCredentialsResponse,
T,
types::BankAccountCredentialsResponse,
>,
> for types::PaymentAuthRouterData<F, T, types::BankAccountCredentialsResponse>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<
F,
PlaidBankAccountCredentialsResponse,
T,
types::BankAccountCredentialsResponse,
>,
) -> Result<Self, Self::Error> {
let (account_numbers, accounts_info) = (item.response.numbers, item.response.accounts);
let mut bank_account_vec = Vec::new();
let mut id_to_subtype = HashMap::new();
accounts_info.into_iter().for_each(|acc| {
id_to_subtype.insert(
acc.account_id,
(
acc.subtype,
acc.name,
acc.balances.and_then(|balance| balance.available),
),
);
});
account_numbers.ach.into_iter().for_each(|ach| {
let (acc_type, acc_name, available_balance) = if let Some((
_type,
name,
available_balance,
)) = id_to_subtype.get(&ach.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Ach(types::BankAccountDetailsAch {
account_number: Secret::new(ach.account),
routing_number: Secret::new(ach.routing),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Ach,
payment_method: PaymentMethod::BankDebit,
account_id: ach.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
account_numbers.bacs.into_iter().for_each(|bacs| {
let (acc_type, acc_name, available_balance) =
if let Some((_type, name, available_balance)) = id_to_subtype.get(&bacs.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Bacs(types::BankAccountDetailsBacs {
account_number: Secret::new(bacs.account),
sort_code: Secret::new(bacs.sort_code),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Bacs,
payment_method: PaymentMethod::BankDebit,
account_id: bacs.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
account_numbers.international.into_iter().for_each(|sepa| {
let (acc_type, acc_name, available_balance) =
if let Some((_type, name, available_balance)) = id_to_subtype.get(&sepa.account_id)
{
(_type.to_owned(), Some(name.clone()), *available_balance)
} else {
(None, None, None)
};
let account_details =
types::PaymentMethodTypeDetails::Sepa(types::BankAccountDetailsSepa {
iban: Secret::new(sepa.iban),
bic: Secret::new(sepa.bic),
});
let bank_details_new = types::BankAccountDetails {
account_name: acc_name,
account_details,
payment_method_type: PaymentMethodType::Sepa,
payment_method: PaymentMethod::BankDebit,
account_id: sepa.account_id.into(),
account_type: acc_type,
balance: available_balance,
};
bank_account_vec.push(bank_details_new);
});
Ok(Self {
response: Ok(types::BankAccountCredentialsResponse {
credentials: bank_account_vec,
}),
..item.data
})
}
}
pub struct PlaidAuthType {
pub client_id: Secret<String>,
pub secret: Secret<String>,
}
impl TryFrom<&types::ConnectorAuthType> for PlaidAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
types::ConnectorAuthType::BodyKey { client_id, secret } => Ok(Self {
client_id: client_id.to_owned(),
secret: secret.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct PlaidErrorResponse {
pub display_message: Option<String>,
pub error_code: Option<String>,
pub error_message: String,
pub error_type: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/types/api.rs | crates/pm_auth/src/types/api.rs | pub mod auth_service;
use std::fmt::Debug;
use common_utils::{
errors::CustomResult,
request::{Request, RequestContent},
};
use masking::Maskable;
use crate::{
core::errors::ConnectorError,
types::{
self as auth_types,
api::auth_service::{AuthService, PaymentInitiation},
},
};
#[async_trait::async_trait]
pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync {
fn get_headers(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
Ok(vec![])
}
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
fn get_url(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<String, ConnectorError> {
Ok(String::new())
}
fn get_request_body(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
) -> CustomResult<RequestContent, ConnectorError> {
Ok(RequestContent::Json(Box::new(serde_json::json!(r#"{}"#))))
}
fn build_request(
&self,
_req: &super::PaymentAuthRouterData<T, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(None)
}
fn handle_response(
&self,
data: &super::PaymentAuthRouterData<T, Req, Resp>,
_res: auth_types::Response,
) -> CustomResult<super::PaymentAuthRouterData<T, Req, Resp>, ConnectorError>
where
T: Clone,
Req: Clone,
Resp: Clone,
{
Ok(data.clone())
}
fn get_error_response(
&self,
_res: auth_types::Response,
) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
Ok(auth_types::ErrorResponse::get_not_implemented())
}
fn get_5xx_error_response(
&self,
res: auth_types::Response,
) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
Ok(auth_types::ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
})
}
}
pub trait ConnectorCommonExt<Flow, Req, Resp>:
ConnectorCommon + ConnectorIntegration<Flow, Req, Resp>
{
fn build_headers(
&self,
_req: &auth_types::PaymentAuthRouterData<Flow, Req, Resp>,
_connectors: &auth_types::PaymentMethodAuthConnectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
Ok(Vec::new())
}
}
pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
}
impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
where
S: ConnectorIntegration<T, Req, Resp>,
{
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
Box::new(self)
}
}
pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation {}
impl<T: Send + Debug + AuthService + PaymentInitiation> AuthServiceConnector for T {}
pub type BoxedPaymentAuthConnector = Box<&'static (dyn AuthServiceConnector + Sync)>;
#[derive(Clone, Debug)]
pub struct PaymentAuthConnectorData {
pub connector: BoxedPaymentAuthConnector,
pub connector_name: super::PaymentMethodAuthConnectors,
}
pub trait ConnectorCommon {
fn id(&self) -> &'static str;
fn get_auth_header(
&self,
_auth_type: &auth_types::ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
Ok(Vec::new())
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a auth_types::PaymentMethodAuthConnectors) -> &'a str;
fn build_error_response(
&self,
res: auth_types::Response,
) -> CustomResult<auth_types::ErrorResponse, ConnectorError> {
Ok(auth_types::ErrorResponse {
status_code: res.status_code,
code: crate::consts::NO_ERROR_CODE.to_string(),
message: crate::consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/types/api/auth_service.rs | crates/pm_auth/src/types/api/auth_service.rs | use crate::types::{
BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest,
ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest,
RecipientCreateResponse,
};
pub trait AuthService:
super::ConnectorCommon
+ AuthServiceLinkToken
+ AuthServiceExchangeToken
+ AuthServiceBankAccountCredentials
{
}
pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {}
#[derive(Debug, Clone)]
pub struct LinkToken;
pub trait AuthServiceLinkToken:
super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>
{
}
#[derive(Debug, Clone)]
pub struct ExchangeToken;
pub trait AuthServiceExchangeToken:
super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>
{
}
#[derive(Debug, Clone)]
pub struct BankAccountCredentials;
pub trait AuthServiceBankAccountCredentials:
super::ConnectorIntegration<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
>
{
}
#[derive(Debug, Clone)]
pub struct RecipientCreate;
pub trait PaymentInitiationRecipientCreate:
super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>
{
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/pm_auth/src/core/errors.rs | crates/pm_auth/src/core/errors.rs | #[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Invalid connector configuration: {config}")]
InvalidConnectorConfig { config: &'static str },
}
pub type CustomResult<T, E> = error_stack::Result<T, E>;
#[derive(Debug, thiserror::Error)]
pub enum ParsingError {
#[error("Failed to parse enum: {0}")]
EnumParseFailure(&'static str),
#[error("Failed to parse struct: {0}")]
StructParseFailure(&'static str),
#[error("Failed to serialize to {0} format")]
EncodeError(&'static str),
#[error("Unknown error while parsing")]
UnknownError,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile-utils/src/lib.rs | zellij-tile-utils/src/lib.rs | #[macro_export]
macro_rules! rgb {
($a:expr) => {
ansi_term::Color::Rgb($a.0, $a.1, $a.2)
};
}
#[macro_export]
macro_rules! palette_match {
($palette_color:expr) => {
match $palette_color {
PaletteColor::Rgb((r, g, b)) => RGB(r, g, b),
PaletteColor::EightBit(color) => Fixed(color),
}
};
}
#[macro_export]
macro_rules! style {
($fg:expr, $bg:expr) => {
ansi_term::Style::new()
.fg(match $fg {
PaletteColor::Rgb((r, g, b)) => ansi_term::Color::RGB(r, g, b),
PaletteColor::EightBit(color) => ansi_term::Color::Fixed(color),
})
.on(match $bg {
PaletteColor::Rgb((r, g, b)) => ansi_term::Color::RGB(r, g, b),
PaletteColor::EightBit(color) => ansi_term::Color::Fixed(color),
})
};
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/src/commands.rs | src/commands.rs | use dialoguer::Confirm;
use std::net::IpAddr;
use std::{fs::File, io::prelude::*, path::PathBuf, process, time::Duration};
#[cfg(feature = "web_server_capability")]
use isahc::{config::RedirectPolicy, prelude::*, HttpClient, Request};
use nix;
use zellij_client::{
old_config_converter::{
config_yaml_to_config_kdl, convert_old_yaml_files, layout_yaml_to_layout_kdl,
},
os_input_output::get_client_os_input,
start_client as start_client_impl, ClientInfo,
};
use zellij_utils::sessions::{
assert_dead_session, assert_session, assert_session_ne, delete_session as delete_session_impl,
generate_unique_session_name, get_active_session, get_resurrectable_sessions, get_sessions,
get_sessions_sorted_by_mtime, kill_session as kill_session_impl, match_session_name,
print_sessions, print_sessions_with_index, resurrection_layout, session_exists, ActiveSession,
SessionNameMatch,
};
use zellij_utils::consts::session_layout_cache_file_name;
#[cfg(feature = "web_server_capability")]
use zellij_client::web_client::start_web_client as start_web_client_impl;
#[cfg(feature = "web_server_capability")]
use zellij_utils::web_server_commands::shutdown_all_webserver_instances;
#[cfg(feature = "web_server_capability")]
use zellij_utils::web_authentication_tokens::{
create_token, list_tokens, revoke_all_tokens, revoke_token,
};
use miette::{Report, Result};
use zellij_server::{os_input_output::get_server_os_input, start_server as start_server_impl};
use zellij_utils::{
cli::{CliArgs, Command, SessionCommand, Sessions},
data::ConnectToSession,
envs,
input::{
actions::Action,
config::{Config, ConfigError},
options::Options,
},
setup::Setup,
};
pub(crate) use zellij_utils::sessions::list_sessions;
pub(crate) fn kill_all_sessions(yes: bool) {
match get_sessions() {
Ok(sessions) if sessions.is_empty() => {
eprintln!("No active zellij sessions found.");
process::exit(1);
},
Ok(sessions) => {
if !yes {
println!("WARNING: this action will kill all sessions.");
if !Confirm::new()
.with_prompt("Do you want to continue?")
.interact()
.unwrap()
{
println!("Abort.");
process::exit(1);
}
}
for session in &sessions {
kill_session_impl(&session.0);
}
process::exit(0);
},
Err(e) => {
eprintln!("Error occurred: {:?}", e);
process::exit(1);
},
}
}
pub(crate) fn delete_all_sessions(yes: bool, force: bool) {
let active_sessions: Vec<String> = get_sessions()
.unwrap_or_default()
.iter()
.map(|s| s.0.clone())
.collect();
let resurrectable_sessions = get_resurrectable_sessions();
let dead_sessions: Vec<_> = if force {
resurrectable_sessions
} else {
resurrectable_sessions
.iter()
.filter(|(name, _)| !active_sessions.contains(name))
.cloned()
.collect()
};
if !yes {
println!("WARNING: this action will delete all resurrectable sessions.");
if !Confirm::new()
.with_prompt("Do you want to continue?")
.interact()
.unwrap()
{
println!("Abort.");
process::exit(1);
}
}
for session in &dead_sessions {
delete_session_impl(&session.0, force);
}
process::exit(0);
}
pub(crate) fn kill_session(target_session: &Option<String>) {
match target_session {
Some(target_session) => {
assert_session(target_session);
kill_session_impl(target_session);
process::exit(0);
},
None => {
println!("Please specify the session name to kill.");
process::exit(1);
},
}
}
pub(crate) fn delete_session(target_session: &Option<String>, force: bool) {
match target_session {
Some(target_session) => {
assert_dead_session(target_session, force);
delete_session_impl(target_session, force);
process::exit(0);
},
None => {
println!("Please specify the session name to delete.");
process::exit(1);
},
}
}
fn get_os_input<OsInputOutput>(
fn_get_os_input: fn() -> Result<OsInputOutput, nix::Error>,
) -> OsInputOutput {
match fn_get_os_input() {
Ok(os_input) => os_input,
Err(e) => {
eprintln!("failed to open terminal:\n{}", e);
process::exit(1);
},
}
}
pub(crate) fn start_server(path: PathBuf, debug: bool) {
// Set instance-wide debug mode
zellij_utils::consts::DEBUG_MODE.set(debug).unwrap();
let os_input = get_os_input(get_server_os_input);
start_server_impl(Box::new(os_input), path);
}
#[cfg(feature = "web_server_capability")]
pub(crate) fn start_web_server(
opts: CliArgs,
run_daemonized: bool,
ip: Option<IpAddr>,
port: Option<u16>,
cert: Option<PathBuf>,
key: Option<PathBuf>,
) {
// TODO: move this outside of this function
let (config, _layout, config_options, _config_without_layout, _config_options_without_layout) =
match Setup::from_cli_args(&opts) {
Ok(results) => results,
Err(e) => {
if let ConfigError::KdlError(error) = e {
let report: Report = error.into();
eprintln!("{:?}", report);
} else {
eprintln!("{}", e);
}
process::exit(1);
},
};
start_web_client_impl(
config,
config_options,
opts.config,
run_daemonized,
ip,
port,
cert,
key,
);
}
#[cfg(not(feature = "web_server_capability"))]
pub(crate) fn start_web_server(
_opts: CliArgs,
_run_daemonized: bool,
_ip: Option<IpAddr>,
_port: Option<u16>,
_cert: Option<PathBuf>,
_key: Option<PathBuf>,
) {
log::error!(
"This version of Zellij was compiled without web server support, cannot run web server!"
);
eprintln!(
"This version of Zellij was compiled without web server support, cannot run web server!"
);
std::process::exit(2);
}
fn create_new_client() -> ClientInfo {
ClientInfo::New(generate_unique_session_name_or_exit(), None, None)
}
#[cfg(feature = "web_server_capability")]
pub(crate) fn stop_web_server() -> Result<(), String> {
shutdown_all_webserver_instances().map_err(|e| e.to_string())?;
Ok(())
}
#[cfg(not(feature = "web_server_capability"))]
pub(crate) fn stop_web_server() -> Result<(), String> {
log::error!(
"This version of Zellij was compiled without web server support, cannot stop web server!"
);
eprintln!(
"This version of Zellij was compiled without web server support, cannot stop web server!"
);
std::process::exit(2);
}
#[cfg(feature = "web_server_capability")]
pub(crate) fn create_auth_token(name: Option<String>, read_only: bool) -> Result<String, String> {
// returns the token and it's name
create_token(name, read_only)
.map(|(token, token_name)| {
let access_type = if read_only { " (read-only)" } else { "" };
format!("{}: {}{}", token, token_name, access_type)
})
.map_err(|e| e.to_string())
}
#[cfg(not(feature = "web_server_capability"))]
pub(crate) fn create_auth_token(_name: Option<String>, _read_only: bool) -> Result<String, String> {
log::error!(
"This version of Zellij was compiled without web server support, cannot create auth token!"
);
eprintln!(
"This version of Zellij was compiled without web server support, cannot create auth token!"
);
std::process::exit(2);
}
#[cfg(feature = "web_server_capability")]
pub(crate) fn revoke_auth_token(token_name: &str) -> Result<bool, String> {
revoke_token(token_name).map_err(|e| e.to_string())
}
#[cfg(not(feature = "web_server_capability"))]
pub(crate) fn revoke_auth_token(_token_name: &str) -> Result<bool, String> {
log::error!(
"This version of Zellij was compiled without web server support, cannot revoke auth token!"
);
eprintln!(
"This version of Zellij was compiled without web server support, cannot revoke auth token!"
);
std::process::exit(2);
}
#[cfg(feature = "web_server_capability")]
pub(crate) fn revoke_all_auth_tokens() -> Result<usize, String> {
// returns the revoked count
revoke_all_tokens().map_err(|e| e.to_string())
}
#[cfg(not(feature = "web_server_capability"))]
pub(crate) fn revoke_all_auth_tokens() -> Result<usize, String> {
log::error!(
"This version of Zellij was compiled without web server support, cannot revoke all tokens!"
);
eprintln!(
"This version of Zellij was compiled without web server support, cannot revoke all tokens!"
);
std::process::exit(2);
}
#[cfg(feature = "web_server_capability")]
pub(crate) fn list_auth_tokens() -> Result<Vec<String>, String> {
// returns the token list line by line
list_tokens()
.map(|tokens| {
let mut res = vec![];
for t in tokens {
let access_type = if t.read_only { " [READ-ONLY]" } else { "" };
res.push(format!(
"{}: created at {}{}",
t.name, t.created_at, access_type
))
}
res
})
.map_err(|e| e.to_string())
}
#[cfg(not(feature = "web_server_capability"))]
pub(crate) fn list_auth_tokens() -> Result<Vec<String>, String> {
log::error!(
"This version of Zellij was compiled without web server support, cannot list tokens!"
);
eprintln!(
"This version of Zellij was compiled without web server support, cannot list tokens!"
);
std::process::exit(2);
}
#[cfg(feature = "web_server_capability")]
pub(crate) fn web_server_status(web_server_base_url: &str) -> Result<String, String> {
let http_client = HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()
.map_err(|e| e.to_string())?;
let request = Request::get(format!("{}/info/version", web_server_base_url,));
let req = request.body(()).map_err(|e| e.to_string())?;
let mut res = http_client.send(req).map_err(|e| e.to_string())?;
let status_code = res.status();
if status_code == 200 {
let body = res.bytes().map_err(|e| e.to_string())?;
Ok(String::from_utf8_lossy(&body).to_string())
} else {
Err(format!(
"Failed to stop web server, got status code: {}",
status_code
))
}
}
#[cfg(not(feature = "web_server_capability"))]
pub(crate) fn web_server_status(_web_server_base_url: &str) -> Result<String, String> {
log::error!(
"This version of Zellij was compiled without web server support, cannot get web server status!"
);
eprintln!(
"This version of Zellij was compiled without web server support, cannot get web server status!"
);
std::process::exit(2);
}
fn find_indexed_session(
sessions: Vec<String>,
config_options: Options,
index: usize,
create: bool,
) -> ClientInfo {
match sessions.get(index) {
Some(session) => ClientInfo::Attach(session.clone(), config_options),
None if create => create_new_client(),
None => {
println!(
"No session indexed by {} found. The following sessions are active:",
index
);
print_sessions_with_index(sessions);
process::exit(1);
},
}
}
/// Client entrypoint for all [`zellij_utils::cli::CliAction`]
///
/// Checks session to send the action to and attaches with client
pub(crate) fn send_action_to_session(
cli_action: zellij_utils::cli::CliAction,
requested_session_name: Option<String>,
config: Option<Config>,
) {
match get_active_session() {
ActiveSession::None => {
eprintln!("There is no active session!");
std::process::exit(1);
},
ActiveSession::One(session_name) => {
if let Some(requested_session_name) = requested_session_name {
if requested_session_name != session_name {
eprintln!(
"Session '{}' not found. The following sessions are active:",
requested_session_name
);
eprintln!("{}", session_name);
std::process::exit(1);
}
}
attach_with_cli_client(cli_action, &session_name, config);
},
ActiveSession::Many => {
let existing_sessions: Vec<String> = get_sessions()
.unwrap_or_default()
.iter()
.map(|s| s.0.clone())
.collect();
if let Some(session_name) = requested_session_name {
if existing_sessions.contains(&session_name) {
attach_with_cli_client(cli_action, &session_name, config);
} else {
eprintln!(
"Session '{}' not found. The following sessions are active:",
session_name
);
list_sessions(false, false, true);
std::process::exit(1);
}
} else if let Ok(session_name) = envs::get_session_name() {
attach_with_cli_client(cli_action, &session_name, config);
} else {
eprintln!("Please specify the session name to send actions to. The following sessions are active:");
list_sessions(false, false, true);
std::process::exit(1);
}
},
};
}
pub(crate) fn convert_old_config_file(old_config_file: PathBuf) {
match File::open(&old_config_file) {
Ok(mut handle) => {
let mut raw_config_file = String::new();
let _ = handle.read_to_string(&mut raw_config_file);
match config_yaml_to_config_kdl(&raw_config_file, false) {
Ok(kdl_config) => {
println!("{}", kdl_config);
process::exit(0);
},
Err(e) => {
eprintln!("Failed to convert config: {}", e);
process::exit(1);
},
}
},
Err(e) => {
eprintln!("Failed to open file: {}", e);
process::exit(1);
},
}
}
pub(crate) fn convert_old_layout_file(old_layout_file: PathBuf) {
match File::open(&old_layout_file) {
Ok(mut handle) => {
let mut raw_layout_file = String::new();
let _ = handle.read_to_string(&mut raw_layout_file);
match layout_yaml_to_layout_kdl(&raw_layout_file) {
Ok(kdl_layout) => {
println!("{}", kdl_layout);
process::exit(0);
},
Err(e) => {
eprintln!("Failed to convert layout: {}", e);
process::exit(1);
},
}
},
Err(e) => {
eprintln!("Failed to open file: {}", e);
process::exit(1);
},
}
}
pub(crate) fn convert_old_theme_file(old_theme_file: PathBuf) {
match File::open(&old_theme_file) {
Ok(mut handle) => {
let mut raw_config_file = String::new();
let _ = handle.read_to_string(&mut raw_config_file);
match config_yaml_to_config_kdl(&raw_config_file, true) {
Ok(kdl_config) => {
println!("{}", kdl_config);
process::exit(0);
},
Err(e) => {
eprintln!("Failed to convert config: {}", e);
process::exit(1);
},
}
},
Err(e) => {
eprintln!("Failed to open file: {}", e);
process::exit(1);
},
}
}
fn attach_with_cli_client(
cli_action: zellij_utils::cli::CliAction,
session_name: &str,
config: Option<Config>,
) {
let os_input = get_os_input(zellij_client::os_input_output::get_cli_client_os_input);
let get_current_dir = || std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
match Action::actions_from_cli(cli_action, Box::new(get_current_dir), config) {
Ok(actions) => {
zellij_client::cli_client::start_cli_client(Box::new(os_input), session_name, actions);
std::process::exit(0);
},
Err(e) => {
eprintln!("{}", e);
log::error!("Error sending action: {}", e);
std::process::exit(2);
},
}
}
fn attach_with_session_index(config_options: Options, index: usize, create: bool) -> ClientInfo {
// Ignore the session_name when `--index` is provided
match get_sessions_sorted_by_mtime() {
Ok(sessions) if sessions.is_empty() => {
if create {
create_new_client()
} else {
eprintln!("No active zellij sessions found.");
process::exit(1);
}
},
Ok(sessions) => find_indexed_session(sessions, config_options, index, create),
Err(e) => {
eprintln!("Error occurred: {:?}", e);
process::exit(1);
},
}
}
fn attach_with_session_name(
session_name: Option<String>,
config_options: Options,
create: bool,
) -> ClientInfo {
match &session_name {
Some(session) if create => {
if session_exists(session).unwrap() {
ClientInfo::Attach(session_name.unwrap(), config_options)
} else {
ClientInfo::New(session_name.unwrap(), None, None)
}
},
Some(prefix) => match match_session_name(prefix).unwrap() {
SessionNameMatch::UniquePrefix(s) | SessionNameMatch::Exact(s) => {
ClientInfo::Attach(s, config_options)
},
SessionNameMatch::AmbiguousPrefix(sessions) => {
println!(
"Ambiguous selection: multiple sessions names start with '{}':",
prefix
);
print_sessions(
sessions
.iter()
.map(|s| (s.clone(), Duration::default(), false))
.collect(),
false,
false,
true,
);
process::exit(1);
},
SessionNameMatch::None => {
eprintln!("No session with the name '{}' found!", prefix);
process::exit(1);
},
},
None => match get_active_session() {
ActiveSession::None if create => create_new_client(),
ActiveSession::None => {
eprintln!("No active zellij sessions found.");
process::exit(1);
},
ActiveSession::One(session_name) => ClientInfo::Attach(session_name, config_options),
ActiveSession::Many => {
println!("Please specify the session to attach to, either by using the full name or a unique prefix.\nThe following sessions are active:");
list_sessions(false, false, true);
process::exit(1);
},
},
}
}
pub(crate) fn start_client(opts: CliArgs) {
// look for old YAML config/layout/theme files and convert them to KDL
convert_old_yaml_files(&opts);
let (
config,
_layout,
config_options,
mut config_without_layout,
mut config_options_without_layout,
) = match Setup::from_cli_args(&opts) {
Ok(results) => results,
Err(e) => {
if let ConfigError::KdlError(error) = e {
let report: Report = error.into();
eprintln!("{:?}", report);
} else {
eprintln!("{}", e);
}
process::exit(1);
},
};
let mut reconnect_to_session: Option<ConnectToSession> = None;
let os_input = get_os_input(get_client_os_input);
loop {
let os_input = os_input.clone();
let config = config.clone();
let mut config_options = config_options.clone();
let mut opts = opts.clone();
let mut is_a_reconnect = false;
let mut should_create_detached = false;
let mut layout_info = None;
let mut new_session_cwd = None;
if let Some(reconnect_to_session) = &reconnect_to_session {
// this is integration code to make session reconnects work with this existing,
// untested and pretty involved function
//
// ideally, we should write tests for this whole function and refctor it
reload_config_from_disk(
&mut config_without_layout,
&mut config_options_without_layout,
&opts,
);
if reconnect_to_session.name.is_some() {
opts.command = Some(Command::Sessions(Sessions::Attach {
session_name: reconnect_to_session.name.clone(),
create: true,
create_background: false,
force_run_commands: false,
index: None,
options: None,
token: None,
remember: false,
forget: false,
}));
} else {
opts.command = None;
opts.session = None;
config_options.attach_to_session = None;
}
if let Some(reconnect_layout) = &reconnect_to_session.layout {
layout_info = Some(reconnect_layout.clone());
}
if let Some(cwd) = &reconnect_to_session.cwd {
new_session_cwd = Some(cwd.clone());
}
is_a_reconnect = true;
}
let start_client_plan = |session_name: std::string::String| {
assert_session_ne(&session_name);
};
if let Some(Command::Sessions(Sessions::Attach {
session_name,
create,
create_background,
force_run_commands,
index,
options,
token,
remember,
forget,
})) = opts.command.clone()
{
if let Some(remote_session_url) = session_name.as_ref().and_then(|s| {
if s.starts_with("http://") || s.starts_with("https://") {
Some(s)
} else {
None
}
}) {
if !cfg!(feature = "web_server_capability") {
eprintln!("This version of Zellij was compiled without web/remote-attach capabilities.");
std::process::exit(2);
}
if options.is_some() || create || create_background || force_run_commands {
eprintln!("Cannot attach to remote session with options.");
std::process::exit(2);
}
#[cfg(feature = "web_server_capability")]
use zellij_client::start_remote_client;
#[cfg(feature = "web_server_capability")]
if let Err(e) = start_remote_client(
Box::new(os_input.clone()),
remote_session_url,
token,
remember,
forget,
) {
eprintln!("{}", e);
std::process::exit(2);
}
} else {
let config_options = match options.as_deref() {
Some(SessionCommand::Options(o)) => {
config_options.merge_from_cli(o.to_owned().into())
},
None => config_options,
};
should_create_detached = create_background;
let mut client = if let Some(idx) = index {
attach_with_session_index(
config_options.clone(),
idx,
create || should_create_detached,
)
} else {
let session_exists = session_name
.as_ref()
.and_then(|s| session_exists(&s).ok())
.unwrap_or(false);
let resurrection_layout =
session_name
.as_ref()
.and_then(|s| match resurrection_layout(&s) {
Ok(layout) => layout,
Err(e) => {
eprintln!("{}", e);
process::exit(2);
},
});
if (create || should_create_detached)
&& !session_exists
&& resurrection_layout.is_none()
{
session_name.clone().map(start_client_plan);
}
match (session_name.as_ref(), resurrection_layout) {
(Some(session_name), Some(mut resurrection_layout)) if !session_exists => {
if force_run_commands {
resurrection_layout.recursively_add_start_suspended(Some(false));
}
ClientInfo::Resurrect(
session_name.clone(),
session_layout_cache_file_name(session_name.as_ref()),
force_run_commands,
new_session_cwd.clone(),
)
},
_ => attach_with_session_name(
session_name,
config_options.clone(),
create || should_create_detached,
),
}
};
if let Ok(val) = std::env::var(envs::SESSION_NAME_ENV_KEY) {
if val == *client.get_session_name() {
panic!("You are trying to attach to the current session (\"{}\"). This is not supported.", val);
}
}
if let Some(layout_info) = layout_info {
client.set_layout_info(layout_info);
}
if let Some(new_session_cwd) = new_session_cwd {
client.set_cwd(new_session_cwd);
}
let tab_position_to_focus = reconnect_to_session
.as_ref()
.and_then(|r| r.tab_position.clone());
let pane_id_to_focus = reconnect_to_session
.as_ref()
.and_then(|r| r.pane_id.clone());
reconnect_to_session = start_client_impl(
Box::new(os_input),
opts,
config,
config_options,
client,
tab_position_to_focus,
pane_id_to_focus,
is_a_reconnect,
should_create_detached,
);
}
} else {
if let Some(session_name) = opts.session.clone() {
start_client_plan(session_name.clone());
reconnect_to_session = start_client_impl(
Box::new(os_input),
opts,
config,
config_options,
ClientInfo::New(session_name, layout_info, new_session_cwd),
None,
None,
is_a_reconnect,
should_create_detached,
);
} else {
if let Some(session_name) = config_options.session_name.as_ref() {
if let Ok(val) = envs::get_session_name() {
// This prevents the same type of recursion as above, only that here we
// don't get the command to "attach", but to start a new session instead.
// This occurs for example when declaring the session name inside a layout
// file and then, from within this session, trying to open a new zellij
// session with the same layout. This causes an infinite recursion in the
// `zellij_server::terminal_bytes::listen` task, flooding the server and
// clients with infinite `Render` requests.
if *session_name == val {
eprintln!("You are trying to attach to the current session (\"{}\"). Zellij does not support nesting a session in itself.", session_name);
process::exit(1);
}
}
match config_options.attach_to_session {
Some(true) => {
let client = attach_with_session_name(
Some(session_name.clone()),
config_options.clone(),
true,
);
reconnect_to_session = start_client_impl(
Box::new(os_input),
opts,
config,
config_options,
client,
None,
None,
is_a_reconnect,
should_create_detached,
);
},
_ => {
start_client_plan(session_name.clone());
reconnect_to_session = start_client_impl(
Box::new(os_input),
opts,
config,
config_options.clone(),
ClientInfo::New(session_name.clone(), layout_info, new_session_cwd),
None,
None,
is_a_reconnect,
should_create_detached,
);
},
}
if reconnect_to_session.is_some() {
continue;
}
// after we detach, this happens and so we need to exit before the rest of the
// function happens
process::exit(0);
}
let session_name = generate_unique_session_name_or_exit();
start_client_plan(session_name.clone());
reconnect_to_session = start_client_impl(
Box::new(os_input),
opts,
config,
config_options,
ClientInfo::New(session_name, layout_info, new_session_cwd),
None,
None,
is_a_reconnect,
should_create_detached,
);
}
}
if reconnect_to_session.is_none() {
break;
}
}
}
fn generate_unique_session_name_or_exit() -> String {
let Some(unique_session_name) = generate_unique_session_name() else {
eprintln!("Failed to generate a unique session name, giving up");
process::exit(1);
};
unique_session_name
}
pub(crate) fn list_aliases(opts: CliArgs) {
let (config, _layout, _config_options, _config_without_layout, _config_options_without_layout) =
match Setup::from_cli_args(&opts) {
Ok(results) => results,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/src/main.rs | src/main.rs | mod commands;
#[cfg(test)]
mod tests;
use clap::Parser;
use zellij_utils::{
cli::{CliAction, CliArgs, Command, Sessions},
consts::{create_config_and_cache_folders, VERSION},
data::UnblockCondition,
envs,
input::config::Config,
logging::*,
setup::Setup,
shared::web_server_base_url_from_config,
};
fn main() {
configure_logger();
create_config_and_cache_folders();
let opts = CliArgs::parse();
{
let config = Config::try_from(&opts).ok();
if let Some(Command::Sessions(Sessions::Action(cli_action))) = opts.command {
commands::send_action_to_session(cli_action, opts.session, config);
std::process::exit(0);
}
if let Some(Command::Sessions(Sessions::Run {
command,
direction,
cwd,
floating,
in_place,
name,
close_on_exit,
start_suspended,
x,
y,
width,
height,
pinned,
stacked,
blocking,
block_until_exit_success,
block_until_exit_failure,
block_until_exit,
near_current_pane,
})) = opts.command
{
let cwd = cwd.or_else(|| std::env::current_dir().ok());
let skip_plugin_cache = false; // N/A for this action
// Compute the unblock condition
let unblock_condition = if block_until_exit_success {
Some(UnblockCondition::OnExitSuccess)
} else if block_until_exit_failure {
Some(UnblockCondition::OnExitFailure)
} else if block_until_exit {
Some(UnblockCondition::OnAnyExit)
} else {
None
};
let command_cli_action = CliAction::NewPane {
command,
plugin: None,
direction,
cwd,
floating,
in_place,
name,
close_on_exit,
start_suspended,
configuration: None,
skip_plugin_cache,
x,
y,
width,
height,
pinned,
stacked,
blocking,
unblock_condition,
near_current_pane,
};
commands::send_action_to_session(command_cli_action, opts.session, config);
std::process::exit(0);
}
if let Some(Command::Sessions(Sessions::Plugin {
url,
floating,
in_place,
configuration,
skip_plugin_cache,
x,
y,
width,
height,
pinned,
})) = opts.command
{
let cwd = None;
let stacked = false;
let blocking = false;
let unblock_condition = None;
let command_cli_action = CliAction::NewPane {
command: vec![],
plugin: Some(url),
direction: None,
cwd,
floating,
in_place,
name: None,
close_on_exit: false,
start_suspended: false,
configuration,
skip_plugin_cache,
x,
y,
width,
height,
pinned,
stacked,
blocking,
unblock_condition,
near_current_pane: false,
};
commands::send_action_to_session(command_cli_action, opts.session, config);
std::process::exit(0);
}
if let Some(Command::Sessions(Sessions::Edit {
file,
direction,
line_number,
floating,
in_place,
cwd,
x,
y,
width,
height,
pinned,
near_current_pane,
})) = opts.command
{
let mut file = file;
let cwd = cwd.or_else(|| std::env::current_dir().ok());
if file.is_relative() {
if let Some(cwd) = cwd.as_ref() {
file = cwd.join(file);
}
}
let command_cli_action = CliAction::Edit {
file,
direction,
line_number,
floating,
in_place,
cwd,
x,
y,
width,
height,
pinned,
near_current_pane,
};
commands::send_action_to_session(command_cli_action, opts.session, config);
std::process::exit(0);
}
if let Some(Command::Sessions(Sessions::ConvertConfig { old_config_file })) = opts.command {
commands::convert_old_config_file(old_config_file);
std::process::exit(0);
}
if let Some(Command::Sessions(Sessions::ConvertLayout { old_layout_file })) = opts.command {
commands::convert_old_layout_file(old_layout_file);
std::process::exit(0);
}
if let Some(Command::Sessions(Sessions::ConvertTheme { old_theme_file })) = opts.command {
commands::convert_old_theme_file(old_theme_file);
std::process::exit(0);
}
if let Some(Command::Sessions(Sessions::Pipe {
name,
payload,
args,
plugin,
plugin_configuration,
})) = opts.command
{
let command_cli_action = CliAction::Pipe {
name,
payload,
args,
plugin,
plugin_configuration,
force_launch_plugin: false,
skip_plugin_cache: false,
floating_plugin: None,
in_place_plugin: None,
plugin_cwd: None,
plugin_title: None,
};
commands::send_action_to_session(command_cli_action, opts.session, config);
std::process::exit(0);
}
}
if let Some(Command::Sessions(Sessions::ListSessions {
no_formatting,
short,
reverse,
})) = opts.command
{
commands::list_sessions(no_formatting, short, reverse);
} else if let Some(Command::Sessions(Sessions::ListAliases)) = opts.command {
commands::list_aliases(opts);
} else if let Some(Command::Sessions(Sessions::Watch { ref session_name })) = opts.command {
commands::watch_session(session_name.clone(), opts);
} else if let Some(Command::Sessions(Sessions::KillAllSessions { yes })) = opts.command {
commands::kill_all_sessions(yes);
} else if let Some(Command::Sessions(Sessions::KillSession { ref target_session })) =
opts.command
{
commands::kill_session(target_session);
} else if let Some(Command::Sessions(Sessions::DeleteAllSessions { yes, force })) = opts.command
{
commands::delete_all_sessions(yes, force);
} else if let Some(Command::Sessions(Sessions::DeleteSession {
ref target_session,
force,
})) = opts.command
{
commands::delete_session(target_session, force);
} else if let Some(path) = opts.server {
commands::start_server(path, opts.debug);
} else if let Some(layout) = &opts.layout {
if let Some(session_name) = opts
.session
.as_ref()
.cloned()
.or_else(|| envs::get_session_name().ok())
{
let config = Config::try_from(&opts).ok();
let options = Setup::from_cli_args(&opts).ok().map(|r| r.2);
let new_layout_cli_action = CliAction::NewTab {
layout: Some(layout.clone()),
layout_dir: options.as_ref().and_then(|o| o.layout_dir.clone()),
name: None,
cwd: options.as_ref().and_then(|o| o.default_cwd.clone()),
initial_command: vec![],
initial_plugin: None,
close_on_exit: Default::default(),
start_suspended: Default::default(),
block_until_exit_success: false,
block_until_exit_failure: false,
block_until_exit: false,
};
commands::send_action_to_session(new_layout_cli_action, Some(session_name), config);
} else {
commands::start_client(opts);
}
} else if let Some(layout_for_new_session) = &opts.new_session_with_layout {
let mut opts = opts.clone();
opts.new_session_with_layout = None;
opts.layout = Some(layout_for_new_session.clone());
commands::start_client(opts);
} else if let Some(Command::Web(web_opts)) = &opts.command {
if web_opts.get_start() {
let daemonize = web_opts.daemonize;
commands::start_web_server(
opts.clone(),
daemonize,
web_opts.ip,
web_opts.port,
web_opts.cert.clone(),
web_opts.key.clone(),
);
} else if web_opts.stop {
match commands::stop_web_server() {
Ok(()) => {
println!("Stopped web server.");
},
Err(e) => {
eprintln!("Failed to stop web server: {}", e);
std::process::exit(2)
},
}
} else if web_opts.status {
let config_options = commands::get_config_options_from_cli_args(&opts)
.expect("Can't find config options");
let web_server_base_url = web_server_base_url_from_config(config_options);
match commands::web_server_status(&web_server_base_url) {
Ok(version) => {
let version = version.trim();
println!(
"Web server online with version: {}. Checked: {}",
version, web_server_base_url
);
if version != VERSION {
println!("");
println!(
"Note: this version differs from the current Zellij version: {}.",
VERSION
);
println!("Consider stopping the server with: zellij web --stop");
println!("And then restarting it with: zellij web --start");
}
},
Err(_e) => {
println!("Web server is offline, checked: {}", web_server_base_url);
},
}
} else if web_opts.create_token {
let read_only = false;
match commands::create_auth_token(web_opts.token_name.clone(), read_only) {
Ok(token_and_name) => {
println!("Created token successfully");
println!("");
println!("{}", token_and_name);
},
Err(e) => {
eprintln!("Failed to create token: {}", e);
std::process::exit(2)
},
}
} else if web_opts.create_read_only_token {
let read_only = true;
match commands::create_auth_token(web_opts.token_name.clone(), read_only) {
Ok(token_and_name) => {
println!("Created token successfully");
println!("");
println!("{}", token_and_name);
},
Err(e) => {
eprintln!("Failed to create token: {}", e);
std::process::exit(2)
},
}
} else if let Some(token_name_to_revoke) = &web_opts.revoke_token {
match commands::revoke_auth_token(token_name_to_revoke) {
Ok(revoked) => {
if revoked {
println!("Successfully revoked token.");
} else {
eprintln!("Token by that name does not exist.");
std::process::exit(2)
}
},
Err(e) => {
eprintln!("Failed to revoke token: {}", e);
std::process::exit(2)
},
}
} else if web_opts.revoke_all_tokens {
match commands::revoke_all_auth_tokens() {
Ok(_) => {
println!("Successfully revoked all auth tokens");
},
Err(e) => {
eprintln!("Failed to revoke all auth tokens: {}", e);
std::process::exit(2)
},
}
} else if web_opts.list_tokens {
match commands::list_auth_tokens() {
Ok(token_list) => {
for item in token_list {
println!("{}", item);
}
},
Err(e) => {
eprintln!("Failed to list tokens: {}", e);
std::process::exit(2)
},
}
}
} else {
commands::start_client(opts);
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/src/tests/mod.rs | src/tests/mod.rs | pub mod e2e;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/src/tests/e2e/mod.rs | src/tests/e2e/mod.rs | pub mod cases;
mod remote_runner;
mod steps;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/src/tests/e2e/steps.rs | src/tests/e2e/steps.rs | use super::cases::{
MOVE_FOCUS_LEFT_IN_NORMAL_MODE, MOVE_TAB_LEFT, MOVE_TAB_RIGHT, NEW_TAB_IN_TAB_MODE,
SECOND_TAB_CONTENT, TAB_MODE,
};
use super::remote_runner::{RemoteTerminal, Step};
pub fn new_tab() -> Step {
Step {
name: "Open new tab",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() {
remote_terminal.send_key(&TAB_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&NEW_TAB_IN_TAB_MODE);
step_is_complete = true;
}
step_is_complete
},
}
}
pub fn check_second_tab_opened() -> Step {
Step {
name: "Check second tab opened",
instruction: |remote_terminal: RemoteTerminal| -> bool {
remote_terminal.status_bar_appears() && remote_terminal.snapshot_contains("Tab #2")
},
}
}
pub fn move_tab_left() -> Step {
Step {
name: "Move tab left",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() {
remote_terminal.send_key(&MOVE_TAB_LEFT);
std::thread::sleep(std::time::Duration::from_millis(100));
step_is_complete = true;
}
step_is_complete
},
}
}
pub fn check_third_tab_moved_left() -> Step {
Step {
name: "Check third tab is in the middle",
instruction: |remote_terminal: RemoteTerminal| -> bool {
remote_terminal.status_bar_appears()
&& remote_terminal.snapshot_contains("Tab #1 Tab #3 Tab #2")
},
}
}
pub fn type_second_tab_content() -> Step {
Step {
name: "Type second tab content",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() {
remote_terminal.send_key(&SECOND_TAB_CONTENT);
step_is_complete = true;
}
step_is_complete
},
}
}
pub fn check_third_tab_opened() -> Step {
Step {
name: "Check third tab opened",
instruction: |remote_terminal: RemoteTerminal| -> bool {
remote_terminal.status_bar_appears() && remote_terminal.snapshot_contains("Tab #3")
},
}
}
pub fn switch_focus_to_left_tab() -> Step {
Step {
name: "Move focus to tab on the left",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() {
remote_terminal.send_key(&MOVE_FOCUS_LEFT_IN_NORMAL_MODE);
step_is_complete = true;
}
step_is_complete
},
}
}
pub fn check_focus_on_second_tab() -> Step {
Step {
name: "Check focus is on the second tab",
instruction: |remote_terminal: RemoteTerminal| -> bool {
remote_terminal.status_bar_appears()
&& remote_terminal.snapshot_contains("Tab #2 content")
},
}
}
pub fn move_tab_right() -> Step {
Step {
name: "Move tab right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() {
remote_terminal.send_key(&MOVE_TAB_RIGHT);
step_is_complete = true;
}
step_is_complete
},
}
}
pub fn check_third_tab_moved_to_beginning() -> Step {
Step {
name: "Check third tab moved to beginning",
instruction: |remote_terminal: RemoteTerminal| -> bool {
remote_terminal.status_bar_appears()
&& remote_terminal.snapshot_contains("Tab #3 Tab #1 Tab #2")
},
}
}
pub fn check_third_tab_is_left_wrapped() -> Step {
Step {
name: "Check third tab is in last position",
instruction: |remote_terminal: RemoteTerminal| -> bool {
remote_terminal.status_bar_appears()
&& remote_terminal.snapshot_contains("Tab #2 Tab #1 Tab #3")
},
}
}
pub fn check_third_tab_is_right_wrapped() -> Step {
Step {
name: "Check third tab is in last position",
instruction: |remote_terminal: RemoteTerminal| -> bool {
remote_terminal.status_bar_appears()
&& remote_terminal.snapshot_contains("Tab #3 Tab #2 Tab #1")
},
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/src/tests/e2e/remote_runner.rs | src/tests/e2e/remote_runner.rs | use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use vte;
use zellij_server::panes::sixel::SixelImageStore;
use zellij_server::panes::{LinkHandler, TerminalPane};
use zellij_utils::data::{Palette, Style};
use zellij_utils::pane_size::{Dimension, PaneGeom, Size, SizeInPixels};
use ssh2::Session;
use std::io::prelude::*;
use std::net::TcpStream;
use std::path::Path;
use std::cell::RefCell;
use std::rc::Rc;
const ZELLIJ_EXECUTABLE_LOCATION: &str = "/usr/src/zellij/x86_64-unknown-linux-musl/release/zellij";
const SET_ENV_VARIABLES: &str = "EDITOR=/usr/bin/vi";
const ZELLIJ_CONFIG_PATH: &str = "/usr/src/zellij/fixtures/configs";
const ZELLIJ_DATA_DIR: &str = "/usr/src/zellij/e2e-data";
const ZELLIJ_FIXTURE_PATH: &str = "/usr/src/zellij/fixtures";
const CONNECTION_STRING: &str = "127.0.0.1:2222";
const CONNECTION_USERNAME: &str = "test";
const CONNECTION_PASSWORD: &str = "test";
const SESSION_NAME: &str = "e2e-test";
const RETRIES: usize = 10;
fn ssh_connect() -> ssh2::Session {
let tcp = TcpStream::connect(CONNECTION_STRING).unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake().unwrap();
sess.userauth_password(CONNECTION_USERNAME, CONNECTION_PASSWORD)
.unwrap();
sess
}
fn ssh_connect_without_timeout() -> ssh2::Session {
let tcp = TcpStream::connect(CONNECTION_STRING).unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake().unwrap();
sess.userauth_password(CONNECTION_USERNAME, CONNECTION_PASSWORD)
.unwrap();
sess
}
fn setup_remote_environment(channel: &mut ssh2::Channel, win_size: Size) {
let (columns, rows) = (win_size.cols as u32, win_size.rows as u32);
channel
.request_pty("xterm", None, Some((columns, rows, 0, 0)))
.unwrap();
channel.shell().unwrap();
channel.write_all(b"export PS1=\"$ \"\n").unwrap();
channel.flush().unwrap();
}
fn stop_zellij(channel: &mut ssh2::Channel) {
// here we remove the status-bar-tips cache to make sure only the quicknav tip is loaded
channel
.write_all(b"find /tmp | grep status-bar-tips | xargs rm\n")
.unwrap();
channel.write_all(b"killall -KILL zellij\n").unwrap();
channel.write_all(b"rm -rf /tmp/*\n").unwrap(); // remove temporary artifacts from previous
// tests
channel.write_all(b"rm -rf /tmp/*\n").unwrap(); // remove temporary artifacts from previous
channel.write_all(b"rm -rf /tmp/*\n").unwrap(); // remove temporary artifacts from previous
channel
.write_all(b"rm -rf ~/.cache/zellij/*/session_info\n")
.unwrap();
channel
.write_all(b"rm -rf ~/.cache/zellij/permissions.kdl\n")
.unwrap();
}
fn start_zellij(channel: &mut ssh2::Channel) {
stop_zellij(channel);
channel
.write_all(
format!(
"{} {} --session {} --data-dir {} options --show-release-notes false --show-startup-tips false\n",
SET_ENV_VARIABLES, ZELLIJ_EXECUTABLE_LOCATION, SESSION_NAME, ZELLIJ_DATA_DIR
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn start_zellij_mirrored_session(channel: &mut ssh2::Channel) {
stop_zellij(channel);
channel
.write_all(
format!(
"{} {} --session {} --data-dir {} options --show-release-notes false --show-startup-tips false --mirror-session true --serialization-interval 1\n",
SET_ENV_VARIABLES, ZELLIJ_EXECUTABLE_LOCATION, SESSION_NAME, ZELLIJ_DATA_DIR
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn start_zellij_mirrored_session_with_layout(channel: &mut ssh2::Channel, layout_file_name: &str) {
stop_zellij(channel);
channel
.write_all(
format!(
"{} {} --session {} --data-dir {} --new-session-with-layout {} options --show-release-notes false --show-startup-tips false --mirror-session true --serialization-interval 1\n",
SET_ENV_VARIABLES,
ZELLIJ_EXECUTABLE_LOCATION,
SESSION_NAME,
ZELLIJ_DATA_DIR,
format!("{}/{}", ZELLIJ_FIXTURE_PATH, layout_file_name)
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn start_zellij_mirrored_session_with_layout_and_viewport_serialization(
channel: &mut ssh2::Channel,
layout_file_name: &str,
) {
stop_zellij(channel);
channel
.write_all(
format!(
"{} {} --session {} --data-dir {} --new-session-with-layout {} options --show-release-notes false --show-startup-tips false --mirror-session true --serialize-pane-viewport true --serialization-interval 1\n",
SET_ENV_VARIABLES,
ZELLIJ_EXECUTABLE_LOCATION,
SESSION_NAME,
ZELLIJ_DATA_DIR,
format!("{}/{}", ZELLIJ_FIXTURE_PATH, layout_file_name)
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn start_zellij_in_session(channel: &mut ssh2::Channel, session_name: &str, mirrored: bool) {
stop_zellij(channel);
channel
.write_all(
format!(
"{} {} --session {} --data-dir {} options --show-release-notes false --show-startup-tips false --mirror-session {}\n",
SET_ENV_VARIABLES,
ZELLIJ_EXECUTABLE_LOCATION,
session_name,
ZELLIJ_DATA_DIR,
mirrored
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn attach_to_existing_session(channel: &mut ssh2::Channel, session_name: &str) {
channel
.write_all(
format!(
"{} {} attach {}\n",
SET_ENV_VARIABLES, ZELLIJ_EXECUTABLE_LOCATION, session_name
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn watch_existing_session(channel: &mut ssh2::Channel, session_name: &str) {
channel
.write_all(
format!(
"{} {} watch {}\n",
SET_ENV_VARIABLES, ZELLIJ_EXECUTABLE_LOCATION, session_name
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn start_zellij_without_frames(channel: &mut ssh2::Channel) {
stop_zellij(channel);
channel
.write_all(
format!(
"{} {} --session {} --data-dir {} options --show-release-notes false --show-startup-tips false --pane-frames false\n",
SET_ENV_VARIABLES, ZELLIJ_EXECUTABLE_LOCATION, SESSION_NAME, ZELLIJ_DATA_DIR
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn start_zellij_with_config(channel: &mut ssh2::Channel, config_path: &str) {
stop_zellij(channel);
channel
.write_all(
format!(
"{} {} --config {} --session {} --data-dir {} options --show-release-notes false --show-startup-tips false\n",
SET_ENV_VARIABLES,
ZELLIJ_EXECUTABLE_LOCATION,
config_path,
SESSION_NAME,
ZELLIJ_DATA_DIR
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(3)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
fn read_from_channel(
channel: &Arc<Mutex<ssh2::Channel>>,
last_snapshot: &Arc<Mutex<String>>,
cursor_coordinates: &Arc<Mutex<(usize, usize)>>,
pane_geom: &PaneGeom,
) -> (Arc<AtomicBool>, std::thread::JoinHandle<()>) {
let should_keep_running = Arc::new(AtomicBool::new(true));
let thread = std::thread::Builder::new()
.name("read_thread".into())
.spawn({
let pane_geom = *pane_geom;
let should_keep_running = should_keep_running.clone();
let channel = channel.clone();
let last_snapshot = last_snapshot.clone();
let cursor_coordinates = cursor_coordinates.clone();
move || {
let mut retries_left = 3;
let mut should_sleep = false;
let mut vte_parser = vte::Parser::new();
let character_cell_size = Rc::new(RefCell::new(Some(SizeInPixels {
height: 21,
width: 8,
})));
let sixel_image_store = Rc::new(RefCell::new(SixelImageStore::default()));
let debug = false;
let arrow_fonts = true;
let styled_underlines = true;
let explicitly_disable_kitty_keyboard_protocol = false;
let mut terminal_output = TerminalPane::new(
0,
pane_geom,
Style::default(),
0,
String::new(),
Rc::new(RefCell::new(LinkHandler::new())),
character_cell_size,
sixel_image_store,
Rc::new(RefCell::new(Palette::default())),
Rc::new(RefCell::new(HashMap::new())),
None,
None,
debug,
arrow_fonts,
styled_underlines,
explicitly_disable_kitty_keyboard_protocol,
None,
); // 0 is the pane index
loop {
if !should_keep_running.load(Ordering::SeqCst) {
break;
}
if should_sleep {
std::thread::sleep(std::time::Duration::from_millis(100));
should_sleep = false;
}
let mut buf = [0u8; 1280000];
match channel.lock().unwrap().read(&mut buf) {
Ok(0) => {
let current_snapshot = take_snapshot(&mut terminal_output);
let mut last_snapshot = last_snapshot.lock().unwrap();
*cursor_coordinates.lock().unwrap() =
terminal_output.cursor_coordinates().unwrap_or((0, 0));
*last_snapshot = current_snapshot;
should_sleep = true;
},
Ok(count) => {
for byte in buf.iter().take(count) {
vte_parser.advance(&mut terminal_output.grid, *byte);
}
let current_snapshot = take_snapshot(&mut terminal_output);
let mut last_snapshot = last_snapshot.lock().unwrap();
*cursor_coordinates.lock().unwrap() =
terminal_output.grid.cursor_coordinates().unwrap_or((0, 0));
*last_snapshot = current_snapshot;
should_sleep = true;
},
Err(e) => {
if e.kind() == std::io::ErrorKind::WouldBlock {
let current_snapshot = take_snapshot(&mut terminal_output);
let mut last_snapshot = last_snapshot.lock().unwrap();
*cursor_coordinates.lock().unwrap() =
terminal_output.cursor_coordinates().unwrap_or((0, 0));
*last_snapshot = current_snapshot;
should_sleep = true;
} else if retries_left > 0 {
retries_left -= 1;
} else {
break;
}
},
}
}
}
})
.unwrap();
(should_keep_running, thread)
}
pub fn take_snapshot(terminal_output: &mut TerminalPane) -> String {
let output_lines = terminal_output.read_buffer_as_lines();
let cursor_coordinates = terminal_output.cursor_coordinates();
let mut snapshot = String::new();
for (line_index, line) in output_lines.iter().enumerate() {
for (character_index, terminal_character) in line.iter().enumerate() {
if let Some((cursor_x, cursor_y)) = cursor_coordinates {
if line_index == cursor_y && character_index == cursor_x {
snapshot.push('█');
continue;
}
}
snapshot.push(terminal_character.character);
}
if line_index != output_lines.len() - 1 {
snapshot.push('\n');
}
}
snapshot
}
pub struct RemoteTerminal {
channel: Arc<Mutex<ssh2::Channel>>,
cursor_x: usize,
cursor_y: usize,
last_snapshot: Arc<Mutex<String>>,
}
impl std::fmt::Debug for RemoteTerminal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"cursor x: {}\ncursor_y: {}\ncurrent_snapshot:\n{}",
self.cursor_x,
self.cursor_y,
*self.last_snapshot.lock().unwrap()
)
}
}
impl RemoteTerminal {
pub fn cursor_position_is(&self, x: usize, y: usize) -> bool {
x == self.cursor_x && y == self.cursor_y
}
pub fn status_bar_appears(&self) -> bool {
self.last_snapshot.lock().unwrap().contains("Ctrl +")
&& self.last_snapshot.lock().unwrap().contains("LOCK")
}
pub fn ctrl_plus_appears(&self) -> bool {
self.last_snapshot.lock().unwrap().contains("Ctrl +")
}
pub fn tab_bar_appears(&self) -> bool {
self.last_snapshot.lock().unwrap().contains("Tab #1")
}
pub fn snapshot_contains(&self, text: &str) -> bool {
self.last_snapshot.lock().unwrap().contains(text)
}
#[allow(unused)]
pub fn current_snapshot(&self) -> String {
// convenience method for writing tests,
// this should only be used when developing,
// please prefer "snapsht_contains" instead
self.last_snapshot.lock().unwrap().clone()
}
#[allow(unused)]
pub fn current_cursor_position(&self) -> String {
// convenience method for writing tests,
// this should only be used when developing,
// please prefer "cursor_position_is" instead
format!("x: {}, y: {}", self.cursor_x, self.cursor_y)
}
pub fn send_key(&mut self, key: &[u8]) {
let mut channel = self.channel.lock().unwrap();
channel.write_all(key).unwrap();
channel.flush().unwrap();
}
pub fn change_size(&mut self, cols: u32, rows: u32) {
self.channel
.lock()
.unwrap()
.request_pty_size(cols, rows, Some(cols), Some(rows))
.unwrap();
}
pub fn attach_to_original_session(&mut self) {
let mut channel = self.channel.lock().unwrap();
channel
.write_all(
format!("{} attach {}\n", ZELLIJ_EXECUTABLE_LOCATION, SESSION_NAME).as_bytes(),
)
.unwrap();
channel.flush().unwrap();
std::thread::sleep(std::time::Duration::from_secs(1)); // wait until Zellij stops parsing startup ANSI codes from the terminal STDIN
}
pub fn run_zellij_action(&mut self, action_and_arguments: &str) {
let mut channel = self.channel.lock().unwrap();
channel
.write_all(
format!(
"{} action {}",
ZELLIJ_EXECUTABLE_LOCATION, action_and_arguments
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
}
pub fn send_command_through_the_cli(&mut self, command: &str) {
let mut channel = self.channel.lock().unwrap();
channel
.write_all(
// note that this is run with the -s flag that suspends the command on startup
format!("{} run -s -- \"{}\"", ZELLIJ_EXECUTABLE_LOCATION, command).as_bytes(),
)
.unwrap();
channel.flush().unwrap();
}
pub fn send_blocking_command_through_the_cli(&mut self, command: &str) {
let mut channel = self.channel.lock().unwrap();
channel
.write_all(
format!(
"{} run --blocking --floating --close-on-exit -- {}",
ZELLIJ_EXECUTABLE_LOCATION, command
)
.as_bytes(),
)
.unwrap();
channel.flush().unwrap();
}
pub fn path_to_fixture_folder(&self) -> String {
ZELLIJ_FIXTURE_PATH.to_string()
}
pub fn load_fixture(&mut self, name: &str) {
let mut channel = self.channel.lock().unwrap();
channel
.write_all(format!("cat {ZELLIJ_FIXTURE_PATH}/{name}\n").as_bytes())
.unwrap();
channel.flush().unwrap();
}
}
#[derive(Clone)]
pub struct Step {
pub instruction: fn(RemoteTerminal) -> bool,
pub name: &'static str,
}
pub struct RemoteRunner {
steps: Vec<Step>,
current_step_index: usize,
channel: Arc<Mutex<ssh2::Channel>>,
currently_running_step: Option<String>,
retries_left: usize,
retry_pause_ms: usize,
panic_on_no_retries_left: bool,
last_snapshot: Arc<Mutex<String>>,
cursor_coordinates: Arc<Mutex<(usize, usize)>>, // x, y
reader_thread: (Arc<AtomicBool>, std::thread::JoinHandle<()>),
pub test_timed_out: bool,
}
impl RemoteRunner {
pub fn new(win_size: Size) -> Self {
let sess = ssh_connect();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
start_zellij(&mut channel);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn new_mirrored_session(win_size: Size) -> Self {
let sess = ssh_connect();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
start_zellij_mirrored_session(&mut channel);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn new_mirrored_session_with_layout(win_size: Size, layout_file_name: &str) -> Self {
let sess = ssh_connect();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
start_zellij_mirrored_session_with_layout(&mut channel, layout_file_name);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn new_mirrored_session_with_layout_and_viewport_serialization(
win_size: Size,
layout_file_name: &str,
) -> Self {
let sess = ssh_connect();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
start_zellij_mirrored_session_with_layout_and_viewport_serialization(
&mut channel,
layout_file_name,
);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn kill_running_sessions(win_size: Size) {
let sess = ssh_connect();
let mut channel = sess.channel_session().unwrap();
setup_remote_environment(&mut channel, win_size);
start_zellij(&mut channel);
}
pub fn new_with_session_name(win_size: Size, session_name: &str, mirrored: bool) -> Self {
// notice that this method does not have a timeout, so use with caution!
let sess = ssh_connect_without_timeout();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
start_zellij_in_session(&mut channel, session_name, mirrored);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn new_existing_session(win_size: Size, session_name: &str) -> Self {
let sess = ssh_connect_without_timeout();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
attach_to_existing_session(&mut channel, session_name);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn new_watcher_session(win_size: Size, session_name: &str) -> Self {
let sess = ssh_connect_without_timeout();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
watch_existing_session(&mut channel, session_name);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn new_without_frames(win_size: Size) -> Self {
let sess = ssh_connect();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
start_zellij_without_frames(&mut channel);
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn new_with_config(win_size: Size, config_file_name: &'static str) -> Self {
let remote_path = Path::new(ZELLIJ_CONFIG_PATH).join(config_file_name);
let sess = ssh_connect();
let mut channel = sess.channel_session().unwrap();
let mut rows = Dimension::fixed(win_size.rows);
let mut cols = Dimension::fixed(win_size.cols);
rows.set_inner(win_size.rows);
cols.set_inner(win_size.cols);
let pane_geom = PaneGeom {
x: 0,
y: 0,
rows,
cols,
stacked: None,
is_pinned: false,
logical_position: None,
};
setup_remote_environment(&mut channel, win_size);
start_zellij_with_config(&mut channel, &remote_path.to_string_lossy());
let channel = Arc::new(Mutex::new(channel));
let last_snapshot = Arc::new(Mutex::new(String::new()));
let cursor_coordinates = Arc::new(Mutex::new((0, 0)));
sess.set_blocking(false);
let reader_thread =
read_from_channel(&channel, &last_snapshot, &cursor_coordinates, &pane_geom);
RemoteRunner {
steps: vec![],
channel,
currently_running_step: None,
current_step_index: 0,
retries_left: RETRIES,
retry_pause_ms: 100,
test_timed_out: false,
panic_on_no_retries_left: true,
last_snapshot,
cursor_coordinates,
reader_thread,
}
}
pub fn dont_panic(mut self) -> Self {
self.panic_on_no_retries_left = false;
self
}
#[allow(unused)]
pub fn retry_pause_ms(mut self, retry_pause_ms: usize) -> Self {
self.retry_pause_ms = retry_pause_ms;
self
}
pub fn add_step(mut self, step: Step) -> Self {
self.steps.push(step);
self
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/src/tests/e2e/cases.rs | src/tests/e2e/cases.rs | #![allow(unused)]
use ::insta::assert_snapshot;
use zellij_utils::{
pane_size::Size,
position::{Column, Line, Position},
};
use rand::Rng;
use regex::Regex;
use std::fmt::Write;
use std::path::Path;
use crate::tests::e2e::steps::{
check_focus_on_second_tab, check_second_tab_opened, check_third_tab_is_left_wrapped,
check_third_tab_is_right_wrapped, check_third_tab_moved_left,
check_third_tab_moved_to_beginning, check_third_tab_opened, move_tab_left, move_tab_right,
new_tab, switch_focus_to_left_tab, type_second_tab_content,
};
use super::remote_runner::{RemoteRunner, RemoteTerminal, Step};
pub const QUIT: [u8; 1] = [17]; // ctrl-q
pub const ESC: [u8; 1] = [27];
pub const ENTER: [u8; 2] = [10, 13]; // '\n\r'
pub const SPACE: [u8; 1] = [32];
pub const LOCK_MODE: [u8; 1] = [7]; // ctrl-g
pub const MOVE_FOCUS_LEFT_IN_NORMAL_MODE: [u8; 2] = [27, 104]; // alt-h
pub const MOVE_FOCUS_RIGHT_IN_NORMAL_MODE: [u8; 2] = [27, 108]; // alt-l
pub const PANE_MODE: [u8; 1] = [16]; // ctrl-p
pub const TMUX_MODE: [u8; 1] = [2]; // ctrl-b
pub const SPAWN_TERMINAL_IN_PANE_MODE: [u8; 1] = [110]; // n
pub const MOVE_FOCUS_IN_PANE_MODE: [u8; 1] = [112]; // p
pub const SPLIT_DOWN_IN_PANE_MODE: [u8; 1] = [100]; // d
pub const SPLIT_RIGHT_IN_PANE_MODE: [u8; 1] = [114]; // r
pub const SPLIT_RIGHT_IN_TMUX_MODE: [u8; 1] = [37]; // %
pub const TOGGLE_ACTIVE_TERMINAL_FULLSCREEN_IN_PANE_MODE: [u8; 1] = [102]; // f
pub const TOGGLE_FLOATING_PANES: [u8; 1] = [119]; // w
pub const CLOSE_PANE_IN_PANE_MODE: [u8; 1] = [120]; // x
pub const MOVE_FOCUS_DOWN_IN_PANE_MODE: [u8; 1] = [106]; // j
pub const MOVE_FOCUS_UP_IN_PANE_MODE: [u8; 1] = [107]; // k
pub const MOVE_FOCUS_LEFT_IN_PANE_MODE: [u8; 1] = [104]; // h
pub const MOVE_FOCUS_RIGHT_IN_PANE_MODE: [u8; 1] = [108]; // l
pub const RENAME_PANE_MODE: [u8; 1] = [99]; // c
pub const SCROLL_MODE: [u8; 1] = [19]; // ctrl-s
pub const SCROLL_UP_IN_SCROLL_MODE: [u8; 1] = [107]; // k
pub const SCROLL_DOWN_IN_SCROLL_MODE: [u8; 1] = [106]; // j
pub const SCROLL_PAGE_UP_IN_SCROLL_MODE: [u8; 1] = [2]; // ctrl-b
pub const SCROLL_PAGE_DOWN_IN_SCROLL_MODE: [u8; 1] = [6]; // ctrl-f
pub const EDIT_SCROLLBACK: [u8; 1] = [101]; // e
pub const RESIZE_MODE: [u8; 1] = [14]; // ctrl-n
pub const RESIZE_DOWN_IN_RESIZE_MODE: [u8; 1] = [106]; // j
pub const RESIZE_UP_IN_RESIZE_MODE: [u8; 1] = [107]; // k
pub const RESIZE_LEFT_IN_RESIZE_MODE: [u8; 1] = [104]; // h
pub const RESIZE_RIGHT_IN_RESIZE_MODE: [u8; 1] = [108]; // l
pub const TAB_MODE: [u8; 1] = [20]; // ctrl-t
pub const NEW_TAB_IN_TAB_MODE: [u8; 1] = [110]; // n
pub const SWITCH_NEXT_TAB_IN_TAB_MODE: [u8; 1] = [108]; // l
pub const SWITCH_PREV_TAB_IN_TAB_MODE: [u8; 1] = [104]; // h
pub const CLOSE_TAB_IN_TAB_MODE: [u8; 1] = [120]; // x
pub const RENAME_TAB_MODE: [u8; 1] = [114]; // r
pub const MOVE_TAB_LEFT: [u8; 2] = [27, 105]; // Alt + i
pub const MOVE_TAB_RIGHT: [u8; 2] = [27, 111]; // Alt + o
pub const SESSION_MODE: [u8; 1] = [15]; // ctrl-o
pub const DETACH_IN_SESSION_MODE: [u8; 1] = [100]; // d
pub const BRACKETED_PASTE_START: [u8; 6] = [27, 91, 50, 48, 48, 126]; // \u{1b}[200~
pub const BRACKETED_PASTE_END: [u8; 6] = [27, 91, 50, 48, 49, 126]; // \u{1b}[201
pub const SLEEP: [u8; 0] = [];
pub const SECOND_TAB_CONTENT: [u8; 14] =
[84, 97, 98, 32, 35, 50, 32, 99, 111, 110, 116, 101, 110, 116]; // Tab #2 content
pub fn sgr_mouse_report(position: Position, button: u8) -> Vec<u8> {
// button: (release is with lower case m, not supported here yet)
// 0 => left click
// 2 => right click
// 64 => scroll up
// 65 => scroll down
let Position { line, column } = position;
format!("\u{1b}[<{};{};{}M", button, column.0, line.0)
.as_bytes()
.to_vec()
}
// what we do here is adjust snapshots for various race conditions that should hopefully be
// temporary until we can fix them - when adding stuff here, please add a detailed comment
// explaining the race condition and what needs to be done to solve it
fn account_for_races_in_snapshot(snapshot: String) -> String {
// these replacements need to be done because plugins set themselves as "unselectable" at runtime
// when they are loaded - since they are loaded asynchronously, sometimes the "BASE" indication
// (which should only happen if there's more than one selectable pane) is rendered and
// sometimes it isn't - this removes it entirely
//
// to fix this, we should set plugins as unselectable in the layout (before they are loaded),
// once that happens, we should be able to remove this hack (and adjust the snapshots for the
// trailing spaces that we had to get rid of here)
let base_replace = Regex::new(r"Alt <\[\]> BASE \s*\n").unwrap();
let base_replace_tmux_mode_1 = Regex::new(r"Alt \[\|SPACE\|Alt \] BASE \s*\n").unwrap();
let base_replace_tmux_mode_2 = Regex::new(r"Alt \[\|Alt \]\|SPACE BASE \s*\n").unwrap();
let eol_arrow_replace = Regex::new(r"\s*\n").unwrap();
let snapshot = base_replace.replace_all(&snapshot, "\n").to_string();
let snapshot = base_replace_tmux_mode_1
.replace_all(&snapshot, "\n")
.to_string();
let snapshot = base_replace_tmux_mode_2
.replace_all(&snapshot, "\n")
.to_string();
let snapshot = eol_arrow_replace.replace_all(&snapshot, "\n").to_string();
snapshot
}
// All the E2E tests are marked as "ignored" so that they can be run separately from the normal
// tests
#[test]
#[ignore]
pub fn starts_with_one_terminal() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size);
let last_snapshot = runner.take_snapshot_after(Step {
name: "Wait for app to load",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() && remote_terminal.cursor_position_is(3, 2)
{
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
let last_snapshot = account_for_races_in_snapshot(last_snapshot);
assert_snapshot!(last_snapshot);
}
#[test]
#[ignore]
pub fn split_terminals_vertically() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size).add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() && remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SPLIT_RIGHT_IN_PANE_MODE);
// back to normal mode after split
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(Step {
name: "Wait for new pane to appear",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 2) && remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second pane
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
let last_snapshot = account_for_races_in_snapshot(last_snapshot);
assert_snapshot!(last_snapshot);
}
#[test]
#[ignore]
pub fn cannot_split_terminals_vertically_when_active_terminal_is_too_small() {
let fake_win_size = Size { cols: 8, rows: 20 };
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size).add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(3, 2) {
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SPLIT_RIGHT_IN_PANE_MODE);
// back to normal mode after split
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(Step {
name: "Make sure only one pane appears",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(3, 2) {
// ... is the truncated tip line
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
let last_snapshot = account_for_races_in_snapshot(last_snapshot);
assert_snapshot!(last_snapshot);
}
#[test]
#[ignore]
pub fn scrolling_inside_a_pane() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size)
.add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears()
&& remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SPLIT_RIGHT_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
})
.add_step(Step {
name: "Fill terminal with text",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 2)
&& remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second pane
remote_terminal.load_fixture("e2e/scrolling_inside_a_pane");
step_is_complete = true;
}
step_is_complete
},
})
.add_step(Step {
name: "Scroll up inside pane",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 21)
&& remote_terminal.snapshot_contains("line21")
{
// all lines have been written to the pane
remote_terminal.send_key(&SCROLL_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SCROLL_UP_IN_SCROLL_MODE);
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(Step {
name: "Wait for scroll to finish",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 21)
&& remote_terminal.snapshot_contains("line3 ")
&& remote_terminal.snapshot_contains("SCROLL: 1/3")
{
// keyboard scrolls up 1 line, scrollback is 4 lines: cat command + 2 extra lines from fixture + prompt
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
let last_snapshot = account_for_races_in_snapshot(last_snapshot);
assert_snapshot!(last_snapshot);
}
#[test]
#[ignore]
pub fn toggle_pane_fullscreen() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size)
.add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears()
&& remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SPLIT_RIGHT_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
})
.add_step(Step {
name: "Change newly opened pane to be fullscreen",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 2)
&& remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second pane
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&TOGGLE_ACTIVE_TERMINAL_FULLSCREEN_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(Step {
name: "Wait for pane to become fullscreen",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(3, 2)
&& remote_terminal.snapshot_contains("LOCK")
{
// cursor is in full screen pane now
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
let last_snapshot = account_for_races_in_snapshot(last_snapshot);
assert_snapshot!(last_snapshot);
}
#[test]
#[ignore]
pub fn open_new_tab() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size)
.add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears()
&& remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SPLIT_RIGHT_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
})
.add_step(Step {
name: "Open new tab",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 2)
&& remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second pane
remote_terminal.send_key(&TAB_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&NEW_TAB_IN_TAB_MODE);
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(Step {
name: "Wait for new tab to open",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(3, 2)
&& remote_terminal.snapshot_contains("Tab #2")
&& remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second tab
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
let last_snapshot = account_for_races_in_snapshot(last_snapshot);
assert_snapshot!(last_snapshot);
}
#[test]
#[ignore]
pub fn close_tab() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size)
.add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears()
&& remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SPLIT_RIGHT_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
})
.add_step(Step {
name: "Open new tab",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 2)
&& remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second pane
remote_terminal.send_key(&TAB_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&NEW_TAB_IN_TAB_MODE);
step_is_complete = true;
}
step_is_complete
},
})
.add_step(Step {
name: "Close tab",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(3, 2)
&& remote_terminal.snapshot_contains("Tab #2")
&& remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second tab
remote_terminal.send_key(&TAB_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&CLOSE_TAB_IN_TAB_MODE);
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(Step {
name: "Wait for tab to close",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.snapshot_contains("Tab #1")
&& !remote_terminal.snapshot_contains("Tab #2")
{
// cursor is in the first tab again
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
assert!(last_snapshot.contains("Tab #1"));
assert!(!last_snapshot.contains("Tab #2"));
}
#[test]
#[ignore]
pub fn move_tab_to_left() {
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size());
let mut runner = RemoteRunner::new(fake_win_size())
.add_step(new_tab())
.add_step(check_second_tab_opened())
.add_step(new_tab())
.add_step(check_third_tab_opened()) // should have Tab#1 >> Tab#2 >> Tab#3 (focused on Tab#3)
.add_step(move_tab_left()); // now, it should be Tab#1 >> Tab#3 >> Tab#2
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(check_third_tab_moved_left());
if !runner.test_timed_out || test_attempts == 0 {
break last_snapshot;
}
test_attempts -= 1;
};
assert_snapshot!(account_for_races_in_snapshot(last_snapshot));
}
fn fake_win_size() -> Size {
Size {
cols: 120,
rows: 24,
}
}
#[test]
#[ignore]
pub fn move_tab_to_right() {
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size());
let mut runner = RemoteRunner::new(fake_win_size())
.add_step(new_tab())
.add_step(check_second_tab_opened())
.add_step(type_second_tab_content()) // allows verifying the focus later
.add_step(new_tab())
.add_step(check_third_tab_opened())
.add_step(switch_focus_to_left_tab())
.add_step(check_focus_on_second_tab()) // should have Tab#1 >> Tab#2 >> Tab#3 (focused on Tab#2)
.add_step(move_tab_right()); // now, it should be Tab#1 >> Tab#3 >> Tab#2
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(check_third_tab_moved_left());
if !runner.test_timed_out || test_attempts == 0 {
break last_snapshot;
}
test_attempts -= 1;
};
assert_snapshot!(account_for_races_in_snapshot(last_snapshot));
}
#[test]
#[ignore]
pub fn move_tab_to_left_until_it_wraps_around() {
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size());
let mut runner = RemoteRunner::new(fake_win_size())
.add_step(new_tab())
.add_step(check_second_tab_opened())
.add_step(new_tab())
.add_step(check_third_tab_opened())
.add_step(move_tab_left())
.add_step(check_third_tab_moved_left())
.add_step(move_tab_left())
.add_step(check_third_tab_moved_to_beginning()) // should have Tab#3 >> Tab#1 >> Tab#2 (focused on Tab#3)
.add_step(move_tab_left()); // now, it should be Tab#2 >> Tab#1 >> Tab#3
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(check_third_tab_is_left_wrapped());
if !runner.test_timed_out || test_attempts == 0 {
break last_snapshot;
}
test_attempts -= 1;
};
assert_snapshot!(account_for_races_in_snapshot(last_snapshot));
}
#[test]
#[ignore]
pub fn move_tab_to_right_until_it_wraps_around() {
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size());
let mut runner = RemoteRunner::new(fake_win_size())
.add_step(new_tab())
.add_step(check_second_tab_opened())
.add_step(new_tab())
.add_step(check_third_tab_opened()) // should have Tab#1 >> Tab#2 >> Tab#3 (focused on Tab#3)
.add_step(move_tab_right()); // now, it should be Tab#3 >> Tab#2 >> Tab#1
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(check_third_tab_is_right_wrapped());
if !runner.test_timed_out || test_attempts == 0 {
break last_snapshot;
}
test_attempts -= 1;
};
assert_snapshot!(account_for_races_in_snapshot(last_snapshot));
}
#[test]
#[ignore]
pub fn close_pane() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size)
.add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears()
&& remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&SPLIT_RIGHT_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
})
.add_step(Step {
name: "Close pane",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(63, 2)
&& remote_terminal.status_bar_appears()
{
// cursor is in the newly opened second pane
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&CLOSE_PANE_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
let last_snapshot = runner.take_snapshot_after(Step {
name: "Wait for pane to close",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.cursor_position_is(3, 2) && remote_terminal.status_bar_appears()
{
// cursor is in the original pane
step_is_complete = true;
}
step_is_complete
},
});
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
} else {
break last_snapshot;
}
};
let last_snapshot = account_for_races_in_snapshot(last_snapshot);
assert_snapshot!(last_snapshot);
}
#[test]
#[ignore]
pub fn exit_zellij() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size).add_step(Step {
name: "Wait for app to load",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() && remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&QUIT);
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
runner.take_snapshot_after(Step {
name: "Wait for app to exit",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if !remote_terminal.status_bar_appears()
&& remote_terminal.snapshot_contains("Bye from Zellij!")
{
step_is_complete = true;
}
step_is_complete
},
})
};
assert!(last_snapshot.contains("Bye from Zellij!"));
}
#[test]
#[ignore]
pub fn closing_last_pane_exits_zellij() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size).add_step(Step {
name: "Close pane",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears() && remote_terminal.cursor_position_is(3, 2)
{
remote_terminal.send_key(&PANE_MODE);
std::thread::sleep(std::time::Duration::from_millis(100));
remote_terminal.send_key(&CLOSE_PANE_IN_PANE_MODE);
step_is_complete = true;
}
step_is_complete
},
});
runner.run_all_steps();
if runner.test_timed_out && test_attempts > 0 {
test_attempts -= 1;
continue;
}
break runner.take_snapshot_after(Step {
name: "Wait for app to exit",
instruction: |remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.snapshot_contains("Bye from Zellij!") {
step_is_complete = true;
}
step_is_complete
},
});
};
assert!(last_snapshot.contains("Bye from Zellij!"));
}
#[test]
#[ignore]
pub fn typing_exit_closes_pane() {
let fake_win_size = Size {
cols: 120,
rows: 24,
};
let mut test_attempts = 10;
let last_snapshot = loop {
RemoteRunner::kill_running_sessions(fake_win_size);
let mut runner = RemoteRunner::new(fake_win_size)
.add_step(Step {
name: "Split pane to the right",
instruction: |mut remote_terminal: RemoteTerminal| -> bool {
let mut step_is_complete = false;
if remote_terminal.status_bar_appears()
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/prelude.rs | zellij-tile/src/prelude.rs | pub use crate::shim::*;
pub use crate::*;
pub use zellij_utils::consts::VERSION;
pub use zellij_utils::data::*;
pub use zellij_utils::errors::prelude::*;
pub use zellij_utils::input::actions;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/lib.rs | zellij-tile/src/lib.rs | //! The zellij-tile crate acts as the Rust API for developing plugins for Zellij.
//!
//! To read more about Zellij plugins:
//! [https://zellij.dev/documentation/plugins](https://zellij.dev/documentation/plugins)
//!
//! ### Interesting things in this libary:
//! - The [`ZellijPlugin`] trait for implementing plugins combined with the
//! [`register_plugin!`](register_plugin) macro to register them.
//! - The list of [commands](shim) representing what a plugin can do.
//! - The list of [`Events`](prelude::Event) a plugin can subscribe to
//! - The [`ZellijWorker`] trait for implementing background workers combined with the
//! [`register_worker!`](register_worker) macro to register them
//!
//! ### Full Example and Development Environment
//! For a working plugin example as well as a development environment, please see:
//! [https://github.com/zellij-org/rust-plugin-example](https://github.com/zellij-org/rust-plugin-example)
//!
pub mod prelude;
pub mod shim;
pub mod ui_components;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use zellij_utils::data::{Event, PipeMessage};
// use zellij_tile::shim::plugin_api::event::ProtobufEvent;
/// This trait should be implemented - once per plugin - on a struct (normally representing the
/// plugin state). This struct should then be registered with the
/// [`register_plugin!`](register_plugin) macro.
#[allow(unused_variables)]
pub trait ZellijPlugin: Default {
/// Will be called when the plugin is loaded, this is a good place to [`subscribe`](shim::subscribe) to events that are interesting for this plugin.
fn load(&mut self, configuration: BTreeMap<String, String>) {}
/// Will be called with an [`Event`](prelude::Event) if the plugin is subscribed to said event.
/// If the plugin returns `true` from this function, Zellij will know it should be rendered and call its `render` function.
fn update(&mut self, event: Event) -> bool {
false
} // return true if it should render
/// Will be called when data is being piped to the plugin, a PipeMessage.payload of None signifies the pipe
/// has ended
/// If the plugin returns `true` from this function, Zellij will know it should be rendered and call its `render` function.
fn pipe(&mut self, pipe_message: PipeMessage) -> bool {
false
} // return true if it should render
/// Will be called either after an `update` that requested it, or when the plugin otherwise needs to be re-rendered (eg. on startup, or when the plugin is resized).
/// The `rows` and `cols` values represent the "content size" of the plugin (this will not include its surrounding frame if the user has pane frames enabled).
fn render(&mut self, rows: usize, cols: usize) {}
}
/// This trait is used to create workers. Workers can be used by plugins to run longer running
/// background tasks without blocking their own rendering (eg. and showing some sort of loading
/// indication in part of the UI as needed while waiting for the task to complete).
///
/// ## Starting workers on plugin load
/// Implement this trait on a struct (typically representing the worker state) and register it with
/// the [`register_worker!`](register_worker) macro.
///
/// ## Sending messages to workers and back to the plugin
/// Send messages to workers with the [`post_message_to`](shim::post_message_to) method.
/// Send messages from workers back to plugins with the
/// [`post_message_to_plugin`](shim::post_message_to_plugin) method (but be sure the plugin has
/// [`subscribe`](shim::subscribe)d to the [`CustomMessage`](prelude::Event::CustomMessage)) event
/// first!
#[allow(unused_variables)]
pub trait ZellijWorker<'de>: Default + Serialize + Deserialize<'de> {
/// Triggered whenever the plugin sends the worker a message using the
/// [`post_message_to`](shim::post_message_to) method.
fn on_message(&mut self, message: String, payload: String) {}
}
pub const PLUGIN_MISMATCH: &str =
"An error occured in a plugin while receiving an Event from zellij. This means
that the plugins aren't compatible with the current zellij version.
The most likely explanation for this is that you're running either a
self-compiled zellij or plugin version. Please make sure that, while developing,
you also rebuild the plugins in order to pick up changes to the plugin code.
Please refer to the documentation for further information:
https://github.com/zellij-org/zellij/blob/main/CONTRIBUTING.md#building
";
/// Used to register a plugin implementing the [`ZellijPlugin`] trait.
///
/// eg.
/// ```rust
/// use zellij_tile::prelude::*;
///
/// #[derive(Default)]
/// pub struct MyPlugin {}
///
/// impl ZellijPlugin for MyPlugin {
/// // ...
/// }
///
/// register_plugin!(MyPlugin);
/// ```
#[macro_export]
macro_rules! register_plugin {
($t:ty) => {
thread_local! {
static STATE: std::cell::RefCell<$t> = std::cell::RefCell::new(Default::default());
}
fn main() {
// Register custom panic handler
std::panic::set_hook(Box::new(|info| {
report_panic(info);
}));
}
#[no_mangle]
fn load() {
STATE.with(|state| {
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::convert::TryInto;
use zellij_tile::shim::plugin_api::action::ProtobufPluginConfiguration;
use zellij_tile::shim::prost::Message;
let protobuf_bytes: Vec<u8> = $crate::shim::object_from_stdin().unwrap();
let protobuf_configuration: ProtobufPluginConfiguration =
ProtobufPluginConfiguration::decode(protobuf_bytes.as_slice()).unwrap();
let plugin_configuration: BTreeMap<String, String> =
BTreeMap::try_from(&protobuf_configuration).unwrap();
state.borrow_mut().load(plugin_configuration);
});
}
#[no_mangle]
pub fn update() -> bool {
let err_context = "Failed to deserialize event";
use std::convert::TryInto;
use zellij_tile::shim::plugin_api::event::ProtobufEvent;
use zellij_tile::shim::prost::Message;
STATE.with(|state| {
let protobuf_bytes: Vec<u8> = $crate::shim::object_from_stdin().unwrap();
let protobuf_event: ProtobufEvent =
ProtobufEvent::decode(protobuf_bytes.as_slice()).unwrap();
let event = protobuf_event.try_into().unwrap();
state.borrow_mut().update(event)
})
}
#[no_mangle]
pub fn pipe() -> bool {
let err_context = "Failed to deserialize pipe message";
use std::convert::TryInto;
use zellij_tile::shim::plugin_api::pipe_message::ProtobufPipeMessage;
use zellij_tile::shim::prost::Message;
STATE.with(|state| {
let protobuf_bytes: Vec<u8> = $crate::shim::object_from_stdin().unwrap();
let protobuf_pipe_message: ProtobufPipeMessage =
ProtobufPipeMessage::decode(protobuf_bytes.as_slice()).unwrap();
let pipe_message = protobuf_pipe_message.try_into().unwrap();
state.borrow_mut().pipe(pipe_message)
})
}
#[no_mangle]
pub fn render(rows: i32, cols: i32) {
STATE.with(|state| {
state.borrow_mut().render(rows as usize, cols as usize);
});
}
#[no_mangle]
pub fn plugin_version() {
println!("{}", $crate::prelude::VERSION);
}
};
}
/// Used to register a plugin worker implementing the [`ZellijWorker`] trait.
///
/// eg.
/// ```rust
/// use zellij_tile::prelude::*;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Default, Serialize, Deserialize)]
/// pub struct FileSearchWorker {}
///
/// impl ZellijWorker<'_> for FileSearchWorker {
/// fn on_message(&mut self, message: String, payload: String) {
/// // ...
/// }
/// }
///
/// register_worker!(
/// FileSearchWorker,
/// file_search_worker, // registers the worker as the namespace "file_search"
/// FILE_SEARCH_WORKER // expanded to a static variable in which the worker state it held
/// );
/// ```
#[macro_export]
macro_rules! register_worker {
($worker:ty, $worker_name:ident, $worker_static_name:ident) => {
// persist worker state in memory in a static variable
thread_local! {
static $worker_static_name: std::cell::RefCell<$worker> = std::cell::RefCell::new(Default::default());
}
#[no_mangle]
pub fn $worker_name() {
use zellij_tile::shim::plugin_api::message::ProtobufMessage;
use zellij_tile::shim::prost::Message;
let worker_display_name = std::stringify!($worker_name);
let protobuf_bytes: Vec<u8> = $crate::shim::object_from_stdin()
.unwrap();
let protobuf_message: ProtobufMessage = ProtobufMessage::decode(protobuf_bytes.as_slice())
.unwrap();
let message = protobuf_message.name;
let payload = protobuf_message.payload;
$worker_static_name.with(|worker_instance| {
let mut worker_instance = worker_instance.borrow_mut();
worker_instance.on_message(message, payload);
});
}
};
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/shim.rs | zellij-tile/src/shim.rs | use serde::{de::DeserializeOwned, Serialize};
use std::collections::{BTreeMap, HashSet};
use std::{
io,
path::{Path, PathBuf},
};
use zellij_utils::data::*;
use zellij_utils::errors::prelude::*;
use zellij_utils::input::actions::Action;
pub use zellij_utils::plugin_api;
use zellij_utils::plugin_api::event::ProtobufPaneScrollbackResponse;
use zellij_utils::plugin_api::plugin_command::{
CreateTokenResponse, ListTokensResponse, ProtobufGetPanePidResponse, ProtobufPluginCommand,
RenameWebTokenResponse, RevokeAllWebTokensResponse, RevokeTokenResponse,
};
use zellij_utils::plugin_api::plugin_ids::{ProtobufPluginIds, ProtobufZellijVersion};
pub use super::ui_components::*;
pub use prost::{self, *};
// Subscription Handling
/// Subscribe to a list of [`Event`]s represented by their [`EventType`]s that will then trigger the `update` method
pub fn subscribe(event_types: &[EventType]) {
let event_types: HashSet<EventType> = event_types.iter().cloned().collect();
let plugin_command = PluginCommand::Subscribe(event_types);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Unsubscribe to a list of [`Event`]s represented by their [`EventType`]s.
pub fn unsubscribe(event_types: &[EventType]) {
let event_types: HashSet<EventType> = event_types.iter().cloned().collect();
let plugin_command = PluginCommand::Unsubscribe(event_types);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
// Plugin Settings
/// Sets the plugin as selectable or unselectable to the user. Unselectable plugins might be desired when they do not accept user input.
pub fn set_selectable(selectable: bool) {
let plugin_command = PluginCommand::SetSelectable(selectable);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Shows the cursor at specific coordinates or hides it
///
/// # Arguments
/// * `cursor_position` - None to hide cursor, Some((x, y)) to show at coordinates
pub fn show_cursor(cursor_position: Option<(usize, usize)>) {
let plugin_command = PluginCommand::ShowCursor(cursor_position);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
pub fn request_permission(permissions: &[PermissionType]) {
let plugin_command = PluginCommand::RequestPluginPermissions(permissions.into());
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
// Query Functions
/// Returns the unique Zellij pane ID for the plugin as well as the Zellij process id.
pub fn get_plugin_ids() -> PluginIds {
let plugin_command = PluginCommand::GetPluginIds;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
let protobuf_plugin_ids =
ProtobufPluginIds::decode(bytes_from_stdin().unwrap().as_slice()).unwrap();
PluginIds::try_from(protobuf_plugin_ids).unwrap()
}
/// Returns the version of the running Zellij instance - can be useful to check plugin compatibility
pub fn get_zellij_version() -> String {
let plugin_command = PluginCommand::GetZellijVersion;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
let protobuf_zellij_version =
ProtobufZellijVersion::decode(bytes_from_stdin().unwrap().as_slice()).unwrap();
protobuf_zellij_version.version
}
// Host Functions
/// Open a file in the user's default `$EDITOR` in a new pane
pub fn open_file(file_to_open: FileToOpen, context: BTreeMap<String, String>) {
let plugin_command = PluginCommand::OpenFile(file_to_open, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a file in the user's default `$EDITOR` in a new floating pane
pub fn open_file_floating(
file_to_open: FileToOpen,
coordinates: Option<FloatingPaneCoordinates>,
context: BTreeMap<String, String>,
) {
let plugin_command = PluginCommand::OpenFileFloating(file_to_open, coordinates, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a file in the user's default `$EDITOR`, replacing the focused pane
pub fn open_file_in_place(file_to_open: FileToOpen, context: BTreeMap<String, String>) {
let plugin_command = PluginCommand::OpenFileInPlace(file_to_open, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a file in the user's default `$EDITOR` in a new pane near th eplugin
pub fn open_file_near_plugin(file_to_open: FileToOpen, context: BTreeMap<String, String>) {
let plugin_command = PluginCommand::OpenFileNearPlugin(file_to_open, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a file in the user's default `$EDITOR` in a new floating pane near the plugin
pub fn open_file_floating_near_plugin(
file_to_open: FileToOpen,
coordinates: Option<FloatingPaneCoordinates>,
context: BTreeMap<String, String>,
) {
let plugin_command =
PluginCommand::OpenFileFloatingNearPlugin(file_to_open, coordinates, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a file in the user's default `$EDITOR`, replacing the plugin pane
pub fn open_file_in_place_of_plugin(
file_to_open: FileToOpen,
close_plugin_after_replace: bool,
context: BTreeMap<String, String>,
) {
let plugin_command =
PluginCommand::OpenFileInPlaceOfPlugin(file_to_open, close_plugin_after_replace, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new terminal pane to the specified location on the host filesystem
pub fn open_terminal<P: AsRef<Path>>(path: P) {
let file_to_open = FileToOpen::new(path.as_ref().to_path_buf());
let plugin_command = PluginCommand::OpenTerminal(file_to_open);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new terminal pane to the specified location on the host filesystem
/// This variant is identical to open_terminal, excpet it opens it near the plugin regardless of
/// whether the user was focused on it or not
pub fn open_terminal_near_plugin<P: AsRef<Path>>(path: P) {
let file_to_open = FileToOpen::new(path.as_ref().to_path_buf());
let plugin_command = PluginCommand::OpenTerminalNearPlugin(file_to_open);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new floating terminal pane to the specified location on the host filesystem
pub fn open_terminal_floating<P: AsRef<Path>>(
path: P,
coordinates: Option<FloatingPaneCoordinates>,
) {
let file_to_open = FileToOpen::new(path.as_ref().to_path_buf());
let plugin_command = PluginCommand::OpenTerminalFloating(file_to_open, coordinates);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new floating terminal pane to the specified location on the host filesystem
/// This variant is identical to open_terminal_floating, excpet it opens it near the plugin regardless of
/// whether the user was focused on it or not
pub fn open_terminal_floating_near_plugin<P: AsRef<Path>>(
path: P,
coordinates: Option<FloatingPaneCoordinates>,
) {
let file_to_open = FileToOpen::new(path.as_ref().to_path_buf());
let plugin_command = PluginCommand::OpenTerminalFloatingNearPlugin(file_to_open, coordinates);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new terminal pane to the specified location on the host filesystem, temporarily
/// replacing the focused pane
pub fn open_terminal_in_place<P: AsRef<Path>>(path: P) {
let file_to_open = FileToOpen::new(path.as_ref().to_path_buf());
let plugin_command = PluginCommand::OpenTerminalInPlace(file_to_open);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new terminal pane to the specified location on the host filesystem, temporarily
/// replacing the plugin pane
pub fn open_terminal_in_place_of_plugin<P: AsRef<Path>>(path: P, close_plugin_after_replace: bool) {
let file_to_open = FileToOpen::new(path.as_ref().to_path_buf());
let plugin_command =
PluginCommand::OpenTerminalInPlaceOfPlugin(file_to_open, close_plugin_after_replace);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new command pane with the specified command and args (this sort of pane allows the user to control the command, re-run it and see its exit status through the Zellij UI).
pub fn open_command_pane(command_to_run: CommandToRun, context: BTreeMap<String, String>) {
let plugin_command = PluginCommand::OpenCommandPane(command_to_run, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new command pane with the specified command and args (this sort of pane allows the user to control the command, re-run it and see its exit status through the Zellij UI).
/// This variant is the same as `open_command_pane` except it opens the pane in the same tab as the
/// plugin regardless of whether the user is focused on it
pub fn open_command_pane_near_plugin(
command_to_run: CommandToRun,
context: BTreeMap<String, String>,
) {
let plugin_command = PluginCommand::OpenCommandPaneNearPlugin(command_to_run, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new floating command pane with the specified command and args (this sort of pane allows the user to control the command, re-run it and see its exit status through the Zellij UI).
pub fn open_command_pane_floating(
command_to_run: CommandToRun,
coordinates: Option<FloatingPaneCoordinates>,
context: BTreeMap<String, String>,
) {
let plugin_command =
PluginCommand::OpenCommandPaneFloating(command_to_run, coordinates, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new floating command pane with the specified command and args (this sort of pane allows the user to control the command, re-run it and see its exit status through the Zellij UI).
/// This variant is the same as `open_command_pane_floating` except it opens the pane in the same tab as the
/// plugin regardless of whether the user is focused on it
pub fn open_command_pane_floating_near_plugin(
command_to_run: CommandToRun,
coordinates: Option<FloatingPaneCoordinates>,
context: BTreeMap<String, String>,
) {
let plugin_command =
PluginCommand::OpenCommandPaneFloatingNearPlugin(command_to_run, coordinates, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new in place command pane with the specified command and args (this sort of pane allows the user to control the command, re-run it and see its exit status through the Zellij UI).
pub fn open_command_pane_in_place(command_to_run: CommandToRun, context: BTreeMap<String, String>) {
let plugin_command = PluginCommand::OpenCommandPaneInPlace(command_to_run, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new in place command pane with the specified command and args (this sort of pane allows the user to control the command, re-run it and see its exit status through the Zellij UI).
/// This variant is the same as open_command_pane_in_place, except that it always replaces the
/// plugin pane rather than whichever pane the user is focused on
pub fn open_command_pane_in_place_of_plugin(
command_to_run: CommandToRun,
close_plugin_after_replace: bool,
context: BTreeMap<String, String>,
) {
let plugin_command = PluginCommand::OpenCommandPaneInPlaceOfPlugin(
command_to_run,
close_plugin_after_replace,
context,
);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new hidden (background) command pane with the specified command and args (this sort of pane allows the user to control the command, re-run it and see its exit status through the Zellij UI).
pub fn open_command_pane_background(
command_to_run: CommandToRun,
context: BTreeMap<String, String>,
) {
let plugin_command = PluginCommand::OpenCommandPaneBackground(command_to_run, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Change the focused tab to the specified index (corresponding with the default tab names, to starting at `1`, `0` will be considered as `1`).
pub fn switch_tab_to(tab_idx: u32) {
let plugin_command = PluginCommand::SwitchTabTo(tab_idx);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Set a timeout in seconds (or fractions thereof) after which the plugins [update](./plugin-api-events#update) method will be called with the [`Timer`](./plugin-api-events.md#timer) event.
pub fn set_timeout(secs: f64) {
let plugin_command = PluginCommand::SetTimeout(secs);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
#[doc(hidden)]
pub fn exec_cmd(cmd: &[&str]) {
let plugin_command =
PluginCommand::ExecCmd(cmd.iter().cloned().map(|s| s.to_owned()).collect());
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Run this command in the background on the host machine, optionally being notified of its output
/// if subscribed to the `RunCommandResult` Event
pub fn run_command(cmd: &[&str], context: BTreeMap<String, String>) {
let plugin_command = PluginCommand::RunCommand(
cmd.iter().cloned().map(|s| s.to_owned()).collect(),
BTreeMap::new(),
PathBuf::from("."),
context,
);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Run this command in the background on the host machine, providing environment variables and a
/// cwd. Optionally being notified of its output if subscribed to the `RunCommandResult` Event
pub fn run_command_with_env_variables_and_cwd(
cmd: &[&str],
env_variables: BTreeMap<String, String>,
cwd: PathBuf,
context: BTreeMap<String, String>,
) {
let plugin_command = PluginCommand::RunCommand(
cmd.iter().cloned().map(|s| s.to_owned()).collect(),
env_variables,
cwd,
context,
);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Make a web request, optionally being notified of its output
/// if subscribed to the `WebRequestResult` Event, the context will be returned verbatim in this
/// event and can be used for eg. marking the request_id
pub fn web_request<S: AsRef<str>>(
url: S,
verb: HttpVerb,
headers: BTreeMap<String, String>,
body: Vec<u8>,
context: BTreeMap<String, String>,
) where
S: ToString,
{
let plugin_command = PluginCommand::WebRequest(url.to_string(), verb, headers, body, context);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Hide the plugin pane (suppress it) from the UI
pub fn hide_self() {
let plugin_command = PluginCommand::HideSelf;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Hide the pane (suppress it) with the specified [PaneId] from the UI
pub fn hide_pane_with_id(pane_id: PaneId) {
let plugin_command = PluginCommand::HidePaneWithId(pane_id);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Show the plugin pane (unsuppress it if it is suppressed), focus it and switch to its tab
pub fn show_self(should_float_if_hidden: bool) {
let plugin_command = PluginCommand::ShowSelf(should_float_if_hidden);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Show the pane (unsuppress it if it is suppressed) with the specified [PaneId], focus it and switch to its tab
pub fn show_pane_with_id(pane_id: PaneId, should_float_if_hidden: bool, should_focus_pane: bool) {
let plugin_command =
PluginCommand::ShowPaneWithId(pane_id, should_float_if_hidden, should_focus_pane);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Close this plugin pane
pub fn close_self() {
let plugin_command = PluginCommand::CloseSelf;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Switch to the specified Input Mode (eg. `Normal`, `Tab`, `Pane`)
pub fn switch_to_input_mode(mode: &InputMode) {
let plugin_command = PluginCommand::SwitchToMode(*mode);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Provide a stringified [`layout`](https://zellij.dev/documentation/layouts.html) to be applied to the current session. If the layout has multiple tabs, they will all be opened.
pub fn new_tabs_with_layout(layout: &str) {
let plugin_command = PluginCommand::NewTabsWithLayout(layout.to_owned());
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Provide a LayoutInfo to be applied to the current session in a new tab. If the layout has multiple tabs, they will all be opened.
pub fn new_tabs_with_layout_info(layout_info: LayoutInfo) {
let plugin_command = PluginCommand::NewTabsWithLayoutInfo(layout_info);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Open a new tab with the default layout
pub fn new_tab<S: AsRef<str>>(name: Option<S>, cwd: Option<S>)
where
S: ToString,
{
let name = name.map(|s| s.to_string());
let cwd = cwd.map(|s| s.to_string());
let plugin_command = PluginCommand::NewTab { name, cwd };
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Change focus to the next tab or loop back to the first
pub fn go_to_next_tab() {
let plugin_command = PluginCommand::GoToNextTab;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Change focus to the previous tab or loop back to the last
pub fn go_to_previous_tab() {
let plugin_command = PluginCommand::GoToPreviousTab;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
pub fn report_panic(info: &std::panic::PanicHookInfo) {
let panic_payload = if let Some(s) = info.payload().downcast_ref::<&str>() {
format!("{}", s)
} else {
format!("<NO PAYLOAD>")
};
let panic_stringified = format!("{}\n\r{:#?}", panic_payload, info).replace("\n", "\r\n");
let plugin_command = PluginCommand::ReportPanic(panic_stringified);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Either Increase or Decrease the size of the focused pane
pub fn resize_focused_pane(resize: Resize) {
let plugin_command = PluginCommand::Resize(resize);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Either Increase or Decrease the size of the focused pane in a specified direction (eg. `Left`, `Right`, `Up`, `Down`).
pub fn resize_focused_pane_with_direction(resize: Resize, direction: Direction) {
let resize_strategy = ResizeStrategy {
resize,
direction: Some(direction),
invert_on_boundaries: false,
};
let plugin_command = PluginCommand::ResizeWithDirection(resize_strategy);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Change focus tot he next pane in chronological order
pub fn focus_next_pane() {
let plugin_command = PluginCommand::FocusNextPane;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Change focus to the previous pane in chronological order
pub fn focus_previous_pane() {
let plugin_command = PluginCommand::FocusPreviousPane;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Change the focused pane in the specified direction
pub fn move_focus(direction: Direction) {
let plugin_command = PluginCommand::MoveFocus(direction);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Change the focused pane in the specified direction, if the pane is on the edge of the screen, the next tab is focused (next if right edge, previous if left edge).
pub fn move_focus_or_tab(direction: Direction) {
let plugin_command = PluginCommand::MoveFocusOrTab(direction);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Detach the user from the active session
pub fn detach() {
let plugin_command = PluginCommand::Detach;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Edit the scrollback of the focused pane in the user's default `$EDITOR`
pub fn edit_scrollback() {
let plugin_command = PluginCommand::EditScrollback;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Write bytes to the `STDIN` of the focused pane
pub fn write(bytes: Vec<u8>) {
let plugin_command = PluginCommand::Write(bytes);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Write characters to the `STDIN` of the focused pane
pub fn write_chars(chars: &str) {
let plugin_command = PluginCommand::WriteChars(chars.to_owned());
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Copy arbitrary text to the user's clipboard
///
/// Respects the user's configured clipboard destination (system clipboard or primary selection).
/// Requires the WriteToClipboard permission.
pub fn copy_to_clipboard(text: impl Into<String>) {
let plugin_command = PluginCommand::CopyToClipboard(text.into());
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Focused the previously focused tab (regardless of the tab position)
pub fn toggle_tab() {
let plugin_command = PluginCommand::ToggleTab;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Switch the position of the focused pane with a different pane
pub fn move_pane() {
let plugin_command = PluginCommand::MovePane;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Switch the position of the focused pane with a different pane in the specified direction (eg. `Down`, `Up`, `Left`, `Right`).
pub fn move_pane_with_direction(direction: Direction) {
let plugin_command = PluginCommand::MovePaneWithDirection(direction);
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Clear the scroll buffer of the focused pane
pub fn clear_screen() {
let plugin_command = PluginCommand::ClearScreen;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Scroll the focused pane up 1 line
pub fn scroll_up() {
let plugin_command = PluginCommand::ScrollUp;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Scroll the focused pane down 1 line
pub fn scroll_down() {
let plugin_command = PluginCommand::ScrollDown;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Scroll the focused pane all the way to the top of the scrollbuffer
pub fn scroll_to_top() {
let plugin_command = PluginCommand::ScrollToTop;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Scroll the focused pane all the way to the bottom of the scrollbuffer
pub fn scroll_to_bottom() {
let plugin_command = PluginCommand::ScrollToBottom;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Scroll the focused pane up one page
pub fn page_scroll_up() {
let plugin_command = PluginCommand::PageScrollUp;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Scroll the focused pane down one page
pub fn page_scroll_down() {
let plugin_command = PluginCommand::PageScrollDown;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Toggle the focused pane to be fullscreen or normal sized
pub fn toggle_focus_fullscreen() {
let plugin_command = PluginCommand::ToggleFocusFullscreen;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Toggle the UI pane frames on or off
pub fn toggle_pane_frames() {
let plugin_command = PluginCommand::TogglePaneFrames;
let protobuf_plugin_command: ProtobufPluginCommand = plugin_command.try_into().unwrap();
object_to_stdout(&protobuf_plugin_command.encode_to_vec());
unsafe { host_run_plugin_command() };
}
/// Embed the currently focused pane (make it stop floating) or turn it to a float pane if it is not
pub fn toggle_pane_embed_or_eject() {
let plugin_command = PluginCommand::TogglePaneEmbedOrEject;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/ui_components/table.rs | zellij-tile/src/ui_components/table.rs | use super::Text;
/// render a table with arbitrary data
#[derive(Debug, Clone)]
pub struct Table {
contents: Vec<Vec<Text>>,
}
impl Table {
pub fn new() -> Self {
Table { contents: vec![] }
}
pub fn add_row(mut self, row: Vec<impl ToString>) -> Self {
self.contents
.push(row.iter().map(|c| Text::new(c.to_string())).collect());
self
}
pub fn add_styled_row(mut self, row: Vec<Text>) -> Self {
self.contents.push(row);
self
}
pub fn serialize(&self) -> String {
let columns = self
.contents
.get(0)
.map(|first_row| first_row.len())
.unwrap_or(0);
let rows = self.contents.len();
let contents = self
.contents
.iter()
.flatten()
.map(|t| t.serialize())
.collect::<Vec<_>>()
.join(";");
format!("{};{};{}\u{1b}\\", columns, rows, contents)
}
}
pub fn print_table(table: Table) {
print!("\u{1b}Pztable;{}", table.serialize())
}
pub fn print_table_with_coordinates(
table: Table,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) {
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
print!(
"\u{1b}Pztable;{}/{}/{}/{};{}\u{1b}\\",
x,
y,
width,
height,
table.serialize()
)
}
pub fn serialize_table(table: &Table) -> String {
format!("\u{1b}Pztable;{}", table.serialize())
}
pub fn serialize_table_with_coordinates(
table: &Table,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) -> String {
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
format!(
"\u{1b}Pztable;{}/{}/{}/{};{}\u{1b}\\",
x,
y,
width,
height,
table.serialize()
)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/ui_components/text.rs | zellij-tile/src/ui_components/text.rs | use std::ops::Bound;
use std::ops::RangeBounds;
#[derive(Debug, Default, Clone)]
pub struct Text {
text: String,
selected: bool,
opaque: bool,
indices: Vec<Vec<usize>>,
}
impl Text {
pub fn new<S: AsRef<str>>(content: S) -> Self
where
S: ToString,
{
Text {
text: content.to_string(),
selected: false,
opaque: false,
indices: vec![],
}
}
pub fn selected(mut self) -> Self {
self.selected = true;
self
}
pub fn opaque(mut self) -> Self {
self.opaque = true;
self
}
pub fn dim_indices(mut self, mut indices: Vec<usize>) -> Self {
const DIM_LEVEL: usize = 4;
self.pad_indices(DIM_LEVEL);
self.indices
.get_mut(DIM_LEVEL)
.map(|i| i.append(&mut indices));
self
}
pub fn dim_range<R: RangeBounds<usize>>(mut self, indices: R) -> Self {
const DIM_LEVEL: usize = 4;
self.pad_indices(DIM_LEVEL);
let start = match indices.start_bound() {
Bound::Unbounded => 0,
Bound::Included(s) => *s,
Bound::Excluded(s) => *s,
};
let end = match indices.end_bound() {
Bound::Unbounded => self.text.chars().count(),
Bound::Included(s) => *s + 1,
Bound::Excluded(s) => *s,
};
let indices = (start..end).into_iter();
self.indices
.get_mut(DIM_LEVEL)
.map(|i| i.append(&mut indices.into_iter().collect()));
self
}
pub fn dim_substring<S: AsRef<str>>(mut self, substr: S) -> Self {
let substr = substr.as_ref();
let mut start = 0;
while let Some(pos) = self.text[start..].find(substr) {
let abs_pos = start + pos;
self = self.dim_range(abs_pos..abs_pos + substr.chars().count());
start = abs_pos + substr.len();
}
self
}
pub fn dim_all(self) -> Self {
const DIM_LEVEL: usize = 4;
self.color_range(DIM_LEVEL, ..)
}
pub fn unbold_indices(mut self, mut indices: Vec<usize>) -> Self {
const UNBOLD_LEVEL: usize = 5;
self.pad_indices(UNBOLD_LEVEL);
self.indices
.get_mut(UNBOLD_LEVEL)
.map(|i| i.append(&mut indices));
self
}
pub fn unbold_range<R: RangeBounds<usize>>(mut self, indices: R) -> Self {
const UNBOLD_LEVEL: usize = 5;
self.pad_indices(UNBOLD_LEVEL);
let start = match indices.start_bound() {
Bound::Unbounded => 0,
Bound::Included(s) => *s,
Bound::Excluded(s) => *s,
};
let end = match indices.end_bound() {
Bound::Unbounded => self.text.chars().count(),
Bound::Included(s) => *s + 1,
Bound::Excluded(s) => *s,
};
let indices = (start..end).into_iter();
self.indices
.get_mut(UNBOLD_LEVEL)
.map(|i| i.append(&mut indices.into_iter().collect()));
self
}
pub fn unbold_substring<S: AsRef<str>>(mut self, substr: S) -> Self {
let substr = substr.as_ref();
let mut start = 0;
while let Some(pos) = self.text[start..].find(substr) {
let abs_pos = start + pos;
self = self.unbold_range(abs_pos..abs_pos + substr.chars().count());
start = abs_pos + substr.len();
}
self
}
pub fn unbold_all(self) -> Self {
const UNBOLD_LEVEL: usize = 5;
self.color_range(UNBOLD_LEVEL, ..)
}
pub fn error_color_indices(mut self, mut indices: Vec<usize>) -> Self {
const ERROR_COLOR_LEVEL: usize = 6;
self.pad_indices(ERROR_COLOR_LEVEL);
self.indices
.get_mut(ERROR_COLOR_LEVEL)
.map(|i| i.append(&mut indices));
self
}
pub fn error_color_range<R: RangeBounds<usize>>(mut self, indices: R) -> Self {
const ERROR_COLOR_LEVEL: usize = 6;
self.pad_indices(ERROR_COLOR_LEVEL);
let start = match indices.start_bound() {
Bound::Unbounded => 0,
Bound::Included(s) => *s,
Bound::Excluded(s) => *s,
};
let end = match indices.end_bound() {
Bound::Unbounded => self.text.chars().count(),
Bound::Included(s) => *s + 1,
Bound::Excluded(s) => *s,
};
let indices = (start..end).into_iter();
self.indices
.get_mut(ERROR_COLOR_LEVEL)
.map(|i| i.append(&mut indices.into_iter().collect()));
self
}
pub fn error_color_substring<S: AsRef<str>>(mut self, substr: S) -> Self {
let substr = substr.as_ref();
let mut start = 0;
while let Some(pos) = self.text[start..].find(substr) {
let abs_pos = start + pos;
self = self.error_color_range(abs_pos..abs_pos + substr.chars().count());
start = abs_pos + substr.len();
}
self
}
pub fn error_color_nth_substring<S: AsRef<str>>(
self,
substr: S,
occurrence_index: usize,
) -> Self {
const ERROR_COLOR_LEVEL: usize = 6;
let substr = substr.as_ref();
let mut start = 0;
let mut count = 0;
while let Some(pos) = self.text[start..].find(substr) {
if count == occurrence_index {
let abs_pos = start + pos;
return self.color_range(ERROR_COLOR_LEVEL, abs_pos..abs_pos + substr.len());
}
count += 1;
start = start + pos + substr.len();
}
self
}
pub fn error_color_all(self) -> Self {
const ERROR_COLOR_LEVEL: usize = 6;
self.color_range(ERROR_COLOR_LEVEL, ..)
}
pub fn success_color_indices(mut self, mut indices: Vec<usize>) -> Self {
const SUCCESS_COLOR_LEVEL: usize = 7;
self.pad_indices(SUCCESS_COLOR_LEVEL);
self.indices
.get_mut(SUCCESS_COLOR_LEVEL)
.map(|i| i.append(&mut indices));
self
}
pub fn success_color_range<R: RangeBounds<usize>>(mut self, indices: R) -> Self {
const SUCCESS_COLOR_LEVEL: usize = 7;
self.pad_indices(SUCCESS_COLOR_LEVEL);
let start = match indices.start_bound() {
Bound::Unbounded => 0,
Bound::Included(s) => *s,
Bound::Excluded(s) => *s,
};
let end = match indices.end_bound() {
Bound::Unbounded => self.text.chars().count(),
Bound::Included(s) => *s + 1,
Bound::Excluded(s) => *s,
};
let indices = (start..end).into_iter();
self.indices
.get_mut(SUCCESS_COLOR_LEVEL)
.map(|i| i.append(&mut indices.into_iter().collect()));
self
}
pub fn success_color_substring<S: AsRef<str>>(mut self, substr: S) -> Self {
let substr = substr.as_ref();
let mut start = 0;
while let Some(pos) = self.text[start..].find(substr) {
let abs_pos = start + pos;
self = self.success_color_range(abs_pos..abs_pos + substr.chars().count());
start = abs_pos + substr.len();
}
self
}
pub fn success_color_nth_substring<S: AsRef<str>>(
self,
substr: S,
occurrence_index: usize,
) -> Self {
const SUCCESS_COLOR_LEVEL: usize = 7;
let substr = substr.as_ref();
let mut start = 0;
let mut count = 0;
while let Some(pos) = self.text[start..].find(substr) {
if count == occurrence_index {
let abs_pos = start + pos;
return self.color_range(SUCCESS_COLOR_LEVEL, abs_pos..abs_pos + substr.len());
}
count += 1;
start = start + pos + substr.len();
}
self
}
pub fn success_color_all(self) -> Self {
const SUCCESS_COLOR_LEVEL: usize = 7;
self.color_range(SUCCESS_COLOR_LEVEL, ..)
}
pub fn color_indices(mut self, index_level: usize, mut indices: Vec<usize>) -> Self {
self.pad_indices(index_level);
self.indices
.get_mut(index_level)
.map(|i| i.append(&mut indices));
self
}
pub fn color_range<R: RangeBounds<usize>>(mut self, index_level: usize, indices: R) -> Self {
self.pad_indices(index_level);
let start = match indices.start_bound() {
Bound::Unbounded => 0,
Bound::Included(s) => *s,
Bound::Excluded(s) => *s,
};
let end = match indices.end_bound() {
Bound::Unbounded => self.text.chars().count(),
Bound::Included(s) => *s + 1,
Bound::Excluded(s) => *s,
};
let indices = (start..end).into_iter();
self.indices
.get_mut(index_level)
.map(|i| i.append(&mut indices.into_iter().collect()));
self
}
pub fn color_substring<S: AsRef<str>>(mut self, index_level: usize, substr: S) -> Self {
let substr = substr.as_ref();
let mut start = 0;
while let Some(pos) = self.text[start..].find(substr) {
let abs_pos = start + pos;
let char_start = self.text[..abs_pos].chars().count();
let char_end = char_start + substr.chars().count();
self = self.color_range(index_level, char_start..char_end);
start = abs_pos + substr.len();
}
self
}
pub fn color_all(self, index_level: usize) -> Self {
self.color_range(index_level, ..)
}
pub fn color_nth_substring<S: AsRef<str>>(
self,
index_level: usize,
substr: S,
occurrence_index: usize,
) -> Self {
let substr = substr.as_ref();
let mut start = 0;
let mut count = 0;
while let Some(pos) = self.text[start..].find(substr) {
if count == occurrence_index {
let abs_pos = start + pos;
return self.color_range(index_level, abs_pos..abs_pos + substr.len());
}
count += 1;
start = start + pos + substr.len();
}
self
}
pub fn content(&self) -> &str {
&self.text
}
fn pad_indices(&mut self, index_level: usize) {
if self.indices.get(index_level).is_none() {
for _ in self.indices.len()..=index_level {
self.indices.push(vec![]);
}
}
}
pub fn serialize(&self) -> String {
let text = self
.text
.to_string()
.as_bytes()
.iter()
.map(|b| b.to_string())
.collect::<Vec<_>>()
.join(",");
let mut indices = String::new();
for index_variants in &self.indices {
indices.push_str(&format!(
"{}$",
index_variants
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(",")
));
}
let mut prefix = "".to_owned();
if self.selected {
prefix = format!("x{}", prefix);
}
if self.opaque {
prefix = format!("z{}", prefix);
}
format!("{}{}{}", prefix, indices, text)
}
pub fn len(&self) -> usize {
self.text.chars().count()
}
}
pub fn print_text(text: Text) {
print!("\u{1b}Pztext;{}\u{1b}\\", text.serialize())
}
pub fn print_text_with_coordinates(
text: Text,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) {
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
print!(
"\u{1b}Pztext;{}/{}/{}/{};{}\u{1b}\\",
x,
y,
width,
height,
text.serialize()
)
}
pub fn serialize_text(text: &Text) -> String {
format!("\u{1b}Pztext;{}\u{1b}\\", text.serialize())
}
pub fn serialize_text_with_coordinates(
text: &Text,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) -> String {
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
format!(
"\u{1b}Pztext;{}/{}/{}/{};{}\u{1b}\\",
x,
y,
width,
height,
text.serialize()
)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/ui_components/mod.rs | zellij-tile/src/ui_components/mod.rs | mod nested_list;
mod ribbon;
mod table;
mod text;
pub use prost::{self, *};
pub use zellij_utils::plugin_api;
pub use nested_list::*;
pub use ribbon::*;
pub use table::*;
pub use text::*;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/ui_components/nested_list.rs | zellij-tile/src/ui_components/nested_list.rs | use super::Text;
use std::borrow::Borrow;
use std::ops::RangeBounds;
#[derive(Debug, Default, Clone)]
pub struct NestedListItem {
indentation_level: usize,
content: Text,
}
impl NestedListItem {
pub fn new<S: AsRef<str>>(text: S) -> Self
where
S: ToString,
{
NestedListItem {
content: Text::new(text),
..Default::default()
}
}
pub fn indent(mut self, indentation_level: usize) -> Self {
self.indentation_level = indentation_level;
self
}
pub fn selected(mut self) -> Self {
self.content = self.content.selected();
self
}
pub fn opaque(mut self) -> Self {
self.content = self.content.opaque();
self
}
pub fn color_indices(mut self, index_level: usize, indices: Vec<usize>) -> Self {
self.content = self.content.color_indices(index_level, indices);
self
}
pub fn color_range<R: RangeBounds<usize>>(mut self, index_level: usize, indices: R) -> Self {
self.content = self.content.color_range(index_level, indices);
self
}
pub fn error_color_indices(mut self, indices: Vec<usize>) -> Self {
self.content = self.content.error_color_indices(indices);
self
}
pub fn error_color_range<R: RangeBounds<usize>>(mut self, indices: R) -> Self {
self.content = self.content.error_color_range(indices);
self
}
pub fn error_color_substring<S: AsRef<str>>(mut self, substr: S) -> Self {
self.content = self.content.error_color_substring(substr);
self
}
pub fn error_color_nth_substring<S: AsRef<str>>(
mut self,
substr: S,
occurrence_index: usize,
) -> Self {
self.content = self
.content
.error_color_nth_substring(substr, occurrence_index);
self
}
pub fn error_color_all(mut self) -> Self {
self.content = self.content.error_color_all();
self
}
pub fn success_color_indices(mut self, indices: Vec<usize>) -> Self {
self.content = self.content.success_color_indices(indices);
self
}
pub fn success_color_range<R: RangeBounds<usize>>(mut self, indices: R) -> Self {
self.content = self.content.success_color_range(indices);
self
}
pub fn success_color_substring<S: AsRef<str>>(mut self, substr: S) -> Self {
self.content = self.content.success_color_substring(substr);
self
}
pub fn success_color_nth_substring<S: AsRef<str>>(
mut self,
substr: S,
occurrence_index: usize,
) -> Self {
self.content = self
.content
.success_color_nth_substring(substr, occurrence_index);
self
}
pub fn success_color_all(mut self) -> Self {
self.content = self.content.success_color_all();
self
}
pub fn serialize(&self) -> String {
let mut serialized = String::new();
for _ in 0..self.indentation_level {
serialized.push('|');
}
format!("{}{}", serialized, self.content.serialize())
}
}
/// render a nested list with arbitrary data
pub fn print_nested_list(items: Vec<NestedListItem>) {
let items = items
.into_iter()
.map(|i| i.serialize())
.collect::<Vec<_>>()
.join(";");
print!("\u{1b}Pznested_list;{}\u{1b}\\", items)
}
pub fn print_nested_list_with_coordinates(
items: Vec<NestedListItem>,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) {
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
let items = items
.into_iter()
.map(|i| i.serialize())
.collect::<Vec<_>>()
.join(";");
print!(
"\u{1b}Pznested_list;{}/{}/{}/{};{}\u{1b}\\",
x, y, width, height, items
)
}
pub fn serialize_nested_list<I>(items: I) -> String
where
I: IntoIterator,
I::Item: Borrow<NestedListItem>,
{
let items = items
.into_iter()
.map(|i| i.borrow().serialize())
.collect::<Vec<_>>()
.join(";");
format!("\u{1b}Pznested_list;{}\u{1b}\\", items)
}
pub fn serialize_nested_list_with_coordinates<I>(
items: I,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) -> String
where
I: IntoIterator,
I::Item: Borrow<NestedListItem>,
{
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
let items = items
.into_iter()
.map(|i| i.borrow().serialize())
.collect::<Vec<_>>()
.join(";");
format!(
"\u{1b}Pznested_list;{}/{}/{}/{};{}\u{1b}\\",
x, y, width, height, items
)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-tile/src/ui_components/ribbon.rs | zellij-tile/src/ui_components/ribbon.rs | use super::Text;
use std::borrow::Borrow;
pub fn print_ribbon(text: Text) {
print!("\u{1b}Pzribbon;{}\u{1b}\\", text.serialize());
}
pub fn print_ribbon_with_coordinates(
text: Text,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) {
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
print!(
"\u{1b}Pzribbon;{}/{}/{}/{};{}\u{1b}\\",
x,
y,
width,
height,
text.serialize()
);
}
pub fn serialize_ribbon(text: &Text) -> String {
format!("\u{1b}Pzribbon;{}\u{1b}\\", text.serialize())
}
pub fn serialize_ribbon_with_coordinates(
text: &Text,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) -> String {
let width = width.map(|w| w.to_string()).unwrap_or_default();
let height = height.map(|h| h.to_string()).unwrap_or_default();
format!(
"\u{1b}Pzribbon;{}/{}/{}/{};{}\u{1b}\\",
x,
y,
width,
height,
text.serialize()
)
}
pub fn serialize_ribbon_line<I>(ribbons: I) -> String
where
I: IntoIterator,
I::Item: Borrow<Text>,
{
ribbons
.into_iter()
.map(|r| serialize_ribbon(r.borrow()))
.collect()
}
pub fn serialize_ribbon_line_with_coordinates<I>(
ribbons: I,
x: usize,
y: usize,
width: Option<usize>,
height: Option<usize>,
) -> String
where
I: IntoIterator,
I::Item: Borrow<Text>,
{
let mut ribbons = ribbons.into_iter();
let Some(first) = ribbons.next() else {
return String::new();
};
let mut result = serialize_ribbon_with_coordinates(first.borrow(), x, y, width, height);
result.push_str(&serialize_ribbon_line(ribbons));
result
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/setup.rs | zellij-utils/src/setup.rs | #[cfg(not(target_family = "wasm"))]
use crate::consts::ASSET_MAP;
use crate::input::theme::Themes;
#[allow(unused_imports)]
use crate::{
cli::{CliArgs, Command, SessionCommand, Sessions},
consts::{
FEATURES, SYSTEM_DEFAULT_CONFIG_DIR, SYSTEM_DEFAULT_DATA_DIR_PREFIX, VERSION,
ZELLIJ_CACHE_DIR, ZELLIJ_DEFAULT_THEMES, ZELLIJ_PROJ_DIR,
},
errors::prelude::*,
home::*,
input::{
config::{Config, ConfigError},
layout::Layout,
options::Options,
},
};
use clap::{Args, IntoApp};
use clap_complete::Shell;
use directories::BaseDirs;
use log::info;
use serde::{Deserialize, Serialize};
use std::{
convert::TryFrom,
fmt::Write as FmtWrite,
fs,
io::Write,
path::{Path, PathBuf},
process,
};
const CONFIG_NAME: &str = "config.kdl";
static ARROW_SEPARATOR: &str = "";
#[cfg(not(test))]
/// Goes through a predefined list and checks for an already
/// existing config directory, returns the first match
pub fn find_default_config_dir() -> Option<PathBuf> {
default_config_dirs()
.into_iter()
.filter(|p| p.is_some())
.find(|p| p.clone().unwrap().exists())
.flatten()
}
#[cfg(test)]
pub fn find_default_config_dir() -> Option<PathBuf> {
None
}
/// Order in which config directories are checked
fn default_config_dirs() -> Vec<Option<PathBuf>> {
vec![
home_config_dir(),
Some(xdg_config_dir()),
Some(Path::new(SYSTEM_DEFAULT_CONFIG_DIR).to_path_buf()),
]
}
/// Looks for an existing dir, uses that, else returns a
/// dir matching the config spec.
pub fn get_default_data_dir() -> PathBuf {
[
xdg_data_dir(),
Path::new(SYSTEM_DEFAULT_DATA_DIR_PREFIX).join("share/zellij"),
]
.into_iter()
.find(|p| p.exists())
.unwrap_or_else(xdg_data_dir)
}
#[cfg(not(test))]
pub fn get_default_themes() -> Themes {
let mut themes = Themes::default();
for file in ZELLIJ_DEFAULT_THEMES.files() {
if let Some(content) = file.contents_utf8() {
let sourced_from_external_file = true;
match Themes::from_string(&content.to_string(), sourced_from_external_file) {
Ok(theme) => themes = themes.merge(theme),
Err(_) => {},
}
}
}
themes
}
#[cfg(test)]
pub fn get_default_themes() -> Themes {
Themes::default()
}
pub fn xdg_config_dir() -> PathBuf {
ZELLIJ_PROJ_DIR.config_dir().to_owned()
}
pub fn xdg_data_dir() -> PathBuf {
ZELLIJ_PROJ_DIR.data_dir().to_owned()
}
pub fn home_config_dir() -> Option<PathBuf> {
if let Some(user_dirs) = BaseDirs::new() {
let config_dir = user_dirs.home_dir().join(CONFIG_LOCATION);
Some(config_dir)
} else {
None
}
}
pub fn get_layout_dir(config_dir: Option<PathBuf>) -> Option<PathBuf> {
config_dir.map(|dir| dir.join("layouts"))
}
pub fn get_theme_dir(config_dir: Option<PathBuf>) -> Option<PathBuf> {
config_dir.map(|dir| dir.join("themes"))
}
pub fn dump_asset(asset: &[u8]) -> std::io::Result<()> {
std::io::stdout().write_all(asset)?;
Ok(())
}
pub const DEFAULT_CONFIG: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/config/default.kdl"
));
pub const DEFAULT_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/default.kdl"
));
pub const DEFAULT_SWAP_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/default.swap.kdl"
));
pub const STRIDER_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/strider.kdl"
));
pub const STRIDER_SWAP_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/strider.swap.kdl"
));
pub const NO_STATUS_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/disable-status-bar.kdl"
));
pub const COMPACT_BAR_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/compact.kdl"
));
pub const COMPACT_BAR_SWAP_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/compact.swap.kdl"
));
pub const CLASSIC_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/classic.kdl"
));
pub const CLASSIC_SWAP_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/classic.swap.kdl"
));
pub const WELCOME_LAYOUT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/layouts/welcome.kdl"
));
pub const FISH_EXTRA_COMPLETION: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/completions/comp.fish"
));
pub const BASH_EXTRA_COMPLETION: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/completions/comp.bash"
));
pub const ZSH_EXTRA_COMPLETION: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/completions/comp.zsh"
));
pub const BASH_AUTO_START_SCRIPT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/shell/auto-start.bash"
));
pub const FISH_AUTO_START_SCRIPT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/shell/auto-start.fish"
));
pub const ZSH_AUTO_START_SCRIPT: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/",
"assets/shell/auto-start.zsh"
));
pub fn add_layout_ext(s: &str) -> String {
match s {
c if s.ends_with(".kdl") => c.to_owned(),
_ => {
let mut s = s.to_owned();
s.push_str(".kdl");
s
},
}
}
pub fn dump_default_config() -> std::io::Result<()> {
dump_asset(DEFAULT_CONFIG)
}
pub fn dump_specified_layout(layout: &str) -> std::io::Result<()> {
match layout {
"strider" => dump_asset(STRIDER_LAYOUT),
"default" => dump_asset(DEFAULT_LAYOUT),
"compact" => dump_asset(COMPACT_BAR_LAYOUT),
"disable-status" => dump_asset(NO_STATUS_LAYOUT),
"classic" => dump_asset(CLASSIC_LAYOUT),
custom => {
info!("Dump {custom} layout");
let custom = add_layout_ext(custom);
let home = default_layout_dir();
let path = home.map(|h| h.join(&custom));
let layout_exists = path.as_ref().map(|p| p.exists()).unwrap_or_default();
match (path, layout_exists) {
(Some(path), true) => {
let content = fs::read_to_string(path)?;
std::io::stdout().write_all(content.as_bytes())
},
_ => {
log::error!("No layout named {custom} found");
return Ok(());
},
}
},
}
}
pub fn dump_specified_swap_layout(swap_layout: &str) -> std::io::Result<()> {
match swap_layout {
"strider" => dump_asset(STRIDER_SWAP_LAYOUT),
"default" => dump_asset(DEFAULT_SWAP_LAYOUT),
"compact" => dump_asset(COMPACT_BAR_SWAP_LAYOUT),
"classic" => dump_asset(CLASSIC_SWAP_LAYOUT),
not_found => Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("Swap Layout not found for: {}", not_found),
)),
}
}
#[cfg(not(target_family = "wasm"))]
pub fn dump_builtin_plugins(path: &PathBuf) -> Result<()> {
for (asset_path, bytes) in ASSET_MAP.iter() {
let plugin_path = path.join(asset_path);
plugin_path
.parent()
.with_context(|| {
format!(
"failed to acquire parent path of '{}'",
plugin_path.display()
)
})
.and_then(|parent_path| {
std::fs::create_dir_all(parent_path).context("failed to create parent path")
})
.with_context(|| {
format!(
"failed to create folder '{}' to dump plugin '{}' to",
path.display(),
plugin_path.display()
)
})?;
std::fs::write(plugin_path, bytes)
.with_context(|| format!("failed to dump builtin plugin '{}'", asset_path.display()))?;
}
Ok(())
}
#[cfg(target_family = "wasm")]
pub fn dump_builtin_plugins(_path: &PathBuf) -> Result<()> {
Ok(())
}
#[derive(Debug, Default, Clone, Args, Serialize, Deserialize)]
pub struct Setup {
/// Dump the default configuration file to stdout
#[clap(long, value_parser)]
pub dump_config: bool,
/// Disables loading of configuration file at default location,
/// loads the defaults that zellij ships with
#[clap(long, value_parser)]
pub clean: bool,
/// Checks the configuration of zellij and displays
/// currently used directories
#[clap(long, value_parser)]
pub check: bool,
/// Dump specified layout to stdout
#[clap(long, value_parser)]
pub dump_layout: Option<String>,
/// Dump the specified swap layout file to stdout
#[clap(long, value_parser)]
pub dump_swap_layout: Option<String>,
/// Dump the builtin plugins to DIR or "DATA DIR" if unspecified
#[clap(
long,
value_name = "DIR",
value_parser,
exclusive = true,
min_values = 0,
max_values = 1
)]
pub dump_plugins: Option<Option<PathBuf>>,
/// Generates completion for the specified shell
#[clap(long, value_name = "SHELL", value_parser)]
pub generate_completion: Option<String>,
/// Generates auto-start script for the specified shell
#[clap(long, value_name = "SHELL", value_parser)]
pub generate_auto_start: Option<String>,
}
impl Setup {
/// Entrypoint from main
/// Merges options from the config file and the command line options
/// into `[Options]`, the command line options superceeding the layout
/// file options, superceeding the config file options:
/// 1. command line options (`zellij options`)
/// 2. layout options
/// (`layout.kdl` / `zellij --layout`)
/// 3. config options (`config.kdl`)
pub fn from_cli_args(
cli_args: &CliArgs,
) -> Result<(Config, Layout, Options, Config, Options), ConfigError> {
// note that this can potentially exit the process
Setup::handle_setup_commands(cli_args);
let config = Config::try_from(cli_args)?;
let cli_config_options: Option<Options> =
if let Some(Command::Options(options)) = cli_args.command.clone() {
Some(options.into())
} else {
None
};
// the attach CLI command can also have its own Options, we need to merge them if they
// exist
let cli_config_options = merge_attach_command_options(cli_config_options, &cli_args);
let mut config_without_layout = config.clone();
let (layout, mut config) =
Setup::parse_layout_and_override_config(cli_config_options.as_ref(), config, cli_args)?;
let config_options =
apply_themes_to_config(&mut config, cli_config_options.clone(), cli_args)?;
let config_options_without_layout =
apply_themes_to_config(&mut config_without_layout, cli_config_options, cli_args)?;
fn apply_themes_to_config(
config: &mut Config,
cli_config_options: Option<Options>,
cli_args: &CliArgs,
) -> Result<Options, ConfigError> {
let config_options = match cli_config_options {
Some(cli_config_options) => config.options.merge(cli_config_options),
None => config.options.clone(),
};
config.themes = config.themes.merge(get_default_themes());
let user_theme_dir = config_options.theme_dir.clone().or_else(|| {
get_theme_dir(cli_args.config_dir.clone().or_else(find_default_config_dir))
.filter(|dir| dir.exists())
});
if let Some(user_theme_dir) = user_theme_dir {
config.themes = config.themes.merge(Themes::from_dir(user_theme_dir)?);
}
Ok(config_options)
}
if let Some(Command::Setup(ref setup)) = &cli_args.command {
setup
.from_cli_with_options(cli_args, &config_options)
.map_or_else(
|e| {
eprintln!("{:?}", e);
process::exit(1);
},
|_| {},
);
};
Ok((
config,
layout,
config_options,
config_without_layout,
config_options_without_layout,
))
}
/// General setup helpers
pub fn from_cli(&self) -> Result<()> {
if self.clean {
return Ok(());
}
if self.dump_config {
dump_default_config()?;
std::process::exit(0);
}
if let Some(shell) = &self.generate_completion {
Self::generate_completion(shell);
std::process::exit(0);
}
if let Some(shell) = &self.generate_auto_start {
Self::generate_auto_start(shell);
std::process::exit(0);
}
if let Some(layout) = &self.dump_layout {
dump_specified_layout(&layout)?;
std::process::exit(0);
}
if let Some(swap_layout) = &self.dump_swap_layout {
dump_specified_swap_layout(swap_layout)?;
std::process::exit(0);
}
Ok(())
}
/// Checks the merged configuration
pub fn from_cli_with_options(&self, opts: &CliArgs, config_options: &Options) -> Result<()> {
if self.check {
Setup::check_defaults_config(opts, config_options)?;
std::process::exit(0);
}
if let Some(maybe_path) = &self.dump_plugins {
let data_dir = &opts.data_dir.clone().unwrap_or_else(get_default_data_dir);
let dir = match maybe_path {
Some(path) => path,
None => data_dir,
};
println!("Dumping plugins to '{}'", dir.display());
dump_builtin_plugins(&dir)?;
std::process::exit(0);
}
Ok(())
}
pub fn check_defaults_config(opts: &CliArgs, config_options: &Options) -> std::io::Result<()> {
let data_dir = opts.data_dir.clone().unwrap_or_else(get_default_data_dir);
let config_dir = opts.config_dir.clone().or_else(find_default_config_dir);
let plugin_dir = data_dir.join("plugins");
let layout_dir = config_options
.layout_dir
.clone()
.or_else(|| get_layout_dir(config_dir.clone()));
let system_data_dir = PathBuf::from(SYSTEM_DEFAULT_DATA_DIR_PREFIX).join("share/zellij");
let config_file = opts
.config
.clone()
.or_else(|| config_dir.clone().map(|p| p.join(CONFIG_NAME)));
// according to
// https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
let hyperlink_start = "\u{1b}]8;;";
let hyperlink_mid = "\u{1b}\\";
let hyperlink_end = "\u{1b}]8;;\u{1b}\\";
let mut message = String::new();
writeln!(&mut message, "[Version]: {:?}", VERSION).unwrap();
if let Some(config_dir) = config_dir {
writeln!(&mut message, "[CONFIG DIR]: {:?}", config_dir).unwrap();
} else {
message.push_str("[CONFIG DIR]: Not Found\n");
let mut default_config_dirs = default_config_dirs()
.iter()
.filter_map(|p| p.clone())
.collect::<Vec<PathBuf>>();
default_config_dirs.dedup();
message.push_str(
" On your system zellij looks in the following config directories by default:\n",
);
for dir in default_config_dirs {
writeln!(&mut message, " {:?}", dir).unwrap();
}
}
if let Some(config_file) = config_file {
writeln!(
&mut message,
"[LOOKING FOR CONFIG FILE FROM]: {:?}",
config_file
)
.unwrap();
match Config::from_path(&config_file, None) {
Ok(_) => message.push_str("[CONFIG FILE]: Well defined.\n"),
Err(e) => writeln!(
&mut message,
"[CONFIG ERROR]: {}. \n By default, zellij loads default configuration",
e
)
.unwrap(),
}
} else {
message.push_str("[CONFIG FILE]: Not Found\n");
writeln!(
&mut message,
" By default zellij looks for a file called [{}] in the configuration directory",
CONFIG_NAME
)
.unwrap();
}
writeln!(&mut message, "[CACHE DIR]: {}", ZELLIJ_CACHE_DIR.display()).unwrap();
writeln!(&mut message, "[DATA DIR]: {:?}", data_dir).unwrap();
message.push_str(&format!("[PLUGIN DIR]: {:?}\n", plugin_dir));
if !cfg!(feature = "disable_automatic_asset_installation") {
writeln!(
&mut message,
" Builtin, default plugins will not be loaded from disk."
)
.unwrap();
writeln!(
&mut message,
" Create a custom layout if you require this behavior."
)
.unwrap();
}
if let Some(layout_dir) = layout_dir {
writeln!(&mut message, "[LAYOUT DIR]: {:?}", layout_dir).unwrap();
} else {
message.push_str("[LAYOUT DIR]: Not Found\n");
}
writeln!(&mut message, "[SYSTEM DATA DIR]: {:?}", system_data_dir).unwrap();
writeln!(&mut message, "[ARROW SEPARATOR]: {}", ARROW_SEPARATOR).unwrap();
message.push_str(" Is the [ARROW_SEPARATOR] displayed correctly?\n");
message.push_str(" If not you may want to either start zellij with a compatible mode: 'zellij options --simplified-ui true'\n");
let mut hyperlink_compat = String::new();
hyperlink_compat.push_str(hyperlink_start);
hyperlink_compat.push_str("https://zellij.dev/documentation/compatibility.html#the-status-bar-fonts-dont-render-correctly");
hyperlink_compat.push_str(hyperlink_mid);
hyperlink_compat.push_str("https://zellij.dev/documentation/compatibility.html#the-status-bar-fonts-dont-render-correctly");
hyperlink_compat.push_str(hyperlink_end);
write!(
&mut message,
" Or check the font that is in use:\n {}\n",
hyperlink_compat
)
.unwrap();
message.push_str("[MOUSE INTERACTION]: \n");
message.push_str(" Can be temporarily disabled through pressing the [SHIFT] key.\n");
message.push_str(" If that doesn't fix any issues consider to disable the mouse handling of zellij: 'zellij options --disable-mouse-mode'\n");
let default_editor = std::env::var("EDITOR")
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| String::from("Not set, checked $EDITOR and $VISUAL"));
writeln!(&mut message, "[DEFAULT EDITOR]: {}", default_editor).unwrap();
writeln!(&mut message, "[FEATURES]: {:?}", FEATURES).unwrap();
let mut hyperlink = String::new();
hyperlink.push_str(hyperlink_start);
hyperlink.push_str("https://www.zellij.dev/documentation/");
hyperlink.push_str(hyperlink_mid);
hyperlink.push_str("zellij.dev/documentation");
hyperlink.push_str(hyperlink_end);
writeln!(&mut message, "[DOCUMENTATION]: {}", hyperlink).unwrap();
//printf '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n'
std::io::stdout().write_all(message.as_bytes())?;
Ok(())
}
fn generate_completion(shell: &str) {
let shell: Shell = match shell.to_lowercase().parse() {
Ok(shell) => shell,
_ => {
eprintln!("Unsupported shell: {}", shell);
std::process::exit(1);
},
};
let mut out = std::io::stdout();
clap_complete::generate(shell, &mut CliArgs::command(), "zellij", &mut out);
// add shell dependent extra completion
match shell {
Shell::Bash => {
let _ = out.write_all(BASH_EXTRA_COMPLETION);
},
Shell::Elvish => {},
Shell::Fish => {
let _ = out.write_all(FISH_EXTRA_COMPLETION);
},
Shell::PowerShell => {},
Shell::Zsh => {
let _ = out.write_all(ZSH_EXTRA_COMPLETION);
},
_ => {},
};
}
fn generate_auto_start(shell: &str) {
let shell: Shell = match shell.to_lowercase().parse() {
Ok(shell) => shell,
_ => {
eprintln!("Unsupported shell: {}", shell);
std::process::exit(1);
},
};
let mut out = std::io::stdout();
match shell {
Shell::Bash => {
let _ = out.write_all(BASH_AUTO_START_SCRIPT);
},
Shell::Fish => {
let _ = out.write_all(FISH_AUTO_START_SCRIPT);
},
Shell::Zsh => {
let _ = out.write_all(ZSH_AUTO_START_SCRIPT);
},
_ => {},
}
}
fn parse_layout_and_override_config(
cli_config_options: Option<&Options>,
config: Config,
cli_args: &CliArgs,
) -> Result<(Layout, Config), ConfigError> {
// find the layout folder relative to which we'll look for our layout
let layout_dir = cli_config_options
.as_ref()
.and_then(|cli_options| cli_options.layout_dir.clone())
.or_else(|| config.options.layout_dir.clone())
.or_else(|| {
get_layout_dir(cli_args.config_dir.clone().or_else(find_default_config_dir))
});
// the chosen layout can either be a path relative to the layout_dir or a name of one
// of our assets, this distinction is made when parsing the layout - TODO: ideally, this
// logic should not be split up and all the decisions should happen here
let chosen_layout = cli_args
.layout
.clone()
.or_else(|| {
cli_config_options
.as_ref()
.and_then(|cli_options| cli_options.default_layout.clone())
})
.or_else(|| config.options.default_layout.clone());
if let Some(layout_url) = chosen_layout
.as_ref()
.and_then(|l| l.to_str())
.and_then(|l| {
if l.starts_with("http://") || l.starts_with("https://") {
Some(l)
} else {
None
}
})
{
Layout::from_url(layout_url, config)
} else {
// we merge-override the config here because the layout might contain configuration
// that needs to take precedence
Layout::from_path_or_default(chosen_layout.as_ref(), layout_dir.clone(), config)
}
}
fn handle_setup_commands(cli_args: &CliArgs) {
if let Some(Command::Setup(ref setup)) = &cli_args.command {
setup.from_cli().map_or_else(
|e| {
eprintln!("{:?}", e);
process::exit(1);
},
|_| {},
);
};
}
}
fn merge_attach_command_options(
cli_config_options: Option<Options>,
cli_args: &CliArgs,
) -> Option<Options> {
let cli_config_options = if let Some(Command::Sessions(Sessions::Attach { options, .. })) =
cli_args.command.clone()
{
match options.clone().as_deref() {
Some(SessionCommand::Options(options)) => match cli_config_options {
Some(cli_config_options) => {
Some(cli_config_options.merge_from_cli(options.to_owned().into()))
},
None => Some(options.to_owned().into()),
},
_ => cli_config_options,
}
} else {
cli_config_options
};
cli_config_options
}
#[cfg(test)]
mod setup_test {
use super::Setup;
use crate::cli::{CliArgs, Command};
use crate::input::options::Options;
use insta::assert_snapshot;
use std::path::PathBuf;
#[test]
fn default_config_with_no_cli_arguments() {
let cli_args = CliArgs::default();
let (config, layout, options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", config));
assert_snapshot!(format!("{:#?}", layout));
assert_snapshot!(format!("{:#?}", options));
}
#[test]
fn cli_arguments_override_config_options() {
let mut cli_args = CliArgs::default();
cli_args.command = Some(Command::Options(Options {
simplified_ui: Some(true),
..Default::default()
}));
let (_config, _layout, options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", options));
}
#[test]
fn layout_options_override_config_options() {
let mut cli_args = CliArgs::default();
cli_args.layout = Some(PathBuf::from(format!(
"{}/src/test-fixtures/layout-with-options.kdl",
env!("CARGO_MANIFEST_DIR")
)));
let (_config, layout, options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", options));
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn cli_arguments_override_layout_options() {
let mut cli_args = CliArgs::default();
cli_args.layout = Some(PathBuf::from(format!(
"{}/src/test-fixtures/layout-with-options.kdl",
env!("CARGO_MANIFEST_DIR")
)));
cli_args.command = Some(Command::Options(Options {
pane_frames: Some(true),
..Default::default()
}));
let (_config, layout, options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", options));
assert_snapshot!(format!("{:#?}", layout));
}
#[test]
fn layout_env_vars_override_config_env_vars() {
let mut cli_args = CliArgs::default();
cli_args.config = Some(PathBuf::from(format!(
"{}/src/test-fixtures/config-with-env-vars.kdl",
env!("CARGO_MANIFEST_DIR")
)));
cli_args.layout = Some(PathBuf::from(format!(
"{}/src/test-fixtures/layout-with-env-vars.kdl",
env!("CARGO_MANIFEST_DIR")
)));
let (config, _layout, _options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", config));
}
#[test]
fn layout_ui_config_overrides_config_ui_config() {
let mut cli_args = CliArgs::default();
cli_args.config = Some(PathBuf::from(format!(
"{}/src/test-fixtures/config-with-ui-config.kdl",
env!("CARGO_MANIFEST_DIR")
)));
cli_args.layout = Some(PathBuf::from(format!(
"{}/src/test-fixtures/layout-with-ui-config.kdl",
env!("CARGO_MANIFEST_DIR")
)));
let (config, _layout, _options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", config));
}
#[test]
fn layout_themes_override_config_themes() {
let mut cli_args = CliArgs::default();
cli_args.config = Some(PathBuf::from(format!(
"{}/src/test-fixtures/config-with-themes-config.kdl",
env!("CARGO_MANIFEST_DIR")
)));
cli_args.layout = Some(PathBuf::from(format!(
"{}/src/test-fixtures/layout-with-themes-config.kdl",
env!("CARGO_MANIFEST_DIR")
)));
let (config, _layout, _options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", config));
}
#[test]
fn layout_keybinds_override_config_keybinds() {
let mut cli_args = CliArgs::default();
cli_args.config = Some(PathBuf::from(format!(
"{}/src/test-fixtures/config-with-keybindings-config.kdl",
env!("CARGO_MANIFEST_DIR")
)));
cli_args.layout = Some(PathBuf::from(format!(
"{}/src/test-fixtures/layout-with-keybindings-config.kdl",
env!("CARGO_MANIFEST_DIR")
)));
let (config, _layout, _options, _, _) = Setup::from_cli_args(&cli_args).unwrap();
assert_snapshot!(format!("{:#?}", config));
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/errors.rs | zellij-utils/src/errors.rs | //! Error context system based on a thread-local representation of the call stack, itself based on
//! the instructions that are sent between threads.
//!
//! # Help wanted
//!
//! There is an ongoing endeavor to improve the state of error handling in zellij. Currently, many
//! functions rely on [`unwrap`]ing [`Result`]s rather than returning and hence propagating
//! potential errors. If you're interested in helping to add error handling to zellij, don't
//! hesitate to get in touch with us. Additional information can be found in [the docs about error
//! handling](https://github.com/zellij-org/zellij/tree/main/docs/ERROR_HANDLING.md).
use anyhow::Context;
use colored::*;
use log::error;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Error, Formatter};
use std::path::PathBuf;
/// Re-exports of common error-handling code.
pub mod prelude {
pub use super::FatalError;
pub use super::LoggableError;
#[cfg(not(target_family = "wasm"))]
pub use super::ToAnyhow;
pub use super::ZellijError;
pub use anyhow::anyhow;
pub use anyhow::bail;
pub use anyhow::Context;
pub use anyhow::Error as anyError;
pub use anyhow::Result;
}
pub trait ErrorInstruction {
fn error(err: String) -> Self;
}
/// Helper trait to easily log error types.
///
/// The `print_error` function takes a closure which takes a `&str` and fares with it as necessary
/// to log the error to some usable location. For convenience, logging to stdout, stderr and
/// `log::error!` is already implemented.
///
/// Note that the trait functions pass the error through unmodified, so they can be chained with
/// the usual handling of [`std::result::Result`] types.
pub trait LoggableError<T>: Sized {
/// Gives a formatted error message derived from `self` to the closure `fun` for
/// printing/logging as appropriate.
///
/// # Examples
///
/// ```should_panic
/// use anyhow;
/// use zellij_utils::errors::LoggableError;
///
/// let my_err: anyhow::Result<&str> = Err(anyhow::anyhow!("Test error"));
/// my_err
/// .print_error(|msg| println!("{msg}"))
/// .unwrap();
/// ```
#[track_caller]
fn print_error<F: Fn(&str)>(self, fun: F) -> Self;
/// Convenienve function, calls `print_error` and logs the result as error.
///
/// This is not a wrapper around `log::error!`, because the `log` crate uses a lot of compile
/// time macros from `std` to determine caller locations/module names etc. Since these are
/// resolved at compile time in the location they are written, they would always resolve to the
/// location in this function where `log::error!` is called, masking the real caller location.
/// Hence, we build the log message ourselves. This means that we lose the information about
/// the calling module (Because it can only be resolved at compile time), however the callers
/// file and line number are preserved.
#[track_caller]
fn to_log(self) -> Self {
let caller = std::panic::Location::caller();
self.print_error(|msg| {
// Build the log entry manually
// NOTE: The log entry has no module path associated with it. This is because `log`
// gets the module path from the `std::module_path!()` macro, which is replaced at
// compile time in the location it is written!
log::logger().log(
&log::Record::builder()
.level(log::Level::Error)
.args(format_args!("{}", msg))
.file(Some(caller.file()))
.line(Some(caller.line()))
.module_path(None)
.build(),
);
})
}
/// Convenienve function, calls `print_error` with the closure `|msg| eprintln!("{}", msg)`.
fn to_stderr(self) -> Self {
self.print_error(|msg| eprintln!("{}", msg))
}
/// Convenienve function, calls `print_error` with the closure `|msg| println!("{}", msg)`.
fn to_stdout(self) -> Self {
self.print_error(|msg| println!("{}", msg))
}
}
impl<T> LoggableError<T> for anyhow::Result<T> {
fn print_error<F: Fn(&str)>(self, fun: F) -> Self {
if let Err(ref err) = self {
fun(&format!("{:?}", err));
}
self
}
}
/// Special trait to mark fatal/non-fatal errors.
///
/// This works in tandem with `LoggableError` above and is meant to make reading code easier with
/// regard to whether an error is fatal or not (i.e. can be ignored, or at least doesn't make the
/// application crash).
///
/// This essentially degrades any `std::result::Result<(), _>` to a simple `()`.
pub trait FatalError<T> {
/// Mark results as being non-fatal.
///
/// If the result is an `Err` variant, this will [print the error to the log][`to_log`].
/// Discards the result type afterwards.
///
/// [`to_log`]: LoggableError::to_log
#[track_caller]
fn non_fatal(self);
/// Mark results as being fatal.
///
/// If the result is an `Err` variant, this will unwrap the error and panic the application.
/// If the result is an `Ok` variant, the inner value is unwrapped and returned instead.
///
/// # Panics
///
/// If the given result is an `Err` variant.
#[track_caller]
fn fatal(self) -> T;
}
/// Helper function to silence `#[warn(unused_must_use)]` cargo warnings. Used exclusively in
/// `FatalError::non_fatal`!
fn discard_result<T>(_arg: anyhow::Result<T>) {}
impl<T> FatalError<T> for anyhow::Result<T> {
fn non_fatal(self) {
if self.is_err() {
discard_result(self.context("a non-fatal error occured").to_log());
}
}
fn fatal(self) -> T {
if let Ok(val) = self {
val
} else {
self.context("a fatal error occured")
.expect("Program terminates")
}
}
}
/// Different types of calls that form an [`ErrorContext`] call stack.
///
/// Complex variants store a variant of a related enum, whose variants can be built from
/// the corresponding Zellij MSPC instruction enum variants ([`ScreenInstruction`],
/// [`PtyInstruction`], [`ClientInstruction`], etc).
#[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)]
pub enum ContextType {
/// A screen-related call.
Screen(ScreenContext),
/// A PTY-related call.
Pty(PtyContext),
/// A plugin-related call.
Plugin(PluginContext),
/// An app-related call.
Client(ClientContext),
/// A server-related call.
IPCServer(ServerContext),
StdinHandler,
AsyncTask,
PtyWrite(PtyWriteContext),
BackgroundJob(BackgroundJobContext),
/// An empty, placeholder call. This should be thought of as representing no call at all.
/// A call stack representation filled with these is the representation of an empty call stack.
Empty,
}
impl Display for ContextType {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
if let Some((left, right)) = match *self {
ContextType::Screen(c) => Some(("screen_thread:", format!("{:?}", c))),
ContextType::Pty(c) => Some(("pty_thread:", format!("{:?}", c))),
ContextType::Plugin(c) => Some(("plugin_thread:", format!("{:?}", c))),
ContextType::Client(c) => Some(("main_thread:", format!("{:?}", c))),
ContextType::IPCServer(c) => Some(("ipc_server:", format!("{:?}", c))),
ContextType::StdinHandler => Some(("stdin_handler_thread:", "AcceptInput".to_string())),
ContextType::AsyncTask => Some(("stream_terminal_bytes:", "AsyncTask".to_string())),
ContextType::PtyWrite(c) => Some(("pty_writer_thread:", format!("{:?}", c))),
ContextType::BackgroundJob(c) => Some(("background_jobs_thread:", format!("{:?}", c))),
ContextType::Empty => None,
} {
write!(f, "{} {}", left.purple(), right.green())
} else {
write!(f, "")
}
}
}
// FIXME: Just deriving EnumDiscriminants from strum will remove the need for any of this!!!
/// Stack call representations corresponding to the different types of [`ScreenInstruction`]s.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ScreenContext {
HandlePtyBytes,
PluginBytes,
Render,
RenderToClients,
NewPane,
OpenInPlaceEditor,
ToggleFloatingPanes,
ShowFloatingPanes,
HideFloatingPanes,
TogglePaneEmbedOrFloating,
HorizontalSplit,
VerticalSplit,
WriteCharacter,
ResizeIncreaseAll,
ResizeIncreaseLeft,
ResizeIncreaseDown,
ResizeIncreaseUp,
ResizeIncreaseRight,
ResizeDecreaseAll,
ResizeDecreaseLeft,
ResizeDecreaseDown,
ResizeDecreaseUp,
ResizeDecreaseRight,
ResizeLeft,
ResizeRight,
ResizeDown,
ResizeUp,
ResizeIncrease,
ResizeDecrease,
SwitchFocus,
FocusNextPane,
FocusPreviousPane,
FocusPaneAt,
MoveFocusLeft,
MoveFocusLeftOrPreviousTab,
MoveFocusDown,
MoveFocusUp,
MoveFocusRight,
MoveFocusRightOrNextTab,
MovePane,
MovePaneBackwards,
MovePaneDown,
MovePaneUp,
MovePaneRight,
MovePaneLeft,
Exit,
ClearScreen,
DumpScreen,
DumpLayout,
EditScrollback,
GetPaneScrollback,
ScrollUp,
ScrollUpAt,
ScrollDown,
ScrollDownAt,
ScrollToBottom,
ScrollToTop,
PageScrollUp,
PageScrollDown,
HalfPageScrollUp,
HalfPageScrollDown,
ClearScroll,
CloseFocusedPane,
ToggleActiveSyncTab,
ToggleActiveTerminalFullscreen,
TogglePaneFrames,
SetSelectable,
ShowPluginCursor,
SetInvisibleBorders,
SetFixedHeight,
SetFixedWidth,
ClosePane,
HoldPane,
UpdatePaneName,
UndoRenamePane,
NewTab,
ApplyLayout,
SwitchTabNext,
SwitchTabPrev,
CloseTab,
GoToTab,
GoToTabName,
UpdateTabName,
UndoRenameTab,
MoveTabLeft,
MoveTabRight,
TerminalResize,
TerminalPixelDimensions,
TerminalBackgroundColor,
TerminalForegroundColor,
TerminalColorRegisters,
ChangeMode,
ChangeModeForAllClients,
LeftClick,
RightClick,
MiddleClick,
LeftMouseRelease,
RightMouseRelease,
MiddleMouseRelease,
MouseEvent,
Copy,
ToggleTab,
AddClient,
RemoveClient,
UpdateSearch,
SearchDown,
SearchUp,
SearchToggleCaseSensitivity,
SearchToggleWholeWord,
SearchToggleWrap,
AddRedPaneFrameColorOverride,
ClearPaneFrameColorOverride,
PreviousSwapLayout,
NextSwapLayout,
OverrideLayout,
OverrideLayoutComplete,
QueryTabNames,
NewTiledPluginPane,
StartOrReloadPluginPane,
NewFloatingPluginPane,
AddPlugin,
UpdatePluginLoadingStage,
ProgressPluginLoadingOffset,
StartPluginLoadingIndication,
RequestStateUpdateForPlugins,
LaunchOrFocusPlugin,
LaunchPlugin,
SuppressPane,
UnsuppressPane,
UnsuppressOrExpandPane,
FocusPaneWithId,
RenamePane,
RenameTab,
RequestPluginPermissions,
BreakPane,
BreakPaneRight,
BreakPaneLeft,
UpdateSessionInfos,
ReplacePane,
NewInPlacePluginPane,
SerializeLayoutForResurrection,
RenameSession,
DumpLayoutToPlugin,
ListClientsMetadata,
Reconfigure,
RerunCommandPane,
ResizePaneWithId,
EditScrollbackForPaneWithId,
WriteToPaneId,
CopyTextToClipboard,
MovePaneWithPaneId,
MovePaneWithPaneIdInDirection,
ClearScreenForPaneId,
ScrollUpInPaneId,
ScrollDownInPaneId,
ScrollToTopInPaneId,
ScrollToBottomInPaneId,
PageScrollUpInPaneId,
PageScrollDownInPaneId,
TogglePaneIdFullscreen,
TogglePaneEmbedOrEjectForPaneId,
CloseTabWithIndex,
BreakPanesToNewTab,
BreakPanesToTabWithIndex,
ListClientsToPlugin,
TogglePanePinned,
SetFloatingPanePinned,
StackPanes,
ChangeFloatingPanesCoordinates,
AddHighlightPaneFrameColorOverride,
GroupAndUngroupPanes,
HighlightAndUnhighlightPanes,
FloatMultiplePanes,
EmbedMultiplePanes,
TogglePaneInGroup,
ToggleGroupMarking,
SessionSharingStatusChange,
SetMouseSelectionSupport,
InterceptKeyPresses,
ClearKeyPressesIntercepts,
ReplacePaneWithExistingPane,
AddWatcherClient,
RemoveWatcherClient,
SetFollowedClient,
WatcherTerminalResize, // NEW
}
/// Stack call representations corresponding to the different types of [`PtyInstruction`]s.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PtyContext {
SpawnTerminal,
OpenInPlaceEditor,
SpawnTerminalVertically,
SpawnTerminalHorizontally,
UpdateActivePane,
GoToTab,
NewTab,
OverrideLayout,
ClosePane,
CloseTab,
ReRunCommandInPane,
DropToShellInPane,
SpawnInPlaceTerminal,
DumpLayout,
LogLayoutToHd,
FillPluginCwd,
DumpLayoutToPlugin,
ListClientsMetadata,
Reconfigure,
ListClientsToPlugin,
ReportPluginCwd,
SendSigintToPaneId,
SendSigkillToPaneId,
GetPanePid,
UpdateAndReportCwds,
Exit,
}
/// Stack call representations corresponding to the different types of [`PluginInstruction`]s.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PluginContext {
Load,
LoadBackgroundPlugin,
Update,
Render,
Unload,
Reload,
ReloadPluginWithId,
Resize,
Exit,
AddClient,
RemoveClient,
NewTab,
OverrideLayout,
ApplyCachedEvents,
ApplyCachedWorkerMessages,
PostMessageToPluginWorker,
PostMessageToPlugin,
PluginSubscribedToEvents,
PermissionRequestResult,
DumpLayout,
LogLayoutToHd,
CliPipe,
Message,
CachePluginEvents,
MessageFromPlugin,
UnblockCliPipes,
WatchFilesystem,
KeybindPipe,
DumpLayoutToPlugin,
ListClientsMetadata,
Reconfigure,
FailedToWriteConfigToDisk,
ListClientsToPlugin,
ChangePluginHostDir,
WebServerStarted,
FailedToStartWebServer,
PaneRenderReport,
UserInput,
}
/// Stack call representations corresponding to the different types of [`ClientInstruction`]s.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ClientContext {
Exit,
Error,
UnblockInputThread,
Render,
ServerError,
SwitchToMode,
Connected,
Log,
LogError,
OwnClientId,
StartedParsingStdinQuery,
DoneParsingStdinQuery,
SwitchSession,
SetSynchronisedOutput,
UnblockCliPipeInput,
CliPipeOutput,
QueryTerminalSize,
WriteConfigToDisk,
StartWebServer,
RenamedSession,
ConfigFileUpdated,
}
/// Stack call representations corresponding to the different types of [`ServerInstruction`]s.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ServerContext {
NewClient,
Render,
UnblockInputThread,
ClientExit,
RemoveClient,
Error,
KillSession,
DetachSession,
AttachClient,
ConnStatus,
Log,
LogError,
SwitchSession,
UnblockCliPipeInput,
CliPipeOutput,
AssociatePipeWithClient,
DisconnectAllClientsExcept,
ChangeMode,
ChangeModeForAllClients,
Reconfigure,
ConfigWrittenToDisk,
FailedToWriteConfigToDisk,
RebindKeys,
StartWebServer,
ShareCurrentSession,
StopSharingCurrentSession,
WebServerStarted,
FailedToStartWebServer,
SendWebClientsForbidden,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PtyWriteContext {
Write,
ResizePty,
StartCachingResizes,
ApplyCachedResizes,
Exit,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum BackgroundJobContext {
DisplayPaneError,
AnimatePluginLoading,
StopPluginLoadingAnimation,
ReadAllSessionInfosOnMachine,
ReportSessionInfo,
ReportLayoutInfo,
RunCommand,
WebRequest,
ReportPluginList,
ListWebSessions,
RenderToClients,
HighlightPanesWithMessage,
QueryZellijWebServerStatus,
Exit,
}
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ZellijError {
#[error("could not find command '{command}' for terminal {terminal_id}")]
CommandNotFound { terminal_id: u32, command: String },
#[error("could not determine default editor")]
NoEditorFound,
#[error("failed to allocate another terminal id")]
NoMoreTerminalIds,
#[error("failed to start PTY")]
FailedToStartPty,
#[error(
"This version of zellij was built to load the core plugins from
the globally configured plugin directory. However, a plugin wasn't found:
Plugin name: '{plugin_path}'
Plugin directory: '{plugin_dir}'
If you're a user:
Please report this error to the distributor of your current zellij version
If you're a developer:
Either make sure to include the plugins with the application (See feature
'disable_automatic_asset_installation'), or make them available in the
plugin directory.
Possible fix for your problem:
Run `zellij setup --dump-plugins`, and optionally point it to your
'DATA DIR', visible in e.g. the output of `zellij setup --check`. Without
further arguments, it will use the default 'DATA DIR'.
"
)]
BuiltinPluginMissing {
plugin_path: PathBuf,
plugin_dir: PathBuf,
#[source]
source: anyhow::Error,
},
#[error(
"It seems you tried to load the following builtin plugin:
Plugin name: '{plugin_path}'
This is not a builtin plugin known to this version of zellij. If you were using
a custom layout, please refer to the layout documentation at:
https://zellij.dev/documentation/creating-a-layout.html#plugin
If you think this is a bug and the plugin is indeed an internal plugin, please
open an issue on GitHub:
https://github.com/zellij-org/zellij/issues
"
)]
BuiltinPluginNonexistent {
plugin_path: PathBuf,
#[source]
source: anyhow::Error,
},
// this is a temporary hack until we're able to merge custom errors from within the various
// crates themselves without having to move their payload types here
#[error("Cannot resize fixed panes")]
CantResizeFixedPanes { pane_ids: Vec<(u32, bool)> }, // bool: 0 => terminal_pane, 1 =>
// plugin_pane
#[error("Pane size remains unchanged")]
PaneSizeUnchanged,
#[error("an error occured")]
GenericError { source: anyhow::Error },
#[error("Client {client_id} is too slow to handle incoming messages")]
ClientTooSlow { client_id: u16 },
#[error("The plugin does not exist")]
PluginDoesNotExist,
#[error("Ran out of room for spans")]
RanOutOfRoomForSpans,
}
#[cfg(not(target_family = "wasm"))]
pub use not_wasm::*;
#[cfg(not(target_family = "wasm"))]
mod not_wasm {
use super::*;
use crate::channels::{SenderWithContext, ASYNCOPENCALLS, OPENCALLS};
use miette::{Diagnostic, GraphicalReportHandler, GraphicalTheme, Report};
use std::panic::PanicHookInfo;
use thiserror::Error as ThisError;
/// The maximum amount of calls an [`ErrorContext`] will keep track
/// of in its stack representation. This is a per-thread maximum.
const MAX_THREAD_CALL_STACK: usize = 6;
#[derive(Debug, ThisError, Diagnostic)]
#[error("{0}{}", self.show_backtrace())]
#[diagnostic(help("{}", self.show_help()))]
struct Panic(String);
impl Panic {
// We already capture a backtrace with `anyhow` using the `backtrace` crate in the background.
// The advantage is that this is the backtrace of the real errors source (i.e. where we first
// encountered the error and turned it into an `anyhow::Error`), whereas the backtrace recorded
// here is the backtrace leading to the call to any `panic`ing function. Since now we propagate
// errors up before `unwrap`ing them (e.g. in `zellij_server::screen::screen_thread_main`), the
// former is what we really want to diagnose.
// We still keep the second one around just in case the first backtrace isn't meaningful or
// non-existent in the first place (Which really shouldn't happen, but you never know).
fn show_backtrace(&self) -> String {
if let Ok(var) = std::env::var("RUST_BACKTRACE") {
if !var.is_empty() && var != "0" {
return format!("\n\nPanic backtrace:\n{:?}", backtrace::Backtrace::new());
}
}
"".into()
}
fn show_help(&self) -> String {
format!(
"If you are seeing this message, it means that something went wrong.
-> To get additional information, check the log at: {}
-> To see a backtrace next time, reproduce the error with: RUST_BACKTRACE=1 zellij [...]
-> To help us fix this, please open an issue: https://github.com/zellij-org/zellij/issues
",
crate::consts::ZELLIJ_TMP_LOG_FILE.display().to_string()
)
}
}
/// Custom panic handler/hook. Prints the [`ErrorContext`].
pub fn handle_panic<T>(info: &PanicHookInfo<'_>, sender: Option<&SenderWithContext<T>>)
where
T: ErrorInstruction + Clone,
{
use std::{process, thread};
let thread = thread::current();
let thread = thread.name().unwrap_or("unnamed");
let msg = match info.payload().downcast_ref::<&'static str>() {
Some(s) => Some(*s),
None => info.payload().downcast_ref::<String>().map(|s| &**s),
}
.unwrap_or("An unexpected error occurred!");
let err_ctx = OPENCALLS.with(|ctx| *ctx.borrow());
let mut report: Report = Panic(format!("\u{1b}[0;31m{}\u{1b}[0;0m", msg)).into();
let mut location_string = String::new();
if let Some(location) = info.location() {
location_string = format!(
"At {}:{}:{}",
location.file(),
location.line(),
location.column()
);
report = report.wrap_err(location_string.clone());
}
if !err_ctx.is_empty() {
report = report.wrap_err(format!("{}", err_ctx));
}
report = report.wrap_err(format!(
"Thread '\u{1b}[0;31m{}\u{1b}[0;0m' panicked.",
thread
));
error!(
"{}",
format!(
"Panic occured:
thread: {}
location: {}
message: {}",
thread, location_string, msg
)
);
if thread == "main" || sender.is_none() {
// here we only show the first line because the backtrace is not readable otherwise
// a better solution would be to escape raw mode before we do this, but it's not trivial
// to get os_input here
println!("\u{1b}[2J{}", fmt_report(report));
process::exit(1);
} else {
let _ = sender.unwrap().send(T::error(fmt_report(report)));
}
}
pub fn get_current_ctx() -> ErrorContext {
ASYNCOPENCALLS
.try_with(|ctx| *ctx.borrow())
.unwrap_or_else(|_| OPENCALLS.with(|ctx| *ctx.borrow()))
}
fn fmt_report(diag: Report) -> String {
let mut out = String::new();
GraphicalReportHandler::new_themed(GraphicalTheme::unicode())
.render_report(&mut out, diag.as_ref())
.unwrap();
out
}
/// A representation of the call stack.
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct ErrorContext {
calls: [ContextType; MAX_THREAD_CALL_STACK],
}
impl ErrorContext {
/// Returns a new, blank [`ErrorContext`] containing only [`Empty`](ContextType::Empty)
/// calls.
pub fn new() -> Self {
Self {
calls: [ContextType::Empty; MAX_THREAD_CALL_STACK],
}
}
/// Returns `true` if the calls has all [`Empty`](ContextType::Empty) calls.
pub fn is_empty(&self) -> bool {
self.calls.iter().all(|c| c == &ContextType::Empty)
}
/// Adds a call to this [`ErrorContext`]'s call stack representation.
pub fn add_call(&mut self, call: ContextType) {
for ctx in &mut self.calls {
if let ContextType::Empty = ctx {
*ctx = call;
break;
}
}
self.update_thread_ctx()
}
/// Updates the thread local [`ErrorContext`].
pub fn update_thread_ctx(&self) {
ASYNCOPENCALLS
.try_with(|ctx| *ctx.borrow_mut() = *self)
.unwrap_or_else(|_| OPENCALLS.with(|ctx| *ctx.borrow_mut() = *self));
}
}
impl Default for ErrorContext {
fn default() -> Self {
Self::new()
}
}
impl Display for ErrorContext {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
writeln!(f, "Originating Thread(s)")?;
for (index, ctx) in self.calls.iter().enumerate() {
if *ctx == ContextType::Empty {
break;
}
writeln!(f, "\t\u{1b}[0;0m{}. {}", index + 1, ctx)?;
}
Ok(())
}
}
/// Helper trait to convert error types that don't satisfy `anyhow`s trait requirements to
/// anyhow errors.
pub trait ToAnyhow<U> {
fn to_anyhow(self) -> anyhow::Result<U>;
}
/// `SendError` doesn't satisfy `anyhow`s trait requirements due to `T` possibly being a
/// `PluginInstruction` type, which wraps an `mpsc::Send` and isn't `Sync`. Due to this, in turn,
/// the whole error type isn't `Sync` and doesn't work with `anyhow` (or pretty much any other
/// error handling crate).
///
/// Takes the `SendError` and creates an `anyhow` error type with the message that was sent
/// (formatted as string), attaching the [`ErrorContext`] as anyhow context to it.
impl<T: std::fmt::Debug, U> ToAnyhow<U>
for Result<U, crate::channels::SendError<(T, ErrorContext)>>
{
fn to_anyhow(self) -> anyhow::Result<U> {
match self {
Ok(val) => anyhow::Ok(val),
Err(e) => {
let (msg, context) = e.into_inner();
if *crate::consts::DEBUG_MODE.get().unwrap_or(&true) {
Err(anyhow::anyhow!(
"failed to send message to channel: {:#?}",
msg
))
.with_context(|| context.to_string())
} else {
Err(anyhow::anyhow!("failed to send message to channel"))
.with_context(|| context.to_string())
}
},
}
}
}
impl<U> ToAnyhow<U> for Result<U, std::sync::PoisonError<U>> {
fn to_anyhow(self) -> anyhow::Result<U> {
match self {
Ok(val) => anyhow::Ok(val),
Err(e) => {
if *crate::consts::DEBUG_MODE.get().unwrap_or(&true) {
Err(anyhow::anyhow!("cannot acquire poisoned lock for {e:#?}"))
} else {
Err(anyhow::anyhow!("cannot acquire poisoned lock"))
}
},
}
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/consts.rs | zellij-utils/src/consts.rs | //! Zellij program-wide constants.
use crate::home::find_default_config_dir;
use directories::ProjectDirs;
use include_dir::{include_dir, Dir};
use lazy_static::lazy_static;
use std::{path::PathBuf, sync::OnceLock};
use uuid::Uuid;
pub const ZELLIJ_CONFIG_FILE_ENV: &str = "ZELLIJ_CONFIG_FILE";
pub const ZELLIJ_CONFIG_DIR_ENV: &str = "ZELLIJ_CONFIG_DIR";
pub const ZELLIJ_LAYOUT_DIR_ENV: &str = "ZELLIJ_LAYOUT_DIR";
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const DEFAULT_SCROLL_BUFFER_SIZE: usize = 10_000;
pub static SCROLL_BUFFER_SIZE: OnceLock<usize> = OnceLock::new();
pub static DEBUG_MODE: OnceLock<bool> = OnceLock::new();
pub const SYSTEM_DEFAULT_CONFIG_DIR: &str = "/etc/zellij";
pub const SYSTEM_DEFAULT_DATA_DIR_PREFIX: &str = system_default_data_dir();
pub static ZELLIJ_DEFAULT_THEMES: Dir = include_dir!("$CARGO_MANIFEST_DIR/assets/themes");
pub const CLIENT_SERVER_CONTRACT_VERSION: usize = 1;
pub fn session_info_cache_file_name(session_name: &str) -> PathBuf {
session_info_folder_for_session(session_name).join("session-metadata.kdl")
}
pub fn session_layout_cache_file_name(session_name: &str) -> PathBuf {
session_info_folder_for_session(session_name).join("session-layout.kdl")
}
pub fn session_info_folder_for_session(session_name: &str) -> PathBuf {
ZELLIJ_SESSION_INFO_CACHE_DIR.join(session_name)
}
pub fn create_config_and_cache_folders() {
if let Err(e) = std::fs::create_dir_all(&ZELLIJ_CACHE_DIR.as_path()) {
log::error!("Failed to create cache dir: {:?}", e);
}
if let Some(config_dir) = find_default_config_dir() {
if let Err(e) = std::fs::create_dir_all(&config_dir.as_path()) {
log::error!("Failed to create config dir: {:?}", e);
}
}
// while session_info is a child of cache currently, it won't necessarily always be this way,
// and so it's explicitly created here
if let Err(e) = std::fs::create_dir_all(&ZELLIJ_SESSION_INFO_CACHE_DIR.as_path()) {
log::error!("Failed to create session_info cache dir: {:?}", e);
}
}
const fn system_default_data_dir() -> &'static str {
if let Some(data_dir) = std::option_env!("PREFIX") {
data_dir
} else {
"/usr"
}
}
lazy_static! {
pub static ref CLIENT_SERVER_CONTRACT_DIR: String =
format!("contract_version_{}", CLIENT_SERVER_CONTRACT_VERSION);
pub static ref ZELLIJ_PROJ_DIR: ProjectDirs =
ProjectDirs::from("org", "Zellij Contributors", "Zellij").unwrap();
pub static ref ZELLIJ_CACHE_DIR: PathBuf = ZELLIJ_PROJ_DIR.cache_dir().to_path_buf();
pub static ref ZELLIJ_SESSION_CACHE_DIR: PathBuf = ZELLIJ_PROJ_DIR
.cache_dir()
.to_path_buf()
.join(format!("{}", Uuid::new_v4()));
pub static ref ZELLIJ_PLUGIN_PERMISSIONS_CACHE: PathBuf =
ZELLIJ_CACHE_DIR.join("permissions.kdl");
pub static ref ZELLIJ_SESSION_INFO_CACHE_DIR: PathBuf = ZELLIJ_CACHE_DIR
.join(CLIENT_SERVER_CONTRACT_DIR.clone())
.join("session_info");
pub static ref ZELLIJ_STDIN_CACHE_FILE: PathBuf =
ZELLIJ_CACHE_DIR.join(VERSION).join("stdin_cache");
pub static ref ZELLIJ_PLUGIN_ARTIFACT_DIR: PathBuf = ZELLIJ_CACHE_DIR.join(VERSION);
pub static ref ZELLIJ_SEEN_RELEASE_NOTES_CACHE_FILE: PathBuf =
ZELLIJ_CACHE_DIR.join(VERSION).join("seen_release_notes");
}
pub const FEATURES: &[&str] = &[
#[cfg(feature = "disable_automatic_asset_installation")]
"disable_automatic_asset_installation",
];
#[cfg(not(target_family = "wasm"))]
pub use not_wasm::*;
#[cfg(not(target_family = "wasm"))]
mod not_wasm {
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::path::PathBuf;
// Convenience macro to add plugins to the asset map (see `ASSET_MAP`)
//
// Plugins are taken from:
//
// - `zellij-utils/assets/plugins`: When building in release mode OR when the
// `plugins_from_target` feature IS NOT set
// - `zellij-utils/../target/wasm32-wasip1/debug`: When building in debug mode AND the
// `plugins_from_target` feature IS set
macro_rules! add_plugin {
($assets:expr, $plugin:literal) => {
$assets.insert(
PathBuf::from("plugins").join($plugin),
#[cfg(any(not(feature = "plugins_from_target"), not(debug_assertions)))]
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/assets/plugins/",
$plugin
))
.to_vec(),
#[cfg(all(feature = "plugins_from_target", debug_assertions))]
include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../target/wasm32-wasip1/debug/",
$plugin
))
.to_vec(),
);
};
}
lazy_static! {
// Zellij asset map
pub static ref ASSET_MAP: HashMap<PathBuf, Vec<u8>> = {
let mut assets = std::collections::HashMap::new();
add_plugin!(assets, "compact-bar.wasm");
add_plugin!(assets, "status-bar.wasm");
add_plugin!(assets, "tab-bar.wasm");
add_plugin!(assets, "strider.wasm");
add_plugin!(assets, "session-manager.wasm");
add_plugin!(assets, "configuration.wasm");
add_plugin!(assets, "plugin-manager.wasm");
add_plugin!(assets, "about.wasm");
add_plugin!(assets, "share.wasm");
add_plugin!(assets, "multiple-select.wasm");
add_plugin!(assets, "sequence.wasm");
assets
};
}
}
#[cfg(unix)]
pub use unix_only::*;
#[cfg(unix)]
mod unix_only {
use super::*;
use crate::envs;
pub use crate::shared::set_permissions;
use lazy_static::lazy_static;
use nix::unistd::Uid;
use std::env::temp_dir;
pub const ZELLIJ_SOCK_MAX_LENGTH: usize = 108;
lazy_static! {
static ref UID: Uid = Uid::current();
pub static ref ZELLIJ_TMP_DIR: PathBuf = temp_dir().join(format!("zellij-{}", *UID));
pub static ref ZELLIJ_TMP_LOG_DIR: PathBuf = ZELLIJ_TMP_DIR.join("zellij-log");
pub static ref ZELLIJ_TMP_LOG_FILE: PathBuf = ZELLIJ_TMP_LOG_DIR.join("zellij.log");
pub static ref ZELLIJ_SOCK_DIR: PathBuf = {
let mut ipc_dir = envs::get_socket_dir().map_or_else(
|_| {
ZELLIJ_PROJ_DIR
.runtime_dir()
.map_or_else(|| ZELLIJ_TMP_DIR.clone(), |p| p.to_owned())
},
PathBuf::from,
);
ipc_dir.push(CLIENT_SERVER_CONTRACT_DIR.clone());
ipc_dir
};
pub static ref WEBSERVER_SOCKET_PATH: PathBuf = ZELLIJ_SOCK_DIR.join("web_server_bus");
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/common_path.rs | zellij-utils/src/common_path.rs | // The following license refers to code in this file and this file only.
// We chose to vendor this dependency rather than depend on it through crates.io in order to facilitate
// packaging. This license was copied verbatim from: https://docs.rs/crate/common-path/1.0.0/source/LICENSE-MIT
//
// MIT License
//
// Copyright 2018 Paul Woolcock <paul@woolcock.us>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use std::path::{Path, PathBuf};
/// Find the common prefix, if any, between any number of paths
///
/// # Example
///
/// ```rust
/// use std::path::{PathBuf, Path};
/// use zellij_utils::common_path::common_path_all;
///
/// # fn main() {
/// let baz = Path::new("/foo/bar/baz");
/// let quux = Path::new("/foo/bar/quux");
/// let foo = Path::new("/foo/bar/foo");
/// let prefix = common_path_all(vec![baz, quux, foo]).unwrap();
/// assert_eq!(prefix, Path::new("/foo/bar").to_path_buf());
/// # }
/// ```
pub fn common_path_all<'a>(paths: impl IntoIterator<Item = &'a Path>) -> Option<PathBuf> {
let mut path_iter = paths.into_iter();
let mut result = path_iter.next()?.to_path_buf();
for path in path_iter {
if let Some(r) = common_path(&result, &path) {
result = r;
} else {
return None;
}
}
Some(result.to_path_buf())
}
/// Find the common prefix, if any, between 2 paths
///
/// # Example
///
/// ```rust
/// use std::path::{PathBuf, Path};
/// use zellij_utils::common_path::common_path;
///
/// # fn main() {
/// let baz = Path::new("/foo/bar/baz");
/// let quux = Path::new("/foo/bar/quux");
/// let prefix = common_path(baz, quux).unwrap();
/// assert_eq!(prefix, Path::new("/foo/bar").to_path_buf());
/// # }
/// ```
pub fn common_path<P, Q>(one: P, two: Q) -> Option<PathBuf>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
let one = one.as_ref();
let two = two.as_ref();
let one = one.components();
let two = two.components();
let mut final_path = PathBuf::new();
let mut found = false;
let paths = one.zip(two);
for (l, r) in paths {
if l == r {
final_path.push(l.as_os_str());
found = true;
} else {
break;
}
}
if found {
Some(final_path)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compare_all_paths() {
let one = Path::new("/foo/bar/baz/one.txt");
let two = Path::new("/foo/bar/quux/quuux/two.txt");
let three = Path::new("/foo/bar/baz/foo/bar");
let result = Path::new("/foo/bar");
let path_permutations = vec![
vec![one, two, three],
vec![one, three, two],
vec![two, one, three],
vec![two, three, one],
vec![three, one, two],
vec![three, two, one],
];
for all in path_permutations {
assert_eq!(common_path_all(all).unwrap(), result.to_path_buf())
}
}
#[test]
fn compare_paths() {
let one = Path::new("/foo/bar/baz/one.txt");
let two = Path::new("/foo/bar/quux/quuux/two.txt");
let result = Path::new("/foo/bar");
assert_eq!(common_path(&one, &two).unwrap(), result.to_path_buf())
}
#[test]
fn no_common_path() {
let one = Path::new("/foo/bar");
let two = Path::new("./baz/quux");
assert!(common_path(&one, &two).is_none());
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/session_serialization.rs | zellij-utils/src/session_serialization.rs | use kdl::{KdlDocument, KdlEntry, KdlNode, KdlValue};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::PathBuf;
use crate::{
input::layout::PluginUserConfiguration,
input::layout::{
FloatingPaneLayout, Layout, LayoutConstraint, PercentOrFixed, Run, RunPluginOrAlias,
SplitDirection, SplitSize, SwapFloatingLayout, SwapTiledLayout, TiledPaneLayout,
},
pane_size::{Constraint, PaneGeom},
};
#[derive(Default, Debug, Clone)]
pub struct GlobalLayoutManifest {
pub global_cwd: Option<PathBuf>,
pub default_shell: Option<PathBuf>,
pub default_layout: Box<Layout>,
pub tabs: Vec<(String, TabLayoutManifest)>,
}
#[derive(Default, Debug, Clone)]
pub struct TabLayoutManifest {
pub tiled_panes: Vec<PaneLayoutManifest>,
pub floating_panes: Vec<PaneLayoutManifest>,
pub is_focused: bool,
pub hide_floating_panes: bool,
}
#[derive(Default, Debug, Clone)]
pub struct PaneLayoutManifest {
pub geom: PaneGeom,
pub run: Option<Run>,
pub cwd: Option<PathBuf>,
pub is_borderless: bool,
pub title: Option<String>,
pub is_focused: bool,
pub pane_contents: Option<String>,
}
pub fn serialize_session_layout(
global_layout_manifest: GlobalLayoutManifest,
) -> Result<(String, BTreeMap<String, String>), &'static str> {
// BTreeMap is the pane contents and their file names
let mut document = KdlDocument::new();
let mut pane_contents = BTreeMap::new();
let mut layout_node = KdlNode::new("layout");
let mut layout_node_children = KdlDocument::new();
if let Some(global_cwd) = serialize_global_cwd(&global_layout_manifest.global_cwd) {
layout_node_children.nodes_mut().push(global_cwd);
}
match serialize_multiple_tabs(global_layout_manifest.tabs, &mut pane_contents) {
Ok(mut serialized_tabs) => {
layout_node_children
.nodes_mut()
.append(&mut serialized_tabs);
},
Err(e) => {
return Err(e);
},
}
serialize_new_tab_template(
global_layout_manifest.default_layout.template,
&mut pane_contents,
&mut layout_node_children,
);
serialize_swap_tiled_layouts(
global_layout_manifest.default_layout.swap_tiled_layouts,
&mut pane_contents,
&mut layout_node_children,
);
serialize_swap_floating_layouts(
global_layout_manifest.default_layout.swap_floating_layouts,
&mut pane_contents,
&mut layout_node_children,
);
layout_node.set_children(layout_node_children);
document.nodes_mut().push(layout_node);
Ok((document.to_string(), pane_contents))
}
fn serialize_tab(
tab_name: String,
is_focused: bool,
hide_floating_panes: bool,
tiled_panes: &Vec<PaneLayoutManifest>,
floating_panes: &Vec<PaneLayoutManifest>,
pane_contents: &mut BTreeMap<String, String>,
) -> Option<KdlNode> {
let mut serialized_tab = KdlNode::new("tab");
let mut serialized_tab_children = KdlDocument::new();
match get_tiled_panes_layout_from_panegeoms(tiled_panes, None) {
Some(tiled_panes_layout) => {
let floating_panes_layout = get_floating_panes_layout_from_panegeoms(floating_panes);
let tiled_panes = if &tiled_panes_layout.children_split_direction
!= &SplitDirection::default()
|| tiled_panes_layout.children_are_stacked
{
vec![tiled_panes_layout]
} else {
tiled_panes_layout.children
};
serialized_tab
.entries_mut()
.push(KdlEntry::new_prop("name", tab_name));
if is_focused {
serialized_tab
.entries_mut()
.push(KdlEntry::new_prop("focus", KdlValue::Bool(true)));
}
if hide_floating_panes {
serialized_tab.entries_mut().push(KdlEntry::new_prop(
"hide_floating_panes",
KdlValue::Bool(true),
));
}
serialize_tiled_and_floating_panes(
&tiled_panes,
floating_panes_layout,
pane_contents,
&mut serialized_tab_children,
);
serialized_tab.set_children(serialized_tab_children);
Some(serialized_tab)
},
None => {
return None;
},
}
}
fn serialize_tiled_and_floating_panes(
tiled_panes: &Vec<TiledPaneLayout>,
floating_panes_layout: Vec<FloatingPaneLayout>,
pane_contents: &mut BTreeMap<String, String>,
serialized_tab_children: &mut KdlDocument,
) {
for tiled_pane_layout in tiled_panes {
let ignore_size = false;
let tiled_pane_node = serialize_tiled_pane(tiled_pane_layout, ignore_size, pane_contents);
serialized_tab_children.nodes_mut().push(tiled_pane_node);
}
if !floating_panes_layout.is_empty() {
let mut floating_panes_node = KdlNode::new("floating_panes");
let mut floating_panes_node_children = KdlDocument::new();
for floating_pane in floating_panes_layout {
let pane_node = serialize_floating_pane(&floating_pane, pane_contents);
floating_panes_node_children.nodes_mut().push(pane_node);
}
floating_panes_node.set_children(floating_panes_node_children);
serialized_tab_children
.nodes_mut()
.push(floating_panes_node);
}
}
fn serialize_tiled_pane(
layout: &TiledPaneLayout,
ignore_size: bool,
pane_contents: &mut BTreeMap<String, String>,
) -> KdlNode {
let (command, args) = extract_command_and_args(&layout.run);
let (plugin, plugin_config) = extract_plugin_and_config(&layout.run);
let (edit, _line_number) = extract_edit_and_line_number(&layout.run);
let cwd = layout.run.as_ref().and_then(|r| r.get_cwd());
let has_children = layout.external_children_index.is_some() || !layout.children.is_empty();
let mut tiled_pane_node = KdlNode::new("pane");
serialize_pane_title_and_attributes(
&command,
&edit,
&layout.name,
cwd,
layout.focus,
&layout.pane_initial_contents,
pane_contents,
has_children,
&mut tiled_pane_node,
);
serialize_tiled_layout_attributes(&layout, ignore_size, &mut tiled_pane_node);
let has_child_attributes = !layout.children.is_empty()
|| layout.external_children_index.is_some()
|| !args.is_empty()
|| plugin.is_some()
|| command.is_some();
if has_child_attributes {
let mut tiled_pane_node_children = KdlDocument::new();
serialize_args(args, &mut tiled_pane_node_children);
serialize_start_suspended(&command, &mut tiled_pane_node_children);
serialize_plugin(plugin, plugin_config, &mut tiled_pane_node_children);
if layout.children.is_empty() && layout.external_children_index.is_some() {
tiled_pane_node_children
.nodes_mut()
.push(KdlNode::new("children"));
}
for (i, pane) in layout.children.iter().enumerate() {
if Some(i) == layout.external_children_index {
tiled_pane_node_children
.nodes_mut()
.push(KdlNode::new("children"));
} else {
let ignore_size = layout.children_are_stacked;
let child_pane_node = serialize_tiled_pane(&pane, ignore_size, pane_contents);
tiled_pane_node_children.nodes_mut().push(child_pane_node);
}
}
tiled_pane_node.set_children(tiled_pane_node_children);
}
tiled_pane_node
}
pub fn extract_command_and_args(layout_run: &Option<Run>) -> (Option<String>, Vec<String>) {
match layout_run {
Some(Run::Command(run_command)) => (
Some(run_command.command.display().to_string()),
run_command.args.clone(),
),
_ => (None, vec![]),
}
}
pub fn extract_plugin_and_config(
layout_run: &Option<Run>,
) -> (Option<String>, Option<PluginUserConfiguration>) {
match &layout_run {
Some(Run::Plugin(run_plugin_or_alias)) => match run_plugin_or_alias {
RunPluginOrAlias::RunPlugin(run_plugin) => (
Some(run_plugin.location.display()),
Some(run_plugin.configuration.clone()),
),
RunPluginOrAlias::Alias(plugin_alias) => {
// in this case, the aliases should already be populated by the RunPlugins they
// translate to - if they are not, the alias either does not exist or this is some
// sort of bug
let name = plugin_alias
.run_plugin
.as_ref()
.map(|run_plugin| run_plugin.location.display().to_string())
.unwrap_or_else(|| plugin_alias.name.clone());
let configuration = plugin_alias
.run_plugin
.as_ref()
.map(|run_plugin| run_plugin.configuration.clone());
(Some(name), configuration)
},
},
_ => (None, None),
}
}
pub fn extract_edit_and_line_number(layout_run: &Option<Run>) -> (Option<String>, Option<usize>) {
match &layout_run {
// TODO: line number in layouts?
Some(Run::EditFile(path, line_number, _cwd)) => {
(Some(path.display().to_string()), line_number.clone())
},
_ => (None, None),
}
}
fn serialize_pane_title_and_attributes(
command: &Option<String>,
edit: &Option<String>,
name: &Option<String>,
cwd: Option<PathBuf>,
focus: Option<bool>,
initial_pane_contents: &Option<String>,
pane_contents: &mut BTreeMap<String, String>,
has_children: bool,
kdl_node: &mut KdlNode,
) {
match (&command, &edit) {
(Some(command), _) => kdl_node
.entries_mut()
.push(KdlEntry::new_prop("command", command.to_owned())),
(None, Some(edit)) => kdl_node
.entries_mut()
.push(KdlEntry::new_prop("edit", edit.to_owned())),
_ => {},
};
if let Some(name) = name {
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("name", name.to_owned()));
}
if let Some(cwd) = cwd {
let path = cwd.display().to_string();
if !path.is_empty() && !has_children {
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("cwd", path.to_owned()));
}
}
if focus.unwrap_or(false) {
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("focus", KdlValue::Bool(true)));
}
if let Some(initial_pane_contents) = initial_pane_contents.as_ref() {
if command.is_none() && edit.is_none() {
let file_name = format!("initial_contents_{}", pane_contents.keys().len() + 1);
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("contents_file", file_name.clone()));
pane_contents.insert(file_name, initial_pane_contents.clone());
}
}
}
fn serialize_args(args: Vec<String>, pane_node_children: &mut KdlDocument) {
if !args.is_empty() {
let mut args_node = KdlNode::new("args");
for arg in &args {
args_node.entries_mut().push(KdlEntry::new(arg.to_owned()));
}
pane_node_children.nodes_mut().push(args_node);
}
}
fn serialize_plugin(
plugin: Option<String>,
plugin_config: Option<PluginUserConfiguration>,
pane_node_children: &mut KdlDocument,
) {
if let Some(plugin) = plugin {
let mut plugin_node = KdlNode::new("plugin");
plugin_node
.entries_mut()
.push(KdlEntry::new_prop("location", plugin.to_owned()));
if let Some(plugin_config) =
plugin_config.and_then(|p| if p.inner().is_empty() { None } else { Some(p) })
{
let mut plugin_node_children = KdlDocument::new();
for (config_key, config_value) in plugin_config.inner() {
let mut config_node = KdlNode::new(config_key.to_owned());
config_node
.entries_mut()
.push(KdlEntry::new(config_value.to_owned()));
plugin_node_children.nodes_mut().push(config_node);
}
plugin_node.set_children(plugin_node_children);
}
pane_node_children.nodes_mut().push(plugin_node);
}
}
fn serialize_tiled_layout_attributes(
layout: &TiledPaneLayout,
ignore_size: bool,
kdl_node: &mut KdlNode,
) {
if !ignore_size {
match layout.split_size {
Some(SplitSize::Fixed(size)) => kdl_node
.entries_mut()
.push(KdlEntry::new_prop("size", KdlValue::Base10(size as i64))),
Some(SplitSize::Percent(size)) => kdl_node
.entries_mut()
.push(KdlEntry::new_prop("size", format!("{size}%"))),
None => (),
};
}
if layout.borderless {
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("borderless", KdlValue::Bool(true)));
}
if layout.children_are_stacked {
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("stacked", KdlValue::Bool(true)));
}
if layout.is_expanded_in_stack {
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("expanded", KdlValue::Bool(true)));
}
if layout.children_split_direction != SplitDirection::default() {
let direction = match layout.children_split_direction {
SplitDirection::Horizontal => "horizontal",
SplitDirection::Vertical => "vertical",
};
kdl_node
.entries_mut()
.push(KdlEntry::new_prop("split_direction", direction));
}
}
fn serialize_floating_layout_attributes(
layout: &FloatingPaneLayout,
pane_node_children: &mut KdlDocument,
) {
match layout.height {
Some(PercentOrFixed::Fixed(fixed_height)) => {
let mut node = KdlNode::new("height");
node.entries_mut()
.push(KdlEntry::new(KdlValue::Base10(fixed_height as i64)));
pane_node_children.nodes_mut().push(node);
},
Some(PercentOrFixed::Percent(percent)) => {
let mut node = KdlNode::new("height");
node.entries_mut()
.push(KdlEntry::new(format!("{}%", percent)));
pane_node_children.nodes_mut().push(node);
},
None => {},
}
match layout.width {
Some(PercentOrFixed::Fixed(fixed_width)) => {
let mut node = KdlNode::new("width");
node.entries_mut()
.push(KdlEntry::new(KdlValue::Base10(fixed_width as i64)));
pane_node_children.nodes_mut().push(node);
},
Some(PercentOrFixed::Percent(percent)) => {
let mut node = KdlNode::new("width");
node.entries_mut()
.push(KdlEntry::new(format!("{}%", percent)));
pane_node_children.nodes_mut().push(node);
},
None => {},
}
match layout.x {
Some(PercentOrFixed::Fixed(fixed_x)) => {
let mut node = KdlNode::new("x");
node.entries_mut()
.push(KdlEntry::new(KdlValue::Base10(fixed_x as i64)));
pane_node_children.nodes_mut().push(node);
},
Some(PercentOrFixed::Percent(percent)) => {
let mut node = KdlNode::new("x");
node.entries_mut()
.push(KdlEntry::new(format!("{}%", percent)));
pane_node_children.nodes_mut().push(node);
},
None => {},
}
match layout.y {
Some(PercentOrFixed::Fixed(fixed_y)) => {
let mut node = KdlNode::new("y");
node.entries_mut()
.push(KdlEntry::new(KdlValue::Base10(fixed_y as i64)));
pane_node_children.nodes_mut().push(node);
},
Some(PercentOrFixed::Percent(percent)) => {
let mut node = KdlNode::new("y");
node.entries_mut()
.push(KdlEntry::new(format!("{}%", percent)));
pane_node_children.nodes_mut().push(node);
},
None => {},
}
match layout.pinned {
Some(true) => {
let mut node = KdlNode::new("pinned");
node.entries_mut().push(KdlEntry::new(KdlValue::Bool(true)));
pane_node_children.nodes_mut().push(node);
},
_ => {},
}
}
fn serialize_start_suspended(command: &Option<String>, pane_node_children: &mut KdlDocument) {
if command.is_some() {
let mut start_suspended_node = KdlNode::new("start_suspended");
start_suspended_node
.entries_mut()
.push(KdlEntry::new(KdlValue::Bool(true)));
pane_node_children.nodes_mut().push(start_suspended_node);
}
}
fn serialize_global_cwd(global_cwd: &Option<PathBuf>) -> Option<KdlNode> {
global_cwd.as_ref().map(|cwd| {
let mut node = KdlNode::new("cwd");
node.push(cwd.display().to_string());
node
})
}
fn serialize_new_tab_template(
new_tab_template: Option<(TiledPaneLayout, Vec<FloatingPaneLayout>)>,
pane_contents: &mut BTreeMap<String, String>,
layout_children_node: &mut KdlDocument,
) {
if let Some((tiled_panes, floating_panes)) = new_tab_template {
let tiled_panes = if &tiled_panes.children_split_direction != &SplitDirection::default() {
vec![tiled_panes]
} else {
tiled_panes.children
};
let mut new_tab_template_node = KdlNode::new("new_tab_template");
let mut new_tab_template_children = KdlDocument::new();
serialize_tiled_and_floating_panes(
&tiled_panes,
floating_panes,
pane_contents,
&mut new_tab_template_children,
);
new_tab_template_node.set_children(new_tab_template_children);
layout_children_node.nodes_mut().push(new_tab_template_node);
}
}
fn serialize_swap_tiled_layouts(
swap_tiled_layouts: Vec<SwapTiledLayout>,
pane_contents: &mut BTreeMap<String, String>,
layout_node_children: &mut KdlDocument,
) {
for swap_tiled_layout in swap_tiled_layouts {
let mut swap_tiled_layout_node = KdlNode::new("swap_tiled_layout");
let mut swap_tiled_layout_node_children = KdlDocument::new();
let swap_tiled_layout_name = swap_tiled_layout.1;
if let Some(name) = swap_tiled_layout_name {
swap_tiled_layout_node
.entries_mut()
.push(KdlEntry::new_prop("name", name.to_owned()));
}
for (layout_constraint, tiled_panes_layout) in swap_tiled_layout.0 {
let tiled_panes_layout =
if &tiled_panes_layout.children_split_direction != &SplitDirection::default() {
vec![tiled_panes_layout]
} else {
tiled_panes_layout.children
};
let mut layout_step_node = KdlNode::new("tab");
let mut layout_step_node_children = KdlDocument::new();
if let Some(layout_constraint_entry) = serialize_layout_constraint(layout_constraint) {
layout_step_node.entries_mut().push(layout_constraint_entry);
}
serialize_tiled_and_floating_panes(
&tiled_panes_layout,
vec![],
pane_contents,
&mut layout_step_node_children,
);
layout_step_node.set_children(layout_step_node_children);
swap_tiled_layout_node_children
.nodes_mut()
.push(layout_step_node);
}
swap_tiled_layout_node.set_children(swap_tiled_layout_node_children);
layout_node_children
.nodes_mut()
.push(swap_tiled_layout_node);
}
}
fn serialize_layout_constraint(layout_constraint: LayoutConstraint) -> Option<KdlEntry> {
match layout_constraint {
LayoutConstraint::MaxPanes(max_panes) => Some(KdlEntry::new_prop(
"max_panes",
KdlValue::Base10(max_panes as i64),
)),
LayoutConstraint::MinPanes(min_panes) => Some(KdlEntry::new_prop(
"min_panes",
KdlValue::Base10(min_panes as i64),
)),
LayoutConstraint::ExactPanes(exact_panes) => Some(KdlEntry::new_prop(
"exact_panes",
KdlValue::Base10(exact_panes as i64),
)),
LayoutConstraint::NoConstraint => None,
}
}
fn serialize_swap_floating_layouts(
swap_floating_layouts: Vec<SwapFloatingLayout>,
pane_contents: &mut BTreeMap<String, String>,
layout_children_node: &mut KdlDocument,
) {
for swap_floating_layout in swap_floating_layouts {
let mut swap_floating_layout_node = KdlNode::new("swap_floating_layout");
let mut swap_floating_layout_node_children = KdlDocument::new();
let swap_floating_layout_name = swap_floating_layout.1;
if let Some(name) = swap_floating_layout_name {
swap_floating_layout_node
.entries_mut()
.push(KdlEntry::new_prop("name", name.to_owned()));
}
for (layout_constraint, floating_panes_layout) in swap_floating_layout.0 {
let mut layout_step_node = KdlNode::new("floating_panes");
let mut layout_step_node_children = KdlDocument::new();
if let Some(layout_constraint_entry) = serialize_layout_constraint(layout_constraint) {
layout_step_node.entries_mut().push(layout_constraint_entry);
}
for floating_pane_layout in floating_panes_layout {
let floating_pane_node =
serialize_floating_pane(&floating_pane_layout, pane_contents);
layout_step_node_children
.nodes_mut()
.push(floating_pane_node);
}
layout_step_node.set_children(layout_step_node_children);
swap_floating_layout_node_children
.nodes_mut()
.push(layout_step_node);
}
swap_floating_layout_node.set_children(swap_floating_layout_node_children);
layout_children_node
.nodes_mut()
.push(swap_floating_layout_node);
}
}
fn serialize_multiple_tabs(
tabs: Vec<(String, TabLayoutManifest)>,
pane_contents: &mut BTreeMap<String, String>,
) -> Result<Vec<KdlNode>, &'static str> {
let mut serialized_tabs: Vec<KdlNode> = vec![];
for (tab_name, tab_layout_manifest) in tabs {
let tiled_panes = tab_layout_manifest.tiled_panes;
let floating_panes = tab_layout_manifest.floating_panes;
let hide_floating_panes = tab_layout_manifest.hide_floating_panes;
let serialized = serialize_tab(
tab_name.clone(),
tab_layout_manifest.is_focused,
hide_floating_panes,
&tiled_panes,
&floating_panes,
pane_contents,
);
if let Some(serialized) = serialized {
serialized_tabs.push(serialized);
} else {
return Err("Failed to serialize session state");
}
}
Ok(serialized_tabs)
}
fn serialize_floating_pane(
layout: &FloatingPaneLayout,
pane_contents: &mut BTreeMap<String, String>,
) -> KdlNode {
let mut floating_pane_node = KdlNode::new("pane");
let mut floating_pane_node_children = KdlDocument::new();
let (command, args) = extract_command_and_args(&layout.run);
let (plugin, plugin_config) = extract_plugin_and_config(&layout.run);
let (edit, _line_number) = extract_edit_and_line_number(&layout.run);
let cwd = layout.run.as_ref().and_then(|r| r.get_cwd());
let has_children = false;
serialize_pane_title_and_attributes(
&command,
&edit,
&layout.name,
cwd,
layout.focus,
&layout.pane_initial_contents,
pane_contents,
has_children,
&mut floating_pane_node,
);
serialize_start_suspended(&command, &mut floating_pane_node_children);
serialize_floating_layout_attributes(&layout, &mut floating_pane_node_children);
serialize_args(args, &mut floating_pane_node_children);
serialize_plugin(plugin, plugin_config, &mut floating_pane_node_children);
floating_pane_node.set_children(floating_pane_node_children);
floating_pane_node
}
fn stack_layout_from_manifest(
geoms: &Vec<PaneLayoutManifest>,
split_size: Option<SplitSize>,
) -> Option<TiledPaneLayout> {
let mut children_stacks: HashMap<usize, Vec<PaneLayoutManifest>> = HashMap::new();
for p in geoms {
if let Some(stack_id) = p.geom.stacked {
children_stacks
.entry(stack_id)
.or_insert_with(Default::default)
.push(p.clone());
}
}
let mut stack_nodes = vec![];
for (_stack_id, stacked_panes) in children_stacks.into_iter() {
stack_nodes.push(TiledPaneLayout {
split_size,
children: stacked_panes
.iter()
.map(|p| tiled_pane_layout_from_manifest(Some(p), None))
.collect(),
children_are_stacked: true,
..Default::default()
})
}
if stack_nodes.len() == 1 {
// if there's only one stack, we return it without a wrapper
stack_nodes.iter().next().cloned()
} else {
// here there is more than one stack, so we wrap it in a logical container node
Some(TiledPaneLayout {
split_size,
children: stack_nodes,
..Default::default()
})
}
}
fn tiled_pane_layout_from_manifest(
manifest: Option<&PaneLayoutManifest>,
split_size: Option<SplitSize>,
) -> TiledPaneLayout {
let (run, borderless, is_expanded_in_stack, name, focus, pane_initial_contents) = manifest
.map(|g| {
let mut run = g.run.clone();
if let Some(cwd) = &g.cwd {
if let Some(run) = run.as_mut() {
run.add_cwd(cwd);
} else {
run = Some(Run::Cwd(cwd.clone()));
}
}
(
run,
g.is_borderless,
g.geom.is_stacked() && g.geom.rows.inner > 1,
g.title.clone(),
Some(g.is_focused),
g.pane_contents.clone(),
)
})
.unwrap_or((None, false, false, None, None, None));
TiledPaneLayout {
split_size,
run,
borderless,
is_expanded_in_stack,
name,
focus,
pane_initial_contents,
..Default::default()
}
}
/// Tab-level parsing
fn get_tiled_panes_layout_from_panegeoms(
geoms: &Vec<PaneLayoutManifest>,
split_size: Option<SplitSize>,
) -> Option<TiledPaneLayout> {
let (children_split_direction, splits) = match get_splits(&geoms) {
Some(x) => x,
None => {
if geoms.len() > 1 {
// this can only happen if all geoms belong to one or more stacks
// since stack splits are discounted in the get_splits method
return stack_layout_from_manifest(geoms, split_size);
} else {
return Some(tiled_pane_layout_from_manifest(
geoms.iter().next(),
split_size,
));
}
},
};
let mut children = Vec::new();
let mut remaining_geoms = geoms.clone();
let mut new_geoms = Vec::new();
let mut new_constraints = Vec::new();
for i in 1..splits.len() {
let (v_min, v_max) = (splits[i - 1], splits[i]);
let subgeoms: Vec<PaneLayoutManifest>;
(subgeoms, remaining_geoms) = match children_split_direction {
SplitDirection::Horizontal => remaining_geoms
.clone()
.into_iter()
.partition(|g| g.geom.y + g.geom.rows.as_usize() <= v_max),
SplitDirection::Vertical => remaining_geoms
.clone()
.into_iter()
.partition(|g| g.geom.x + g.geom.cols.as_usize() <= v_max),
};
match get_domain_constraint(&subgeoms, &children_split_direction, (v_min, v_max)) {
Some(constraint) => {
new_geoms.push(subgeoms);
new_constraints.push(constraint);
},
None => {
return None;
},
}
}
let new_split_sizes = get_split_sizes(&new_constraints);
for (subgeoms, subsplit_size) in new_geoms.iter().zip(new_split_sizes) {
match get_tiled_panes_layout_from_panegeoms(&subgeoms, subsplit_size) {
Some(child) => {
children.push(child);
},
None => {
return None;
},
}
}
let children_are_stacked = children_split_direction == SplitDirection::Horizontal
&& all_geoms_are_from_the_same_stack(&new_geoms);
Some(TiledPaneLayout {
children_split_direction,
split_size,
children,
children_are_stacked,
..Default::default()
})
}
fn all_geoms_are_from_the_same_stack(manifests: &Vec<Vec<PaneLayoutManifest>>) -> bool {
let mut stack_ids = HashSet::new();
for manifest_group in manifests {
for pane_layout_manifest in manifest_group {
stack_ids.insert(pane_layout_manifest.geom.stacked);
}
}
stack_ids.len() == 1 && !stack_ids.contains(&None)
}
fn get_floating_panes_layout_from_panegeoms(
manifests: &Vec<PaneLayoutManifest>,
) -> Vec<FloatingPaneLayout> {
manifests
.iter()
.map(|m| {
let mut run = m.run.clone();
if let Some(cwd) = &m.cwd {
run.as_mut().map(|r| r.add_cwd(cwd));
}
FloatingPaneLayout {
name: m.title.clone(),
height: Some(m.geom.rows.into()),
width: Some(m.geom.cols.into()),
x: Some(PercentOrFixed::Fixed(m.geom.x)),
y: Some(PercentOrFixed::Fixed(m.geom.y)),
pinned: Some(m.geom.is_pinned),
run,
focus: Some(m.is_focused),
already_running: false,
pane_initial_contents: m.pane_contents.clone(),
logical_position: None,
}
})
.collect()
}
fn get_x_lims(geoms: &Vec<PaneLayoutManifest>) -> Option<(usize, usize)> {
match (
geoms.iter().map(|g| g.geom.x).min(),
geoms
.iter()
.map(|g| g.geom.x + g.geom.cols.as_usize())
.max(),
) {
(Some(x_min), Some(x_max)) => Some((x_min, x_max)),
_ => None,
}
}
fn get_y_lims(geoms: &Vec<PaneLayoutManifest>) -> Option<(usize, usize)> {
match (
geoms.iter().map(|g| g.geom.y).min(),
geoms
.iter()
.map(|g| g.geom.y + g.geom.rows.as_usize())
.max(),
) {
(Some(y_min), Some(y_max)) => Some((y_min, y_max)),
_ => None,
}
}
/// Returns the `SplitDirection` as well as the values, on the axis
/// perpendicular the `SplitDirection`, for which there is a split spanning
/// the max_cols or max_rows of the domain. The values are ordered
/// increasingly and contains the boundaries of the domain.
fn get_splits(geoms: &Vec<PaneLayoutManifest>) -> Option<(SplitDirection, Vec<usize>)> {
if geoms.len() == 1 {
return None;
}
let (x_lims, y_lims) = match (get_x_lims(&geoms), get_y_lims(&geoms)) {
(Some(x_lims), Some(y_lims)) => (x_lims, y_lims),
_ => return None,
};
let mut direction = SplitDirection::default();
let mut splits = match direction {
SplitDirection::Vertical => get_col_splits(&geoms, &x_lims, &y_lims),
SplitDirection::Horizontal => get_row_splits(&geoms, &x_lims, &y_lims),
};
if splits.len() <= 2 {
// ie only the boundaries are present and no real split has been found
direction = !direction;
splits = match direction {
SplitDirection::Vertical => get_col_splits(&geoms, &x_lims, &y_lims),
SplitDirection::Horizontal => get_row_splits(&geoms, &x_lims, &y_lims),
};
}
if splits.len() <= 2 {
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/web_server_commands.rs | zellij-utils/src/web_server_commands.rs | use crate::consts::WEBSERVER_SOCKET_PATH;
use crate::errors::prelude::*;
use crate::web_server_contract::web_server_contract::InstructionForWebServer as ProtoInstructionForWebServer;
use interprocess::local_socket::LocalSocketStream;
use prost::Message;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{BufWriter, Write};
use std::os::unix::fs::FileTypeExt;
pub fn shutdown_all_webserver_instances() -> Result<()> {
let entries = fs::read_dir(&*WEBSERVER_SOCKET_PATH)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if let Some(file_name) = path.file_name() {
if let Some(_file_name_str) = file_name.to_str() {
let metadata = entry.metadata()?;
let file_type = metadata.file_type();
if file_type.is_socket() {
match create_webserver_sender(path.to_str().unwrap_or("")) {
Ok(mut sender) => {
let _ = send_webserver_instruction(
&mut sender,
InstructionForWebServer::ShutdownWebServer,
);
},
Err(_) => {
// no-op
},
}
}
}
}
}
Ok(())
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum InstructionForWebServer {
ShutdownWebServer,
}
pub fn create_webserver_sender(path: &str) -> Result<BufWriter<LocalSocketStream>> {
let stream = LocalSocketStream::connect(path)?;
Ok(BufWriter::new(stream))
}
pub fn send_webserver_instruction(
sender: &mut BufWriter<LocalSocketStream>,
instruction: InstructionForWebServer,
) -> Result<()> {
// Convert to protobuf and send with length prefix
let proto_instruction: ProtoInstructionForWebServer = instruction.into();
let encoded = proto_instruction.encode_to_vec();
let len = encoded.len() as u32;
// Write length prefix
sender.write_all(&len.to_le_bytes())?;
// Write protobuf message
sender.write_all(&encoded)?;
sender.flush()?;
Ok(())
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/lib.rs | zellij-utils/src/lib.rs | pub mod cli;
pub mod client_server_contract;
pub mod consts;
pub mod data;
pub mod envs;
pub mod errors;
pub mod home;
pub mod input;
pub mod kdl;
pub mod pane_size;
pub mod plugin_api;
pub mod position;
pub mod session_serialization;
pub mod setup;
pub mod shared;
// The following modules can't be used when targeting wasm
#[cfg(not(target_family = "wasm"))]
pub mod channels; // Requires async_std
#[cfg(not(target_family = "wasm"))]
pub mod common_path;
#[cfg(not(target_family = "wasm"))]
pub mod downloader; // Requires async_std
#[cfg(not(target_family = "wasm"))]
pub mod ipc; // Requires interprocess
#[cfg(not(target_family = "wasm"))]
pub mod logging; // Requires log4rs
#[cfg(all(not(target_family = "wasm"), feature = "web_server_capability"))]
pub mod remote_session_tokens;
#[cfg(not(target_family = "wasm"))]
pub mod sessions;
#[cfg(all(not(target_family = "wasm"), feature = "web_server_capability"))]
pub mod web_authentication_tokens;
#[cfg(all(not(target_family = "wasm"), feature = "web_server_capability"))]
pub mod web_server_commands;
#[cfg(all(not(target_family = "wasm"), feature = "web_server_capability"))]
pub mod web_server_contract;
// TODO(hartan): Remove this re-export for the next minor release.
pub use ::prost;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/channels.rs | zellij-utils/src/channels.rs | //! Definitions and helpers for sending and receiving messages between threads.
use async_std::task_local;
use std::cell::RefCell;
use crate::errors::{get_current_ctx, ErrorContext};
pub use crossbeam::channel::{
bounded, unbounded, Receiver, RecvError, Select, SendError, Sender, TrySendError,
};
/// An [MPSC](mpsc) asynchronous channel with added error context.
pub type ChannelWithContext<T> = (Sender<(T, ErrorContext)>, Receiver<(T, ErrorContext)>);
/// Sends messages on an [MPSC](std::sync::mpsc) channel, along with an [`ErrorContext`],
/// synchronously or asynchronously depending on the underlying [`SenderType`].
#[derive(Clone)]
pub struct SenderWithContext<T> {
sender: Sender<(T, ErrorContext)>,
}
impl<T: Clone> SenderWithContext<T> {
pub fn new(sender: Sender<(T, ErrorContext)>) -> Self {
Self { sender }
}
/// Sends an event, along with the current [`ErrorContext`], on this
/// [`SenderWithContext`]'s channel.
pub fn send(&self, event: T) -> Result<(), SendError<(T, ErrorContext)>> {
let err_ctx = get_current_ctx();
self.sender.send((event, err_ctx))
}
}
thread_local!(
/// A key to some thread local storage (TLS) that holds a representation of the thread's call
/// stack in the form of an [`ErrorContext`].
pub static OPENCALLS: RefCell<ErrorContext> = RefCell::default()
);
task_local! {
/// A key to some task local storage that holds a representation of the task's call
/// stack in the form of an [`ErrorContext`].
pub static ASYNCOPENCALLS: RefCell<ErrorContext> = RefCell::default()
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/pane_size.rs | zellij-utils/src/pane_size.rs | use serde::{Deserialize, Serialize};
use std::{
fmt::Display,
hash::{Hash, Hasher},
};
use crate::data::FloatingPaneCoordinates;
use crate::input::layout::{SplitDirection, SplitSize};
use crate::position::Position;
/// Contains the position and size of a [`Pane`], or more generally of any terminal, measured
/// in character rows and columns.
#[derive(Clone, Copy, Default, Debug, Serialize, Deserialize)]
pub struct PaneGeom {
pub x: usize,
pub y: usize,
pub rows: Dimension,
pub cols: Dimension,
pub stacked: Option<usize>, // usize - stack id
pub is_pinned: bool, // only relevant to floating panes
pub logical_position: Option<usize>, // relevant when placing this pane in a layout
}
impl PartialEq for PaneGeom {
fn eq(&self, other: &Self) -> bool {
// compare all except is_pinned
// NOTE: Keep this in sync with what the `Hash` trait impl does.
self.x == other.x
&& self.y == other.y
&& self.rows == other.rows
&& self.cols == other.cols
&& self.stacked == other.stacked
}
}
impl std::hash::Hash for PaneGeom {
fn hash<H: Hasher>(&self, state: &mut H) {
// NOTE: Keep this in sync with what the `PartiqlEq` trait impl does.
self.x.hash(state);
self.y.hash(state);
self.rows.hash(state);
self.cols.hash(state);
self.stacked.hash(state);
}
}
impl Eq for PaneGeom {}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Viewport {
pub x: usize,
pub y: usize,
pub rows: usize,
pub cols: usize,
}
impl Viewport {
pub fn has_positive_size(&self) -> bool {
self.rows > 0 && self.cols > 0
}
}
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct Offset {
pub top: usize,
pub bottom: usize,
pub right: usize,
pub left: usize,
}
#[derive(Clone, Copy, Default, PartialEq, Debug, Serialize, Deserialize)]
pub struct Size {
pub rows: usize,
pub cols: usize,
}
#[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct SizeInPixels {
pub height: usize,
pub width: usize,
}
#[derive(Eq, Clone, Copy, PartialEq, Debug, Serialize, Deserialize, Hash)]
pub struct Dimension {
pub constraint: Constraint,
pub(crate) inner: usize,
}
impl Default for Dimension {
fn default() -> Self {
Self::percent(100.0)
}
}
impl Dimension {
pub fn fixed(size: usize) -> Dimension {
Self {
constraint: Constraint::Fixed(size),
inner: size,
}
}
pub fn percent(percent: f64) -> Dimension {
Self {
constraint: Constraint::Percent(percent),
inner: 1,
}
}
pub fn as_usize(&self) -> usize {
self.inner
}
pub fn as_percent(&self) -> Option<f64> {
if let Constraint::Percent(p) = self.constraint {
Some(p)
} else {
None
}
}
pub fn set_percent(&mut self, percent: f64) {
self.constraint = Constraint::Percent(percent);
}
pub fn set_inner(&mut self, inner: usize) {
self.inner = inner;
}
pub fn adjust_inner(&mut self, full_size: usize) -> f64 {
// returns the leftover from
// rounding if any
// TODO: elsewhere?
match self.constraint {
Constraint::Percent(percent) => {
let new_inner = (percent / 100.0) * full_size as f64;
let rounded = new_inner.floor();
let leftover = rounded - new_inner;
self.set_inner(rounded as usize);
leftover
},
Constraint::Fixed(fixed_size) => {
self.set_inner(fixed_size);
0.0
},
}
}
pub fn increase_inner(&mut self, by: usize) {
self.inner += by;
}
pub fn decrease_inner(&mut self, by: usize) {
self.inner = self.inner.saturating_sub(by);
}
pub fn is_fixed(&self) -> bool {
matches!(self.constraint, Constraint::Fixed(_))
}
pub fn is_percent(&self) -> bool {
matches!(self.constraint, Constraint::Percent(_))
}
pub fn from_split_size(split_size: SplitSize, full_size: usize) -> Self {
match split_size {
SplitSize::Fixed(fixed) => Dimension {
constraint: Constraint::Fixed(fixed),
inner: fixed,
},
SplitSize::Percent(percent) => Dimension {
constraint: Constraint::Percent(percent as f64),
inner: ((percent as f64 / 100.0) * full_size as f64).floor() as usize,
},
}
}
pub fn split_out(&mut self, by: f64) -> Self {
match self.constraint {
Constraint::Percent(percent) => {
let split_out_value = percent / by;
let split_out_inner_value = self.inner / by as usize;
self.constraint = Constraint::Percent(percent - split_out_value);
self.inner = self.inner.saturating_sub(split_out_inner_value);
let mut split_out_dimension = Self::percent(split_out_value);
split_out_dimension.inner = split_out_inner_value;
split_out_dimension
},
Constraint::Fixed(fixed) => {
let split_out_value = fixed / by as usize;
self.constraint = Constraint::Fixed(fixed - split_out_value);
Self::fixed(split_out_value)
},
}
}
pub fn reduce_by(&mut self, by: f64, by_inner: usize) {
match self.constraint {
Constraint::Percent(percent) => {
self.constraint = Constraint::Percent(percent - by);
self.inner = self.inner.saturating_sub(by_inner);
},
Constraint::Fixed(_fixed) => {
log::error!("Cannot reduce_by fixed dimensions");
},
}
}
}
#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
pub enum Constraint {
/// Constrains the dimension to a fixed, integer number of rows / columns
Fixed(usize),
/// Constrains the dimension to a flexible percent size of the total screen
Percent(f64),
}
impl Display for Constraint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let actual = match self {
Constraint::Fixed(v) => *v as f64,
Constraint::Percent(v) => *v,
};
write!(f, "{}", actual)?;
Ok(())
}
}
#[allow(clippy::derive_hash_xor_eq)]
impl Hash for Constraint {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Constraint::Fixed(size) => size.hash(state),
Constraint::Percent(size) => (*size as usize).hash(state),
}
}
}
impl Eq for Constraint {}
impl PaneGeom {
pub fn contains(&self, point: &Position) -> bool {
let col = point.column.0 as usize;
let row = point.line.0 as usize;
self.x <= col
&& col < self.x + self.cols.as_usize()
&& self.y <= row
&& row < self.y + self.rows.as_usize()
}
pub fn is_at_least_minimum_size(&self) -> bool {
self.rows.as_usize() > 0 && self.cols.as_usize() > 0
}
pub fn is_flexible_in_direction(&self, split_direction: SplitDirection) -> bool {
match split_direction {
SplitDirection::Vertical => self.cols.is_percent(),
SplitDirection::Horizontal => self.rows.is_percent(),
}
}
pub fn adjust_coordinates(
&mut self,
floating_pane_coordinates: FloatingPaneCoordinates,
viewport: Viewport,
) {
if let Some(x) = floating_pane_coordinates.x {
self.x = x.to_fixed(viewport.cols);
}
if let Some(y) = floating_pane_coordinates.y {
self.y = y.to_fixed(viewport.rows);
}
if let Some(height) = floating_pane_coordinates.height {
self.rows = Dimension::from_split_size(height, viewport.rows);
}
if let Some(width) = floating_pane_coordinates.width {
self.cols = Dimension::from_split_size(width, viewport.cols);
}
if self.x < viewport.x {
self.x = viewport.x;
} else if self.x > viewport.x + viewport.cols {
self.x = (viewport.x + viewport.cols).saturating_sub(self.cols.as_usize());
}
if self.y < viewport.y {
self.y = viewport.y;
} else if self.y > viewport.y + viewport.rows {
self.y = (viewport.y + viewport.rows).saturating_sub(self.rows.as_usize());
}
if self.x + self.cols.as_usize() > viewport.x + viewport.cols {
let new_cols = (viewport.x + viewport.cols).saturating_sub(self.x);
self.cols.set_inner(new_cols);
}
if self.y + self.rows.as_usize() > viewport.y + viewport.rows {
let new_rows = (viewport.y + viewport.rows).saturating_sub(self.y);
self.rows.set_inner(new_rows);
}
}
pub fn combine_vertically_with(&self, geom_below: &PaneGeom) -> Option<Self> {
match (self.rows.constraint, geom_below.rows.constraint) {
(Constraint::Percent(self_percent), Constraint::Percent(geom_below_percent)) => {
let mut combined = self.clone();
combined.rows = Dimension::percent(self_percent + geom_below_percent);
combined.rows.inner = self.rows.inner + geom_below.rows.inner;
Some(combined)
},
_ => {
log::error!("Can't combine fixed panes");
None
},
}
}
pub fn combine_horizontally_with(&self, geom_to_the_right: &PaneGeom) -> Option<Self> {
match (self.cols.constraint, geom_to_the_right.cols.constraint) {
(Constraint::Percent(self_percent), Constraint::Percent(geom_to_the_right_percent)) => {
let mut combined = self.clone();
combined.cols = Dimension::percent(self_percent + geom_to_the_right_percent);
combined.cols.inner = self.cols.inner + geom_to_the_right.cols.inner;
Some(combined)
},
_ => {
log::error!("Can't combine fixed panes");
None
},
}
}
pub fn combine_vertically_with_many(&self, geoms_below: &Vec<PaneGeom>) -> Option<Self> {
// here we expect the geoms to be sorted by their y and be contiguous (i.e. same x and
// width, no overlaps) and be below self
let mut combined = self.clone();
for geom_below in geoms_below {
match (combined.rows.constraint, geom_below.rows.constraint) {
(
Constraint::Percent(combined_percent),
Constraint::Percent(geom_below_percent),
) => {
let new_rows_inner = combined.rows.inner + geom_below.rows.inner;
combined.rows = Dimension::percent(combined_percent + geom_below_percent);
combined.rows.inner = new_rows_inner;
},
_ => {
log::error!("Can't combine fixed panes");
return None;
},
}
}
Some(combined)
}
pub fn combine_horizontally_with_many(
&self,
geoms_to_the_right: &Vec<PaneGeom>,
) -> Option<Self> {
// here we expect the geoms to be sorted by their x and be contiguous (i.e. same x and
// width, no overlaps) and be right of self
let mut combined = self.clone();
for geom_to_the_right in geoms_to_the_right {
match (combined.cols.constraint, geom_to_the_right.cols.constraint) {
(
Constraint::Percent(combined_percent),
Constraint::Percent(geom_to_the_right_percent),
) => {
let new_cols = combined.cols.inner + geom_to_the_right.cols.inner;
combined.cols =
Dimension::percent(combined_percent + geom_to_the_right_percent);
combined.cols.inner = new_cols;
},
_ => {
log::error!("Can't combine fixed panes");
return None;
},
}
}
Some(combined)
}
pub fn is_stacked(&self) -> bool {
self.stacked.is_some()
}
}
impl Display for PaneGeom {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{{ ")?;
write!(f, r#""x": {},"#, self.x)?;
write!(f, r#""y": {},"#, self.y)?;
write!(f, r#""cols": {},"#, self.cols.constraint)?;
write!(f, r#""rows": {},"#, self.rows.constraint)?;
write!(f, r#""stacked": {:?}"#, self.stacked)?;
write!(f, r#""logical_position": {:?}"#, self.logical_position)?;
write!(f, " }}")?;
Ok(())
}
}
impl Offset {
pub fn frame(size: usize) -> Self {
Self {
top: size,
bottom: size,
right: size,
left: size,
}
}
pub fn shift_right_and_top(right: usize, top: usize) -> Self {
Self {
right,
top,
..Default::default()
}
}
pub fn shift_right(right: usize) -> Self {
Self {
right,
..Default::default()
}
}
pub fn shift_right_top_and_bottom(right: usize, top: usize, bottom: usize) -> Self {
Self {
right,
top,
bottom,
..Default::default()
}
}
// FIXME: This should be top and left, not bottom and right, but `boundaries.rs` would need
// some changing
pub fn shift(bottom: usize, right: usize) -> Self {
Self {
bottom,
right,
..Default::default()
}
}
}
impl From<PaneGeom> for Viewport {
fn from(pane: PaneGeom) -> Self {
Self {
x: pane.x,
y: pane.y,
rows: pane.rows.as_usize(),
cols: pane.cols.as_usize(),
}
}
}
impl From<Size> for Viewport {
fn from(size: Size) -> Self {
Self {
rows: size.rows,
cols: size.cols,
..Default::default()
}
}
}
impl From<&PaneGeom> for Size {
fn from(pane_geom: &PaneGeom) -> Self {
Self {
rows: pane_geom.rows.as_usize(),
cols: pane_geom.cols.as_usize(),
}
}
}
impl From<&Size> for PaneGeom {
fn from(size: &Size) -> Self {
let mut rows = Dimension::percent(100.0);
let mut cols = Dimension::percent(100.0);
rows.set_inner(size.rows);
cols.set_inner(size.cols);
Self {
rows,
cols,
..Default::default()
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/cli.rs | zellij-utils/src/cli.rs | use crate::data::{Direction, InputMode, Resize, UnblockCondition};
use crate::setup::Setup;
use crate::{
consts::{ZELLIJ_CONFIG_DIR_ENV, ZELLIJ_CONFIG_FILE_ENV},
input::{layout::PluginUserConfiguration, options::Options},
};
use clap::{Args, Parser, Subcommand};
use serde::{Deserialize, Serialize};
use std::net::IpAddr;
use std::path::PathBuf;
use url::Url;
fn validate_session(name: &str) -> Result<String, String> {
#[cfg(unix)]
{
use crate::consts::ZELLIJ_SOCK_MAX_LENGTH;
let mut socket_path = crate::consts::ZELLIJ_SOCK_DIR.clone();
socket_path.push(name);
if socket_path.as_os_str().len() >= ZELLIJ_SOCK_MAX_LENGTH {
// socket path must be less than 108 bytes
let available_length = ZELLIJ_SOCK_MAX_LENGTH
.saturating_sub(socket_path.as_os_str().len())
.saturating_sub(1);
return Err(format!(
"session name must be less than {} characters",
available_length
));
};
};
Ok(name.to_owned())
}
#[derive(Parser, Default, Debug, Clone, Serialize, Deserialize)]
#[clap(version, name = "zellij")]
pub struct CliArgs {
/// Maximum panes on screen, caution: opening more panes will close old ones
#[clap(long, value_parser)]
pub max_panes: Option<usize>,
/// Change where zellij looks for plugins
#[clap(long, value_parser, overrides_with = "data_dir")]
pub data_dir: Option<PathBuf>,
/// Run server listening at the specified socket path
#[clap(long, value_parser, hide = true, overrides_with = "server")]
pub server: Option<PathBuf>,
/// Specify name of a new session
#[clap(long, short, overrides_with = "session", value_parser = validate_session)]
pub session: Option<String>,
/// Name of a predefined layout inside the layout directory or the path to a layout file
/// if inside a session (or using the --session flag) will be added to the session as a new tab
/// or tabs, otherwise will start a new session
#[clap(short, long, value_parser, overrides_with = "layout")]
pub layout: Option<PathBuf>,
/// Name of a predefined layout inside the layout directory or the path to a layout file
/// Will always start a new session, even if inside an existing session
#[clap(short, long, value_parser, overrides_with = "new_session_with_layout")]
pub new_session_with_layout: Option<PathBuf>,
/// Change where zellij looks for the configuration file
#[clap(short, long, overrides_with = "config", env = ZELLIJ_CONFIG_FILE_ENV, value_parser)]
pub config: Option<PathBuf>,
/// Change where zellij looks for the configuration directory
#[clap(long, overrides_with = "config_dir", env = ZELLIJ_CONFIG_DIR_ENV, value_parser)]
pub config_dir: Option<PathBuf>,
#[clap(subcommand)]
pub command: Option<Command>,
/// Specify emitting additional debug information
#[clap(short, long, value_parser)]
pub debug: bool,
}
impl CliArgs {
pub fn is_setup_clean(&self) -> bool {
if let Some(Command::Setup(ref setup)) = &self.command {
if setup.clean {
return true;
}
}
false
}
pub fn options(&self) -> Option<Options> {
if let Some(Command::Options(options)) = &self.command {
return Some(options.clone());
}
None
}
}
#[derive(Debug, Subcommand, Clone, Serialize, Deserialize)]
pub enum Command {
/// Change the behaviour of zellij
#[clap(name = "options", value_parser)]
Options(Options),
/// Setup zellij and check its configuration
#[clap(name = "setup", value_parser)]
Setup(Setup),
/// Run a web server to serve terminal sessions
#[clap(name = "web", value_parser)]
Web(WebCli),
/// Explore existing zellij sessions
#[clap(flatten)]
Sessions(Sessions),
}
#[derive(Debug, Clone, Args, Serialize, Deserialize)]
pub struct WebCli {
/// Start the server (default unless other arguments are specified)
#[clap(long, value_parser, display_order = 1)]
pub start: bool,
/// Stop the server
#[clap(long, value_parser, exclusive(true), display_order = 2)]
pub stop: bool,
/// Get the server status
#[clap(long, value_parser, exclusive(true), display_order = 3)]
pub status: bool,
/// Run the server in the background
#[clap(
short,
long,
value_parser,
conflicts_with_all(&["stop", "status", "create-token", "revoke-token", "revoke-all-tokens"]),
display_order = 4
)]
pub daemonize: bool,
/// Create a login token for the web interface, will only be displayed once and cannot later be
/// retrieved. Returns the token name and the token.
#[clap(long, value_parser, exclusive(true), display_order = 5)]
pub create_token: bool,
/// Optional name for the token
#[clap(long, value_parser, value_name = "TOKEN_NAME", display_order = 6)]
pub token_name: Option<String>,
/// Create a read-only login token (can only attach to existing sessions as watcher)
#[clap(long, value_parser, exclusive(true), display_order = 7)]
pub create_read_only_token: bool,
/// Revoke a login token by its name
#[clap(
long,
value_parser,
exclusive(true),
value_name = "TOKEN NAME",
display_order = 8
)]
pub revoke_token: Option<String>,
/// Revoke all login tokens
#[clap(long, value_parser, exclusive(true), display_order = 9)]
pub revoke_all_tokens: bool,
/// List token names and their creation dates (cannot show actual tokens)
#[clap(long, value_parser, exclusive(true), display_order = 10)]
pub list_tokens: bool,
/// The ip address to listen on locally for connections (defaults to 127.0.0.1)
#[clap(
long,
value_parser,
conflicts_with_all(&["stop", "status", "create-token", "revoke-token", "revoke-all-tokens"]),
display_order = 11
)]
pub ip: Option<IpAddr>,
/// The port to listen on locally for connections (defaults to 8082)
#[clap(
long,
value_parser,
conflicts_with_all(&["stop", "status", "create-token", "revoke-token", "revoke-all-tokens"]),
display_order = 12
)]
pub port: Option<u16>,
/// The path to the SSL certificate (required if not listening on 127.0.0.1)
#[clap(
long,
value_parser,
conflicts_with_all(&["stop", "status", "create-token", "revoke-token", "revoke-all-tokens"]),
display_order = 13
)]
pub cert: Option<PathBuf>,
/// The path to the SSL key (required if not listening on 127.0.0.1)
#[clap(
long,
value_parser,
conflicts_with_all(&["stop", "status", "create-token", "revoke-token", "revoke-all-tokens"]),
display_order = 14
)]
pub key: Option<PathBuf>,
}
impl WebCli {
pub fn get_start(&self) -> bool {
self.start
|| !(self.stop
|| self.status
|| self.create_token
|| self.create_read_only_token
|| self.revoke_token.is_some()
|| self.revoke_all_tokens
|| self.list_tokens)
}
}
#[derive(Debug, Subcommand, Clone, Serialize, Deserialize)]
pub enum SessionCommand {
/// Change the behaviour of zellij
#[clap(name = "options")]
Options(Options),
}
#[derive(Debug, Subcommand, Clone, Serialize, Deserialize)]
pub enum Sessions {
/// List active sessions
#[clap(visible_alias = "ls")]
ListSessions {
/// Do not add colors and formatting to the list (useful for parsing)
#[clap(short, long, value_parser, takes_value(false), default_value("false"))]
no_formatting: bool,
/// Print just the session name
#[clap(short, long, value_parser, takes_value(false), default_value("false"))]
short: bool,
/// List the sessions in reverse order (default is ascending order)
#[clap(short, long, value_parser, takes_value(false), default_value("false"))]
reverse: bool,
},
/// List existing plugin aliases
#[clap(visible_alias = "la")]
ListAliases,
/// Attach to a session
#[clap(visible_alias = "a")]
Attach {
/// Name of the session to attach to.
#[clap(value_parser)]
session_name: Option<String>,
/// Create a session if one does not exist.
#[clap(short, long, value_parser)]
create: bool,
/// Create a detached session in the background if one does not exist
#[clap(short('b'), long, value_parser)]
create_background: bool,
/// Number of the session index in the active sessions ordered creation date.
#[clap(long, value_parser)]
index: Option<usize>,
/// Change the behaviour of zellij
#[clap(subcommand, name = "options")]
options: Option<Box<SessionCommand>>,
/// If resurrecting a dead session, immediately run all its commands on startup
#[clap(short, long, value_parser, takes_value(false), default_value("false"))]
force_run_commands: bool,
/// Authentication token for remote sessions
#[clap(short('t'), long, value_parser)]
token: Option<String>,
/// Save session for automatic re-authentication (4 weeks)
#[clap(short('r'), long, value_parser)]
remember: bool,
/// Delete saved session before connecting
#[clap(long, value_parser)]
forget: bool,
},
/// Watch a session (read-only)
#[clap(visible_alias = "w")]
Watch {
/// Name of the session to watch
#[clap(value_parser)]
session_name: Option<String>,
},
/// Kill a specific session
#[clap(visible_alias = "k")]
KillSession {
/// Name of target session
#[clap(value_parser)]
target_session: Option<String>,
},
/// Delete a specific session
#[clap(visible_alias = "d")]
DeleteSession {
/// Name of target session
#[clap(value_parser)]
target_session: Option<String>,
/// Kill the session if it's running before deleting it
#[clap(short, long, value_parser, takes_value(false), default_value("false"))]
force: bool,
},
/// Kill all sessions
#[clap(visible_alias = "ka")]
KillAllSessions {
/// Automatic yes to prompts
#[clap(short, long, value_parser)]
yes: bool,
},
/// Delete all sessions
#[clap(visible_alias = "da")]
DeleteAllSessions {
/// Automatic yes to prompts
#[clap(short, long, value_parser)]
yes: bool,
/// Kill the sessions if they're running before deleting them
#[clap(short, long, value_parser, takes_value(false), default_value("false"))]
force: bool,
},
/// Send actions to a specific session
#[clap(visible_alias = "ac")]
#[clap(subcommand)]
Action(CliAction),
/// Run a command in a new pane
#[clap(visible_alias = "r")]
Run {
/// Command to run
#[clap(last(true), required(true))]
command: Vec<String>,
/// Direction to open the new pane in
#[clap(short, long, value_parser, conflicts_with("floating"))]
direction: Option<Direction>,
/// Change the working directory of the new pane
#[clap(long, value_parser)]
cwd: Option<PathBuf>,
/// Open the new pane in floating mode
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
floating: bool,
/// Open the new pane in place of the current pane, temporarily suspending it
#[clap(
short,
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("floating"),
conflicts_with("direction")
)]
in_place: bool,
/// Name of the new pane
#[clap(short, long, value_parser)]
name: Option<String>,
/// Close the pane immediately when its command exits
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
close_on_exit: bool,
/// Start the command suspended, only running after you first presses ENTER
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
start_suspended: bool,
/// The x coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
x: Option<String>,
/// The y coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
y: Option<String>,
/// The width if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
width: Option<String>,
/// The height if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
height: Option<String>,
/// Whether to pin a floating pane so that it is always on top
#[clap(long, requires("floating"))]
pinned: Option<bool>,
#[clap(
long,
conflicts_with("floating"),
conflicts_with("direction"),
value_parser,
default_value("false"),
takes_value(false)
)]
stacked: bool,
/// Block until the command has finished and its pane has been closed
#[clap(long, value_parser, default_value("false"), takes_value(false))]
blocking: bool,
/// Block until the command exits successfully (exit status 0) OR its pane has been closed
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("blocking"),
conflicts_with("block-until-exit-failure"),
conflicts_with("block-until-exit")
)]
block_until_exit_success: bool,
/// Block until the command exits with failure (non-zero exit status) OR its pane has been
/// closed
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("blocking"),
conflicts_with("block-until-exit-success"),
conflicts_with("block-until-exit")
)]
block_until_exit_failure: bool,
/// Block until the command exits (regardless of exit status) OR its pane has been closed
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("blocking"),
conflicts_with("block-until-exit-success"),
conflicts_with("block-until-exit-failure")
)]
block_until_exit: bool,
/// if set, will open the pane near the current one rather than following the user's focus
#[clap(long)]
near_current_pane: bool,
},
/// Load a plugin
#[clap(visible_alias = "p")]
Plugin {
/// Plugin URL, can either start with http(s), file: or zellij:
#[clap(last(true), required(true))]
url: String,
/// Plugin configuration
#[clap(short, long, value_parser)]
configuration: Option<PluginUserConfiguration>,
/// Open the new pane in floating mode
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
floating: bool,
/// Open the new pane in place of the current pane, temporarily suspending it
#[clap(
short,
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("floating")
)]
in_place: bool,
/// Skip the memory and HD cache and force recompile of the plugin (good for development)
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
skip_plugin_cache: bool,
/// The x coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
x: Option<String>,
/// The y coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
y: Option<String>,
/// The width if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
width: Option<String>,
/// The height if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
height: Option<String>,
/// Whether to pin a floating pane so that it is always on top
#[clap(long, requires("floating"))]
pinned: Option<bool>,
},
/// Edit file with default $EDITOR / $VISUAL
#[clap(visible_alias = "e")]
Edit {
file: PathBuf,
/// Open the file in the specified line number
#[clap(short, long, value_parser)]
line_number: Option<usize>,
/// Direction to open the new pane in
#[clap(short, long, value_parser, conflicts_with("floating"))]
direction: Option<Direction>,
/// Open the new pane in place of the current pane, temporarily suspending it
#[clap(
short,
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("floating"),
conflicts_with("direction")
)]
in_place: bool,
/// Open the new pane in floating mode
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
floating: bool,
/// Change the working directory of the editor
#[clap(long, value_parser)]
cwd: Option<PathBuf>,
/// The x coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
x: Option<String>,
/// The y coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
y: Option<String>,
/// The width if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
width: Option<String>,
/// The height if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
height: Option<String>,
/// Whether to pin a floating pane so that it is always on top
#[clap(long, requires("floating"))]
pinned: Option<bool>,
/// if set, will open the pane near the current one rather than following the user's focus
#[clap(long)]
near_current_pane: bool,
},
ConvertConfig {
old_config_file: PathBuf,
},
ConvertLayout {
old_layout_file: PathBuf,
},
ConvertTheme {
old_theme_file: PathBuf,
},
/// Send data to one or more plugins, launch them if they are not running.
#[clap(override_usage(
r#"
zellij pipe [OPTIONS] [--] <PAYLOAD>
* Send data to a specific plugin:
zellij pipe --plugin file:/path/to/my/plugin.wasm --name my_pipe_name -- my_arbitrary_data
* To all running plugins (that are listening):
zellij pipe --name my_pipe_name -- my_arbitrary_data
* Pipe data into this command's STDIN and get output from the plugin on this command's STDOUT
tail -f /tmp/my-live-logfile | zellij pipe --name logs --plugin https://example.com/my-plugin.wasm | wc -l
"#))]
Pipe {
/// The name of the pipe
#[clap(short, long, value_parser, display_order(1))]
name: Option<String>,
/// The data to send down this pipe (if blank, will listen to STDIN)
payload: Option<String>,
#[clap(short, long, value_parser, display_order(2))]
/// The args of the pipe
args: Option<PluginUserConfiguration>, // TODO: we might want to not re-use
// PluginUserConfiguration
/// The plugin url (eg. file:/tmp/my-plugin.wasm) to direct this pipe to, if not specified,
/// will be sent to all plugins, if specified and is not running, the plugin will be launched
#[clap(short, long, value_parser, display_order(3))]
plugin: Option<String>,
/// The plugin configuration (note: the same plugin with different configuration is
/// considered a different plugin for the purposes of determining the pipe destination)
#[clap(short('c'), long, value_parser, display_order(4))]
plugin_configuration: Option<PluginUserConfiguration>,
},
}
#[derive(Debug, Subcommand, Clone, Serialize, Deserialize)]
pub enum CliAction {
/// Write bytes to the terminal.
Write {
bytes: Vec<u8>,
},
/// Write characters to the terminal.
WriteChars {
chars: String,
},
/// [increase|decrease] the focused panes area at the [left|down|up|right] border.
Resize {
resize: Resize,
direction: Option<Direction>,
},
/// Change focus to the next pane
FocusNextPane,
/// Change focus to the previous pane
FocusPreviousPane,
/// Move the focused pane in the specified direction. [right|left|up|down]
MoveFocus {
direction: Direction,
},
/// Move focus to the pane or tab (if on screen edge) in the specified direction
/// [right|left|up|down]
MoveFocusOrTab {
direction: Direction,
},
/// Change the location of the focused pane in the specified direction or rotate forwrads
/// [right|left|up|down]
MovePane {
direction: Option<Direction>,
},
/// Rotate the location of the previous pane backwards
MovePaneBackwards,
/// Clear all buffers for a focused pane
Clear,
/// Dump the focused pane to a file
DumpScreen {
path: PathBuf,
/// Dump the pane with full scrollback
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
full: bool,
},
/// Dump current layout to stdout
DumpLayout,
/// Open the pane scrollback in your default editor
EditScrollback,
/// Scroll up in the focused pane
ScrollUp,
/// Scroll down in focus pane.
ScrollDown,
/// Scroll down to bottom in focus pane.
ScrollToBottom,
/// Scroll up to top in focus pane.
ScrollToTop,
/// Scroll up one page in focus pane.
PageScrollUp,
/// Scroll down one page in focus pane.
PageScrollDown,
/// Scroll up half page in focus pane.
HalfPageScrollUp,
/// Scroll down half page in focus pane.
HalfPageScrollDown,
/// Toggle between fullscreen focus pane and normal layout.
ToggleFullscreen,
/// Toggle frames around panes in the UI
TogglePaneFrames,
/// Toggle between sending text commands to all panes on the current tab and normal mode.
ToggleActiveSyncTab,
/// Open a new pane in the specified direction [right|down]
/// If no direction is specified, will try to use the biggest available space.
NewPane {
/// Direction to open the new pane in
#[clap(short, long, value_parser, conflicts_with("floating"))]
direction: Option<Direction>,
#[clap(last(true))]
command: Vec<String>,
#[clap(short, long, conflicts_with("command"), conflicts_with("direction"))]
plugin: Option<String>,
/// Change the working directory of the new pane
#[clap(long, value_parser)]
cwd: Option<PathBuf>,
/// Open the new pane in floating mode
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
floating: bool,
/// Open the new pane in place of the current pane, temporarily suspending it
#[clap(
short,
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("floating"),
conflicts_with("direction")
)]
in_place: bool,
/// Name of the new pane
#[clap(short, long, value_parser)]
name: Option<String>,
/// Close the pane immediately when its command exits
#[clap(
short,
long,
value_parser,
default_value("false"),
takes_value(false),
requires("command")
)]
close_on_exit: bool,
/// Start the command suspended, only running it after the you first press ENTER
#[clap(
short,
long,
value_parser,
default_value("false"),
takes_value(false),
requires("command")
)]
start_suspended: bool,
#[clap(long, value_parser)]
configuration: Option<PluginUserConfiguration>,
#[clap(long, value_parser)]
skip_plugin_cache: bool,
/// The x coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
x: Option<String>,
/// The y coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
y: Option<String>,
/// The width if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
width: Option<String>,
/// The height if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
height: Option<String>,
/// Whether to pin a floating pane so that it is always on top
#[clap(long, requires("floating"))]
pinned: Option<bool>,
#[clap(
long,
conflicts_with("floating"),
conflicts_with("direction"),
value_parser,
default_value("false"),
takes_value(false)
)]
stacked: bool,
#[clap(short, long)]
blocking: bool,
// TODO: clean this up
#[clap(skip)]
unblock_condition: Option<UnblockCondition>,
/// if set, will open the pane near the current one rather than following the user's focus
#[clap(long)]
near_current_pane: bool,
},
/// Open the specified file in a new zellij pane with your default EDITOR
Edit {
file: PathBuf,
/// Direction to open the new pane in
#[clap(short, long, value_parser, conflicts_with("floating"))]
direction: Option<Direction>,
/// Open the file in the specified line number
#[clap(short, long, value_parser)]
line_number: Option<usize>,
/// Open the new pane in floating mode
#[clap(short, long, value_parser, default_value("false"), takes_value(false))]
floating: bool,
/// Open the new pane in place of the current pane, temporarily suspending it
#[clap(
short,
long,
value_parser,
default_value("false"),
takes_value(false),
conflicts_with("floating"),
conflicts_with("direction")
)]
in_place: bool,
/// Change the working directory of the editor
#[clap(long, value_parser)]
cwd: Option<PathBuf>,
/// The x coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
x: Option<String>,
/// The y coordinates if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(short, long, requires("floating"))]
y: Option<String>,
/// The width if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
width: Option<String>,
/// The height if the pane is floating as a bare integer (eg. 1) or percent (eg. 10%)
#[clap(long, requires("floating"))]
height: Option<String>,
/// Whether to pin a floating pane so that it is always on top
#[clap(long, requires("floating"))]
pinned: Option<bool>,
/// if set, will open the pane near the current one rather than following the user's focus
#[clap(long)]
near_current_pane: bool,
},
/// Switch input mode of all connected clients [locked|pane|tab|resize|move|search|session]
SwitchMode {
input_mode: InputMode,
},
/// Embed focused pane if floating or float focused pane if embedded
TogglePaneEmbedOrFloating,
/// Toggle the visibility of all floating panes in the current Tab, open one if none exist
ToggleFloatingPanes,
/// Close the focused pane.
ClosePane,
/// Renames the focused pane
RenamePane {
name: String,
},
/// Remove a previously set pane name
UndoRenamePane,
/// Go to the next tab.
GoToNextTab,
/// Go to the previous tab.
GoToPreviousTab,
/// Close the current tab.
CloseTab,
/// Go to tab with index [index]
GoToTab {
index: u32,
},
/// Go to tab with name [name]
GoToTabName {
name: String,
/// Create a tab if one does not exist.
#[clap(short, long, value_parser)]
create: bool,
},
/// Renames the focused pane
RenameTab {
name: String,
},
/// Remove a previously set tab name
UndoRenameTab,
/// Create a new tab, optionally with a specified tab layout and name
NewTab {
/// Layout to use for the new tab
#[clap(short, long, value_parser)]
layout: Option<PathBuf>,
/// Default folder to look for layouts
#[clap(long, value_parser, requires("layout"))]
layout_dir: Option<PathBuf>,
/// Name of the new tab
#[clap(short, long, value_parser)]
name: Option<String>,
/// Change the working directory of the new tab
#[clap(short, long, value_parser)]
cwd: Option<PathBuf>,
/// Optional initial command to run in the new tab
#[clap(
value_parser,
conflicts_with("initial-plugin"),
multiple_values(true),
takes_value(true),
last(true)
)]
initial_command: Vec<String>,
/// Initial plugin to load in the new tab
#[clap(long, value_parser, conflicts_with("initial-command"))]
initial_plugin: Option<String>,
/// Close the pane immediately when its command exits
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
requires("initial-command")
)]
close_on_exit: bool,
/// Start the command suspended, only running it after you first press ENTER
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
requires("initial-command")
)]
start_suspended: bool,
/// Block until the command exits successfully (exit status 0) OR its pane has been closed
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
requires("initial-command"),
conflicts_with("block-until-exit-failure"),
conflicts_with("block-until-exit")
)]
block_until_exit_success: bool,
/// Block until the command exits with failure (non-zero exit status) OR its pane has been closed
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
requires("initial-command"),
conflicts_with("block-until-exit-success"),
conflicts_with("block-until-exit")
)]
block_until_exit_failure: bool,
/// Block until the command exits (regardless of exit status) OR its pane has been closed
#[clap(
long,
value_parser,
default_value("false"),
takes_value(false),
requires("initial-command"),
conflicts_with("block-until-exit-success"),
conflicts_with("block-until-exit-failure")
)]
block_until_exit: bool,
},
/// Move the focused tab in the specified direction. [right|left]
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/home.rs | zellij-utils/src/home.rs | //!
//! # This module contain everything you'll need to access local system paths
//! containing configuration and layouts
use crate::consts::{SYSTEM_DEFAULT_DATA_DIR_PREFIX, ZELLIJ_PROJ_DIR};
#[cfg(not(test))]
use crate::consts::SYSTEM_DEFAULT_CONFIG_DIR;
use directories::BaseDirs;
use std::{path::Path, path::PathBuf};
pub(crate) const CONFIG_LOCATION: &str = ".config/zellij";
#[cfg(not(test))]
/// Goes through a predefined list and checks for an already
/// existing config directory, returns the first match
pub fn find_default_config_dir() -> Option<PathBuf> {
default_config_dirs()
.into_iter()
.filter(|p| p.is_some())
.find(|p| p.clone().unwrap().exists())
.flatten()
}
#[cfg(test)]
pub fn find_default_config_dir() -> Option<PathBuf> {
None
}
/// Order in which config directories are checked
#[cfg(not(test))]
pub(crate) fn default_config_dirs() -> Vec<Option<PathBuf>> {
vec![
home_config_dir(),
Some(xdg_config_dir()),
Some(Path::new(SYSTEM_DEFAULT_CONFIG_DIR).to_path_buf()),
]
}
/// Looks for an existing dir, uses that, else returns a
/// dir matching the config spec.
pub fn get_default_data_dir() -> PathBuf {
[
xdg_data_dir(),
Path::new(SYSTEM_DEFAULT_DATA_DIR_PREFIX).join("share/zellij"),
]
.into_iter()
.find(|p| p.exists())
.unwrap_or_else(xdg_data_dir)
}
pub fn xdg_config_dir() -> PathBuf {
ZELLIJ_PROJ_DIR.config_dir().to_owned()
}
pub fn xdg_data_dir() -> PathBuf {
ZELLIJ_PROJ_DIR.data_dir().to_owned()
}
pub fn home_config_dir() -> Option<PathBuf> {
if let Some(user_dirs) = BaseDirs::new() {
let config_dir = user_dirs.home_dir().join(CONFIG_LOCATION);
Some(config_dir)
} else {
None
}
}
pub fn try_create_home_config_dir() {
if let Some(user_dirs) = BaseDirs::new() {
let config_dir = user_dirs.home_dir().join(CONFIG_LOCATION);
if let Err(e) = std::fs::create_dir_all(config_dir) {
log::error!("Failed to create config dir: {:?}", e);
}
}
}
pub fn get_layout_dir(config_dir: Option<PathBuf>) -> Option<PathBuf> {
config_dir.map(|dir| dir.join("layouts"))
}
pub fn default_layout_dir() -> Option<PathBuf> {
find_default_config_dir().map(|dir| dir.join("layouts"))
}
pub fn get_theme_dir(config_dir: Option<PathBuf>) -> Option<PathBuf> {
config_dir.map(|dir| dir.join("themes"))
}
pub fn default_theme_dir() -> Option<PathBuf> {
find_default_config_dir().map(|dir| dir.join("themes"))
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/downloader.rs | zellij-utils/src/downloader.rs | use async_std::sync::Mutex;
use async_std::{
fs,
io::{ReadExt, WriteExt},
stream::StreamExt,
};
use isahc::prelude::*;
use isahc::{config::RedirectPolicy, HttpClient, Request};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use thiserror::Error;
use url::Url;
#[derive(Error, Debug)]
pub enum DownloaderError {
#[error("RequestError: {0}")]
Request(#[from] isahc::Error),
#[error("HttpError: {0}")]
HttpError(#[from] isahc::http::Error),
#[error("IoError: {0}")]
Io(#[source] std::io::Error),
#[error("StdIoError: {0}")]
StdIoError(#[from] std::io::Error),
#[error("File name cannot be found in URL: {0}")]
NotFoundFileName(String),
#[error("Failed to parse URL body: {0}")]
InvalidUrlBody(String),
}
#[derive(Debug, Clone)]
pub struct Downloader {
client: Option<HttpClient>,
location: PathBuf,
// the whole thing is an Arc/Mutex so that Downloader is thread safe, and the individual values of
// the HashMap are Arc/Mutexes (Mutexi?) to represent that individual downloads should not
// happen concurrently
download_locks: Arc<Mutex<HashMap<String, Arc<Mutex<()>>>>>,
}
impl Default for Downloader {
fn default() -> Self {
Self {
client: HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()
.ok(),
location: PathBuf::from(""),
download_locks: Default::default(),
}
}
}
impl Downloader {
pub fn new(location: PathBuf) -> Self {
Self {
client: HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()
.ok(),
location,
download_locks: Default::default(),
}
}
pub async fn download(
&self,
url: &str,
file_name: Option<&str>,
) -> Result<(), DownloaderError> {
let Some(client) = &self.client else {
log::error!("No Http client found, cannot perform requests - this is likely a misconfiguration of isahc::HttpClient");
return Ok(());
};
let file_name = match file_name {
Some(name) => name.to_string(),
None => self.parse_name(url)?,
};
// we do this to make sure only one download of a specific url is happening at a time
// otherwise the downloads corrupt each other (and we waste lots of system resources)
let download_lock = self.acquire_download_lock(&file_name).await;
// it's important that _lock remains in scope, otherwise it gets dropped and the lock is
// released before the download is complete
let _lock = download_lock.lock().await;
let file_path = self.location.join(file_name.as_str());
if file_path.exists() {
log::debug!("File already exists: {:?}", file_path);
return Ok(());
}
let file_part_path = self.location.join(format!("{}.part", file_name));
let (mut target, file_part_size) = {
if file_part_path.exists() {
let file_part = fs::OpenOptions::new()
.append(true)
.write(true)
.open(&file_part_path)
.await
.map_err(|e| DownloaderError::Io(e))?;
let file_part_size = file_part
.metadata()
.await
.map_err(|e| DownloaderError::Io(e))?
.len();
log::debug!("Resuming download from {} bytes", file_part_size);
(file_part, file_part_size)
} else {
let file_part = fs::File::create(&file_part_path)
.await
.map_err(|e| DownloaderError::Io(e))?;
(file_part, 0)
}
};
let request = Request::get(url)
.header("Content-Type", "application/octet-stream")
.header("Range", format!("bytes={}-", file_part_size))
.body(())?;
let mut res = client.send_async(request).await?;
let body = res.body_mut();
let mut stream = body.bytes();
while let Some(byte) = stream.next().await {
let byte = byte.map_err(|e| DownloaderError::Io(e))?;
target
.write(&[byte])
.await
.map_err(|e| DownloaderError::Io(e))?;
}
log::debug!("Download complete: {:?}", file_part_path);
fs::rename(file_part_path, file_path)
.await
.map_err(|e| DownloaderError::Io(e))?;
Ok(())
}
pub async fn download_without_cache(url: &str) -> Result<String, DownloaderError> {
let request = Request::get(url)
.header("Content-Type", "application/octet-stream")
.body(())?;
let client = HttpClient::builder()
// TODO: timeout?
.redirect_policy(RedirectPolicy::Follow)
.build()?;
let mut res = client.send_async(request).await?;
let mut downloaded_bytes: Vec<u8> = vec![];
let body = res.body_mut();
let mut stream = body.bytes();
while let Some(byte) = stream.next().await {
let byte = byte.map_err(|e| DownloaderError::Io(e))?;
downloaded_bytes.push(byte);
}
log::debug!("Download complete");
let stringified = String::from_utf8(downloaded_bytes)
.map_err(|e| DownloaderError::InvalidUrlBody(format!("{}", e)))?;
Ok(stringified)
}
fn parse_name(&self, url: &str) -> Result<String, DownloaderError> {
Url::parse(url)
.map_err(|_| DownloaderError::NotFoundFileName(url.to_string()))?
.path_segments()
.ok_or_else(|| DownloaderError::NotFoundFileName(url.to_string()))?
.last()
.ok_or_else(|| DownloaderError::NotFoundFileName(url.to_string()))
.map(|s| s.to_string())
}
async fn acquire_download_lock(&self, file_name: &String) -> Arc<Mutex<()>> {
let mut lock_dict = self.download_locks.lock().await;
let download_lock = lock_dict
.entry(file_name.clone())
.or_insert_with(|| Default::default());
download_lock.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[ignore]
#[async_std::test]
async fn test_download_ok() {
let location = tempdir().expect("Failed to create temp directory");
let location_path = location.path();
let downloader = Downloader::new(location_path.to_path_buf());
let result = downloader
.download(
"https://github.com/imsnif/monocle/releases/download/0.39.0/monocle.wasm",
Some("monocle.wasm"),
)
.await
.is_ok();
assert!(result);
assert!(location_path.join("monocle.wasm").exists());
location.close().expect("Failed to close temp directory");
}
#[ignore]
#[async_std::test]
async fn test_download_without_file_name() {
let location = tempdir().expect("Failed to create temp directory");
let location_path = location.path();
let downloader = Downloader::new(location_path.to_path_buf());
let result = downloader
.download(
"https://github.com/imsnif/multitask/releases/download/0.38.2v2/multitask.wasm",
None,
)
.await
.is_ok();
assert!(result);
assert!(location_path.join("multitask.wasm").exists());
location.close().expect("Failed to close temp directory");
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/remote_session_tokens.rs | zellij-utils/src/remote_session_tokens.rs | use crate::consts::ZELLIJ_PROJ_DIR;
use crate::shared::set_permissions;
use rusqlite::Connection;
use std::path::PathBuf;
#[derive(Debug)]
pub enum TokenError {
Database(rusqlite::Error),
Io(std::io::Error),
InvalidPath,
}
impl std::fmt::Display for TokenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TokenError::Database(e) => write!(f, "Database error: {}", e),
TokenError::Io(e) => write!(f, "IO error: {}", e),
TokenError::InvalidPath => write!(f, "Invalid path"),
}
}
}
impl std::error::Error for TokenError {}
impl From<rusqlite::Error> for TokenError {
fn from(error: rusqlite::Error) -> Self {
TokenError::Database(error)
}
}
impl From<std::io::Error> for TokenError {
fn from(error: std::io::Error) -> Self {
TokenError::Io(error)
}
}
type Result<T> = std::result::Result<T, TokenError>;
fn get_db_path() -> Result<PathBuf> {
let data_dir = ZELLIJ_PROJ_DIR.data_dir();
std::fs::create_dir_all(data_dir)?;
let db_path = data_dir.join("remote_sessions.db");
Ok(db_path)
}
fn init_db(conn: &Connection) -> Result<()> {
conn.execute(
"CREATE TABLE IF NOT EXISTS remote_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
server_url TEXT UNIQUE NOT NULL,
session_token TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
last_used_at DATETIME DEFAULT CURRENT_TIMESTAMP
)",
[],
)?;
Ok(())
}
/// Save session token for a server (upsert)
pub fn save_session_token(server_url: &str, session_token: &str) -> Result<()> {
let db_path = get_db_path()?;
// Set file permissions to 0600 if creating new file
let is_new = !db_path.exists();
let conn = Connection::open(&db_path)?;
init_db(&conn)?;
if is_new {
set_permissions(&db_path, 0o600)?;
}
conn.execute(
"INSERT OR REPLACE INTO remote_sessions (server_url, session_token, last_used_at)
VALUES (?1, ?2, CURRENT_TIMESTAMP)",
[server_url, session_token],
)?;
Ok(())
}
/// Get session token for a server, update last_used_at
pub fn get_session_token(server_url: &str) -> Result<Option<String>> {
let db_path = get_db_path()?;
if !db_path.exists() {
return Ok(None);
}
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let token = match conn.query_row(
"SELECT session_token FROM remote_sessions WHERE server_url = ?1",
[server_url],
|row| row.get::<_, String>(0),
) {
Ok(token) => Some(token),
Err(rusqlite::Error::QueryReturnedNoRows) => None,
Err(e) => return Err(TokenError::Database(e)),
};
if token.is_some() {
// Update last_used_at
conn.execute(
"UPDATE remote_sessions SET last_used_at = CURRENT_TIMESTAMP WHERE server_url = ?1",
[server_url],
)?;
}
Ok(token)
}
/// Delete session token for a server
pub fn delete_session_token(server_url: &str) -> Result<bool> {
let db_path = get_db_path()?;
if !db_path.exists() {
return Ok(false);
}
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let rows_affected = conn.execute(
"DELETE FROM remote_sessions WHERE server_url = ?1",
[server_url],
)?;
Ok(rows_affected > 0)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/web_authentication_tokens.rs | zellij-utils/src/web_authentication_tokens.rs | // TODO: GATE THIS WHOLE FILE AND RELEVANT DEPS BEHIND web_server_capability
use crate::consts::ZELLIJ_PROJ_DIR;
use rusqlite::Connection;
use sha2::{Digest, Sha256};
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
use uuid::Uuid;
#[derive(Debug)]
pub struct TokenInfo {
pub name: String,
pub created_at: String,
pub read_only: bool,
}
#[derive(Debug)]
pub enum TokenError {
Database(rusqlite::Error),
Io(std::io::Error),
InvalidPath,
DuplicateName(String),
TokenNotFound(String),
InvalidToken,
}
impl std::fmt::Display for TokenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TokenError::Database(e) => write!(f, "Database error: {}", e),
TokenError::Io(e) => write!(f, "IO error: {}", e),
TokenError::InvalidPath => write!(f, "Invalid path"),
TokenError::DuplicateName(name) => write!(f, "Token name '{}' already exists", name),
TokenError::TokenNotFound(name) => write!(f, "Token '{}' not found", name),
TokenError::InvalidToken => write!(f, "Invalid token"),
}
}
}
impl std::error::Error for TokenError {}
impl From<rusqlite::Error> for TokenError {
fn from(error: rusqlite::Error) -> Self {
match error {
rusqlite::Error::SqliteFailure(ffi_error, _)
if ffi_error.code == rusqlite::ErrorCode::ConstraintViolation =>
{
TokenError::DuplicateName("unknown".to_string())
},
_ => TokenError::Database(error),
}
}
}
impl From<std::io::Error> for TokenError {
fn from(error: std::io::Error) -> Self {
TokenError::Io(error)
}
}
type Result<T> = std::result::Result<T, TokenError>;
fn get_db_path() -> Result<PathBuf> {
if cfg!(debug_assertions) {
// tests db
let data_dir = ZELLIJ_PROJ_DIR.data_dir();
std::fs::create_dir_all(&data_dir)?;
Ok(data_dir.join("tokens_for_dev.db"))
} else {
// prod db
let data_dir = ZELLIJ_PROJ_DIR.data_dir();
std::fs::create_dir_all(data_dir)?;
Ok(data_dir.join("tokens.db"))
}
}
fn init_db(conn: &Connection) -> Result<()> {
conn.execute(
"CREATE TABLE IF NOT EXISTS tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
token_hash TEXT UNIQUE NOT NULL,
name TEXT UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)",
[],
)?;
conn.execute(
"CREATE TABLE IF NOT EXISTS session_tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_token_hash TEXT UNIQUE NOT NULL,
auth_token_hash TEXT NOT NULL,
remember_me BOOLEAN NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
expires_at DATETIME NOT NULL,
FOREIGN KEY (auth_token_hash) REFERENCES tokens(token_hash)
)",
[],
)?;
// Migration: Add read_only column if it doesn't exist
conn.execute(
"ALTER TABLE tokens ADD COLUMN read_only BOOLEAN NOT NULL DEFAULT 0",
[],
)
.ok();
Ok(())
}
fn hash_token(token: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(token.as_bytes());
format!("{:x}", hasher.finalize())
}
pub fn create_token(name: Option<String>, read_only: bool) -> Result<(String, String)> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let token = Uuid::new_v4().to_string();
let token_hash = hash_token(&token);
let token_name = if let Some(n) = name {
n.to_string()
} else {
let count: i64 = conn.query_row("SELECT COUNT(*) FROM tokens", [], |row| row.get(0))?;
format!("token_{}", count + 1)
};
match conn.execute(
"INSERT INTO tokens (token_hash, name, read_only) VALUES (?1, ?2, ?3)",
[&token_hash, &token_name, &(read_only as i64).to_string()],
) {
Err(rusqlite::Error::SqliteFailure(ffi_error, _))
if ffi_error.code == rusqlite::ErrorCode::ConstraintViolation =>
{
Err(TokenError::DuplicateName(token_name))
},
Err(e) => Err(TokenError::Database(e)),
Ok(_) => Ok((token, token_name)),
}
}
pub fn create_session_token(auth_token: &str, remember_me: bool) -> Result<String> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
cleanup_expired_sessions()?;
let auth_token_hash = hash_token(auth_token);
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM tokens WHERE token_hash = ?1",
[&auth_token_hash],
|row| row.get(0),
)?;
if count == 0 {
return Err(TokenError::InvalidToken);
}
let session_token = Uuid::new_v4().to_string();
let session_token_hash = hash_token(&session_token);
let expires_at = if remember_me {
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let four_weeks = 4 * 7 * 24 * 60 * 60;
format!("datetime({}, 'unixepoch')", now + four_weeks)
} else {
// For session-only: very short expiration (e.g., 5 minutes)
// The browser will handle the session aspect via cookie expiration
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let short_duration = 5 * 60; // 5 minutes
format!("datetime({}, 'unixepoch')", now + short_duration)
};
conn.execute(
&format!("INSERT INTO session_tokens (session_token_hash, auth_token_hash, remember_me, expires_at) VALUES (?1, ?2, ?3, {})", expires_at),
[&session_token_hash, &auth_token_hash, &(remember_me as i64).to_string()],
)?;
Ok(session_token)
}
pub fn validate_session_token(session_token: &str) -> Result<bool> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let session_token_hash = hash_token(session_token);
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM session_tokens WHERE session_token_hash = ?1 AND expires_at > datetime('now')",
[&session_token_hash],
|row| row.get(0),
)?;
Ok(count > 0)
}
pub fn is_session_token_read_only(session_token: &str) -> Result<bool> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let session_token_hash = hash_token(session_token);
// Join session_tokens to tokens table to get read_only flag
let read_only: i64 = match conn.query_row(
"SELECT t.read_only FROM tokens t
JOIN session_tokens st ON st.auth_token_hash = t.token_hash
WHERE st.session_token_hash = ?1 AND st.expires_at > datetime('now')",
[&session_token_hash],
|row| row.get(0),
) {
Ok(val) => val,
Err(rusqlite::Error::QueryReturnedNoRows) => return Err(TokenError::InvalidToken),
Err(e) => return Err(TokenError::Database(e)),
};
Ok(read_only != 0)
}
pub fn cleanup_expired_sessions() -> Result<usize> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let rows_affected = conn.execute(
"DELETE FROM session_tokens WHERE expires_at <= datetime('now')",
[],
)?;
Ok(rows_affected)
}
pub fn revoke_session_token(session_token: &str) -> Result<bool> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let session_token_hash = hash_token(session_token);
let rows_affected = conn.execute(
"DELETE FROM session_tokens WHERE session_token_hash = ?1",
[&session_token_hash],
)?;
Ok(rows_affected > 0)
}
pub fn revoke_sessions_for_auth_token(auth_token: &str) -> Result<usize> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let auth_token_hash = hash_token(auth_token);
let rows_affected = conn.execute(
"DELETE FROM session_tokens WHERE auth_token_hash = ?1",
[&auth_token_hash],
)?;
Ok(rows_affected)
}
pub fn revoke_token(name: &str) -> Result<bool> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let token_hash = match conn.query_row(
"SELECT token_hash FROM tokens WHERE name = ?1",
[&name],
|row| row.get::<_, String>(0),
) {
Ok(hash) => Some(hash),
Err(rusqlite::Error::QueryReturnedNoRows) => None,
Err(e) => return Err(TokenError::Database(e)),
};
if let Some(token_hash) = token_hash {
conn.execute(
"DELETE FROM session_tokens WHERE auth_token_hash = ?1",
[&token_hash],
)?;
}
let rows_affected = conn.execute("DELETE FROM tokens WHERE name = ?1", [&name])?;
Ok(rows_affected > 0)
}
pub fn revoke_all_tokens() -> Result<usize> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
conn.execute("DELETE FROM session_tokens", [])?;
let rows_affected = conn.execute("DELETE FROM tokens", [])?;
Ok(rows_affected)
}
pub fn rename_token(old_name: &str, new_name: &str) -> Result<()> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM tokens WHERE name = ?1",
[&old_name],
|row| row.get(0),
)?;
if count == 0 {
return Err(TokenError::TokenNotFound(old_name.to_string()));
}
match conn.execute(
"UPDATE tokens SET name = ?1 WHERE name = ?2",
[&new_name, &old_name],
) {
Err(rusqlite::Error::SqliteFailure(ffi_error, _))
if ffi_error.code == rusqlite::ErrorCode::ConstraintViolation =>
{
Err(TokenError::DuplicateName(new_name.to_string()))
},
Err(e) => Err(TokenError::Database(e)),
Ok(_) => Ok(()),
}
}
pub fn list_tokens() -> Result<Vec<TokenInfo>> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let mut stmt =
conn.prepare("SELECT name, created_at, read_only FROM tokens ORDER BY created_at")?;
let rows = stmt.query_map([], |row| {
Ok(TokenInfo {
name: row.get::<_, String>(0)?,
created_at: row.get::<_, String>(1)?,
read_only: row.get::<_, i64>(2)? != 0,
})
})?;
let mut tokens = Vec::new();
for token in rows {
tokens.push(token?);
}
Ok(tokens)
}
pub fn delete_db() -> Result<()> {
let db_path = get_db_path()?;
if db_path.exists() {
std::fs::remove_file(db_path)?;
}
Ok(())
}
pub fn validate_token(token: &str) -> Result<bool> {
let db_path = get_db_path()?;
let conn = Connection::open(db_path)?;
init_db(&conn)?;
let token_hash = hash_token(token);
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM tokens WHERE token_hash = ?1",
[&token_hash],
|row| row.get(0),
)?;
Ok(count > 0)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/sessions.rs | zellij-utils/src/sessions.rs | use crate::{
consts::{
session_info_folder_for_session, session_layout_cache_file_name,
ZELLIJ_SESSION_INFO_CACHE_DIR, ZELLIJ_SOCK_DIR,
},
envs,
input::layout::Layout,
ipc::{ClientToServerMsg, IpcReceiverWithContext, IpcSenderWithContext, ServerToClientMsg},
};
use anyhow;
use humantime::format_duration;
use interprocess::local_socket::LocalSocketStream;
use std::collections::HashMap;
use std::os::unix::fs::FileTypeExt;
use std::time::{Duration, SystemTime};
use std::{fs, io, process};
use suggest::Suggest;
pub fn get_sessions() -> Result<Vec<(String, Duration)>, io::ErrorKind> {
match fs::read_dir(&*ZELLIJ_SOCK_DIR) {
Ok(files) => {
let mut sessions = Vec::new();
files.for_each(|file| {
if let Ok(file) = file {
let file_name = file.file_name().into_string().unwrap();
let ctime = std::fs::metadata(&file.path())
.ok()
.and_then(|f| f.created().ok())
.and_then(|d| d.elapsed().ok())
.unwrap_or_default();
let duration = Duration::from_secs(ctime.as_secs());
if file.file_type().unwrap().is_socket() && assert_socket(&file_name) {
sessions.push((file_name, duration));
}
}
});
Ok(sessions)
},
Err(err) if io::ErrorKind::NotFound != err.kind() => Err(err.kind()),
Err(_) => Ok(Vec::with_capacity(0)),
}
}
pub fn get_resurrectable_sessions() -> Vec<(String, Duration)> {
match fs::read_dir(&*ZELLIJ_SESSION_INFO_CACHE_DIR) {
Ok(files_in_session_info_folder) => {
let files_that_are_folders = files_in_session_info_folder
.filter_map(|f| f.ok().map(|f| f.path()))
.filter(|f| f.is_dir());
files_that_are_folders
.filter_map(|folder_name| {
let layout_file_name =
session_layout_cache_file_name(&folder_name.display().to_string());
let ctime = match std::fs::metadata(&layout_file_name)
.and_then(|metadata| metadata.created())
{
Ok(created) => Some(created),
Err(_e) => None,
};
let elapsed_duration = ctime
.map(|ctime| {
Duration::from_secs(ctime.elapsed().ok().unwrap_or_default().as_secs())
})
.unwrap_or_default();
let session_name = folder_name
.file_name()
.map(|f| std::path::PathBuf::from(f).display().to_string())?;
if std::path::Path::new(&layout_file_name).exists() {
Some((session_name, elapsed_duration))
} else {
None
}
})
.collect()
},
Err(e) => {
log::error!(
"Failed to read session_info cache folder: \"{:?}\": {:?}",
&*ZELLIJ_SESSION_INFO_CACHE_DIR,
e
);
vec![]
},
}
}
pub fn get_resurrectable_session_names() -> Vec<String> {
match fs::read_dir(&*ZELLIJ_SESSION_INFO_CACHE_DIR) {
Ok(files_in_session_info_folder) => {
let files_that_are_folders = files_in_session_info_folder
.filter_map(|f| f.ok().map(|f| f.path()))
.filter(|f| f.is_dir());
files_that_are_folders
.filter_map(|folder_name| {
let folder = folder_name.display().to_string();
let resurrection_layout_file = session_layout_cache_file_name(&folder);
if std::path::Path::new(&resurrection_layout_file).exists() {
folder_name
.file_name()
.map(|f| format!("{}", f.to_string_lossy()))
} else {
None
}
})
.collect()
},
Err(e) => {
log::error!(
"Failed to read session_info cache folder: \"{:?}\": {:?}",
&*ZELLIJ_SESSION_INFO_CACHE_DIR,
e
);
vec![]
},
}
}
pub fn get_sessions_sorted_by_mtime() -> anyhow::Result<Vec<String>> {
match fs::read_dir(&*ZELLIJ_SOCK_DIR) {
Ok(files) => {
let mut sessions_with_mtime: Vec<(String, SystemTime)> = Vec::new();
for file in files {
let file = file?;
let file_name = file.file_name().into_string().unwrap();
let file_modified_at = file.metadata()?.modified()?;
if file.file_type()?.is_socket() && assert_socket(&file_name) {
sessions_with_mtime.push((file_name, file_modified_at));
}
}
sessions_with_mtime.sort_by_key(|x| x.1); // the oldest one will be the first
let sessions = sessions_with_mtime.iter().map(|x| x.0.clone()).collect();
Ok(sessions)
},
Err(err) if io::ErrorKind::NotFound != err.kind() => Err(err.into()),
Err(_) => Ok(Vec::with_capacity(0)),
}
}
fn assert_socket(name: &str) -> bool {
let path = &*ZELLIJ_SOCK_DIR.join(name);
match LocalSocketStream::connect(path) {
Ok(stream) => {
let mut sender: IpcSenderWithContext<ClientToServerMsg> =
IpcSenderWithContext::new(stream);
let _ = sender.send_client_msg(ClientToServerMsg::ConnStatus);
let mut receiver: IpcReceiverWithContext<ServerToClientMsg> = sender.get_receiver();
match receiver.recv_server_msg() {
Some((ServerToClientMsg::Connected, _)) => true,
None | Some((_, _)) => false,
}
},
Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => {
drop(fs::remove_file(path));
false
},
Err(_) => false,
}
}
pub fn print_sessions(
mut sessions: Vec<(String, Duration, bool)>,
no_formatting: bool,
short: bool,
reverse: bool,
) {
// (session_name, timestamp, is_dead)
let curr_session = envs::get_session_name().unwrap_or_else(|_| "".into());
sessions.sort_by(|a, b| {
if reverse {
// sort by `Duration` ascending (newest would be first)
a.1.cmp(&b.1)
} else {
b.1.cmp(&a.1)
}
});
sessions
.iter()
.for_each(|(session_name, timestamp, is_dead)| {
if short {
println!("{}", session_name);
return;
}
if no_formatting {
let suffix = if curr_session == *session_name {
format!("(current)")
} else if *is_dead {
format!("(EXITED - attach to resurrect)")
} else {
String::new()
};
let timestamp = format!("[Created {} ago]", format_duration(*timestamp));
println!("{} {} {}", session_name, timestamp, suffix);
} else {
let formatted_session_name = format!("\u{1b}[32;1m{}\u{1b}[m", session_name);
let suffix = if curr_session == *session_name {
format!("(current)")
} else if *is_dead {
format!("(\u{1b}[31;1mEXITED\u{1b}[m - attach to resurrect)")
} else {
String::new()
};
let timestamp = format!(
"[Created \u{1b}[35;1m{}\u{1b}[m ago]",
format_duration(*timestamp)
);
println!("{} {} {}", formatted_session_name, timestamp, suffix);
}
})
}
pub fn print_sessions_with_index(sessions: Vec<String>) {
let curr_session = envs::get_session_name().unwrap_or_else(|_| "".into());
for (i, session) in sessions.iter().enumerate() {
let suffix = if curr_session == *session {
" (current)"
} else {
""
};
println!("{}: {}{}", i, session, suffix);
}
}
pub enum ActiveSession {
None,
One(String),
Many,
}
pub fn get_active_session() -> ActiveSession {
match get_sessions() {
Ok(sessions) if sessions.is_empty() => ActiveSession::None,
Ok(mut sessions) if sessions.len() == 1 => ActiveSession::One(sessions.pop().unwrap().0),
Ok(_) => ActiveSession::Many,
Err(e) => {
eprintln!("Error occurred: {:?}", e);
process::exit(1);
},
}
}
pub fn kill_session(name: &str) {
let path = &*ZELLIJ_SOCK_DIR.join(name);
match LocalSocketStream::connect(path) {
Ok(stream) => {
let _ = IpcSenderWithContext::<ClientToServerMsg>::new(stream)
.send_client_msg(ClientToServerMsg::KillSession);
},
Err(e) => {
eprintln!("Error occurred: {:?}", e);
process::exit(1);
},
};
}
pub fn delete_session(name: &str, force: bool) {
if force {
let path = &*ZELLIJ_SOCK_DIR.join(name);
let _ = LocalSocketStream::connect(path).map(|stream| {
IpcSenderWithContext::<ClientToServerMsg>::new(stream)
.send_client_msg(ClientToServerMsg::KillSession)
.ok();
});
}
if let Err(e) = std::fs::remove_dir_all(session_info_folder_for_session(name)) {
if e.kind() == std::io::ErrorKind::NotFound {
eprintln!("Session: {:?} not found.", name);
process::exit(2);
} else {
log::error!("Failed to remove session {:?}: {:?}", name, e);
}
} else {
println!("Session: {:?} successfully deleted.", name);
}
}
pub fn list_sessions(no_formatting: bool, short: bool, reverse: bool) {
let exit_code = match get_sessions() {
Ok(running_sessions) => {
let resurrectable_sessions = get_resurrectable_sessions();
let mut all_sessions: HashMap<String, (Duration, bool)> = resurrectable_sessions
.iter()
.map(|(name, timestamp)| (name.clone(), (timestamp.clone(), true)))
.collect();
for (session_name, duration) in running_sessions {
all_sessions.insert(session_name.clone(), (duration, false));
}
if all_sessions.is_empty() {
eprintln!("No active zellij sessions found.");
1
} else {
print_sessions(
all_sessions
.iter()
.map(|(name, (timestamp, is_dead))| {
(name.clone(), timestamp.clone(), *is_dead)
})
.collect(),
no_formatting,
short,
reverse,
);
0
}
},
Err(e) => {
eprintln!("Error occurred: {:?}", e);
1
},
};
process::exit(exit_code);
}
#[derive(Debug, Clone)]
pub enum SessionNameMatch {
AmbiguousPrefix(Vec<String>),
UniquePrefix(String),
Exact(String),
None,
}
pub fn match_session_name(prefix: &str) -> Result<SessionNameMatch, io::ErrorKind> {
let sessions = get_sessions()?;
let filtered_sessions: Vec<_> = sessions
.iter()
.filter(|s| s.0.starts_with(prefix))
.collect();
if filtered_sessions.iter().any(|s| s.0 == prefix) {
return Ok(SessionNameMatch::Exact(prefix.to_string()));
}
Ok({
match &filtered_sessions[..] {
[] => SessionNameMatch::None,
[s] => SessionNameMatch::UniquePrefix(s.0.to_string()),
_ => SessionNameMatch::AmbiguousPrefix(
filtered_sessions.into_iter().map(|s| s.0.clone()).collect(),
),
}
})
}
pub fn session_exists(name: &str) -> Result<bool, io::ErrorKind> {
match match_session_name(name) {
Ok(SessionNameMatch::Exact(_)) => Ok(true),
Ok(_) => Ok(false),
Err(e) => Err(e),
}
}
// if the session is resurrecable, the returned layout is the one to be used to resurrect it
pub fn resurrection_layout(session_name_to_resurrect: &str) -> Result<Option<Layout>, String> {
let layout_file_name = session_layout_cache_file_name(&session_name_to_resurrect);
let raw_layout = match std::fs::read_to_string(&layout_file_name) {
Ok(raw_layout) => raw_layout,
Err(_e) => {
return Ok(None);
},
};
match Layout::from_kdl(
&raw_layout,
Some(layout_file_name.display().to_string()),
None,
None,
) {
Ok(layout) => Ok(Some(layout)),
Err(e) => {
log::error!(
"Failed to parse resurrection layout file {}: {}",
layout_file_name.display(),
e
);
return Err(format!(
"Failed to parse resurrection layout file {}: {}.",
layout_file_name.display(),
e
));
},
}
}
pub fn assert_session(name: &str) {
match session_exists(name) {
Ok(result) => {
if result {
return;
} else {
println!("No session named {:?} found.", name);
if let Some(sugg) = get_sessions()
.unwrap()
.iter()
.map(|s| s.0.clone())
.collect::<Vec<_>>()
.suggest(name)
{
println!(" help: Did you mean `{}`?", sugg);
}
}
},
Err(e) => {
eprintln!("Error occurred: {:?}", e);
},
};
process::exit(1);
}
pub fn assert_dead_session(name: &str, force: bool) {
match session_exists(name) {
Ok(exists) => {
if exists && !force {
println!(
"A session by the name {:?} exists and is active, use --force to delete it.",
name
)
} else if exists && force {
println!("A session by the name {:?} exists and is active, but will be force killed and deleted.", name);
return;
} else {
return;
}
},
Err(e) => {
eprintln!("Error occurred: {:?}", e);
},
};
process::exit(1);
}
pub fn assert_session_ne(name: &str) {
if name.trim().is_empty() {
eprintln!("Session name cannot be empty. Please provide a specific session name.");
process::exit(1);
}
if name == "." || name == ".." {
eprintln!("Invalid session name: \"{}\".", name);
process::exit(1);
}
if name.contains('/') {
eprintln!("Session name cannot contain '/'.");
process::exit(1);
}
match session_exists(name) {
Ok(result) if !result => {
let resurrectable_sessions = get_resurrectable_session_names();
if resurrectable_sessions.iter().find(|s| s == &name).is_some() {
println!("Session with name {:?} already exists, but is dead. Use the attach command to resurrect it or, the delete-session command to kill it or specify a different name.", name);
} else {
return
}
}
Ok(_) => println!("Session with name {:?} already exists. Use attach command to connect to it or specify a different name.", name),
Err(e) => eprintln!("Error occurred: {:?}", e),
};
process::exit(1);
}
pub fn generate_unique_session_name() -> Option<String> {
let sessions = get_sessions().map(|sessions| {
sessions
.iter()
.map(|s| s.0.clone())
.collect::<Vec<String>>()
});
let dead_sessions = get_resurrectable_session_names();
let Ok(sessions) = sessions else {
eprintln!("Failed to list existing sessions: {:?}", sessions);
return None;
};
let name = get_name_generator()
.take(1000)
.find(|name| !sessions.contains(name) && !dead_sessions.contains(name));
if let Some(name) = name {
return Some(name);
} else {
return None;
}
}
/// Create a new random name generator
///
/// Used to provide a memorable handle for a session when users don't specify a session name when the session is
/// created.
///
/// Uses the list of adjectives and nouns defined below, with the intention of avoiding unfortunate
/// and offensive combinations. Care should be taken when adding or removing to either list due to the birthday paradox/
/// hash collisions, e.g. with 4096 unique names, the likelihood of a collision in 10 session names is 1%.
pub fn get_name_generator() -> impl Iterator<Item = String> {
names::Generator::new(&ADJECTIVES, &NOUNS, names::Name::Plain)
}
const ADJECTIVES: &[&'static str] = &[
"adamant",
"adept",
"adventurous",
"arcadian",
"auspicious",
"awesome",
"blossoming",
"brave",
"charming",
"chatty",
"circular",
"considerate",
"cubic",
"curious",
"delighted",
"didactic",
"diligent",
"effulgent",
"erudite",
"excellent",
"exquisite",
"fabulous",
"fascinating",
"friendly",
"glowing",
"gracious",
"gregarious",
"hopeful",
"implacable",
"inventive",
"joyous",
"judicious",
"jumping",
"kind",
"likable",
"loyal",
"lucky",
"marvellous",
"mellifluous",
"nautical",
"oblong",
"outstanding",
"polished",
"polite",
"profound",
"quadratic",
"quiet",
"rectangular",
"remarkable",
"rusty",
"sensible",
"sincere",
"sparkling",
"splendid",
"stellar",
"tenacious",
"tremendous",
"triangular",
"undulating",
"unflappable",
"unique",
"verdant",
"vitreous",
"wise",
"zippy",
];
const NOUNS: &[&'static str] = &[
"aardvark",
"accordion",
"apple",
"apricot",
"bee",
"brachiosaur",
"cactus",
"capsicum",
"clarinet",
"cowbell",
"crab",
"cuckoo",
"cymbal",
"diplodocus",
"donkey",
"drum",
"duck",
"echidna",
"elephant",
"foxglove",
"galaxy",
"glockenspiel",
"goose",
"hill",
"horse",
"iguanadon",
"jellyfish",
"kangaroo",
"lake",
"lemon",
"lemur",
"magpie",
"megalodon",
"mountain",
"mouse",
"muskrat",
"newt",
"oboe",
"ocelot",
"orange",
"panda",
"peach",
"pepper",
"petunia",
"pheasant",
"piano",
"pigeon",
"platypus",
"quasar",
"rhinoceros",
"river",
"rustacean",
"salamander",
"sitar",
"stegosaurus",
"tambourine",
"tiger",
"tomato",
"triceratops",
"ukulele",
"viola",
"weasel",
"xylophone",
"yak",
"zebra",
];
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/logging.rs | zellij-utils/src/logging.rs | //! Zellij logging utility functions.
use std::{
fs,
io::{self, prelude::*},
os::unix::io::RawFd,
path::{Path, PathBuf},
};
use log::LevelFilter;
use log4rs::append::rolling_file::{
policy::compound::{
roll::fixed_window::FixedWindowRoller, trigger::size::SizeTrigger, CompoundPolicy,
},
RollingFileAppender,
};
use log4rs::config::{Appender, Config, Logger, Root};
use log4rs::encode::pattern::PatternEncoder;
use crate::consts::{ZELLIJ_TMP_DIR, ZELLIJ_TMP_LOG_DIR, ZELLIJ_TMP_LOG_FILE};
use crate::shared::set_permissions;
const LOG_MAX_BYTES: u64 = 1024 * 1024 * 16; // 16 MiB per log
pub fn configure_logger() {
atomic_create_dir(&*ZELLIJ_TMP_DIR).unwrap();
atomic_create_dir(&*ZELLIJ_TMP_LOG_DIR).unwrap();
atomic_create_file(&*ZELLIJ_TMP_LOG_FILE).unwrap();
let trigger = SizeTrigger::new(LOG_MAX_BYTES);
let roller = FixedWindowRoller::builder()
.build(
ZELLIJ_TMP_LOG_DIR
.join("zellij.log.old.{}")
.to_str()
.unwrap(),
1,
)
.unwrap();
// {n} means platform dependent newline
// module is padded to exactly 25 bytes and thread is padded to be between 10 and 15 bytes.
let file_pattern = "{highlight({level:<6})} |{module:<25.25}| {date(%Y-%m-%d %H:%M:%S.%3f)} [{thread:<10.15}] [{file}:{line}]: {message} {n}";
// default zellij appender, should be used across most of the codebase.
let log_file = RollingFileAppender::builder()
.encoder(Box::new(PatternEncoder::new(file_pattern)))
.build(
&*ZELLIJ_TMP_LOG_FILE,
Box::new(CompoundPolicy::new(
Box::new(trigger),
Box::new(roller.clone()),
)),
)
.unwrap();
// plugin appender. To be used in logging_pipe to forward stderr output from plugins. We do some formatting
// in logging_pipe to print plugin name as 'module' and plugin_id instead of thread.
let log_plugin = RollingFileAppender::builder()
.encoder(Box::new(PatternEncoder::new(
"{highlight({level:<6})} {message} {n}",
)))
.build(
&*ZELLIJ_TMP_LOG_FILE,
Box::new(CompoundPolicy::new(Box::new(trigger), Box::new(roller))),
)
.unwrap();
// Set the default logging level to "info" and log it to zellij.log file
// Decrease verbosity for `wasmtime_wasi` module because it has a lot of useless info logs
// For `zellij_server::logging_pipe`, we use custom format as we use logging macros to forward stderr output from plugins
let config = Config::builder()
.appender(Appender::builder().build("logFile", Box::new(log_file)))
.appender(Appender::builder().build("logPlugin", Box::new(log_plugin)))
// reduce the verbosity of isahc, otherwise it logs on every failed web request
.logger(
Logger::builder()
.appender("logFile")
.build("isahc", LevelFilter::Error),
)
.logger(
Logger::builder()
.appender("logPlugin")
.build("wasmtime_wasi", LevelFilter::Warn),
)
.logger(
Logger::builder()
.appender("logPlugin")
.additive(false)
.build("zellij_server::logging_pipe", LevelFilter::Trace),
)
.build(Root::builder().appender("logFile").build(LevelFilter::Info))
.unwrap();
let _ = log4rs::init_config(config).unwrap();
}
pub fn atomic_create_file(file_name: &Path) -> io::Result<()> {
let _ = fs::OpenOptions::new()
.append(true)
.create(true)
.open(file_name)?;
set_permissions(file_name, 0o600)
}
pub fn atomic_create_dir(dir_name: &Path) -> io::Result<()> {
let result = if let Err(e) = fs::create_dir(dir_name) {
if e.kind() == std::io::ErrorKind::AlreadyExists {
Ok(())
} else {
Err(e)
}
} else {
Ok(())
};
if result.is_ok() {
set_permissions(dir_name, 0o700)?;
}
result
}
pub fn debug_to_file(message: &[u8], pid: RawFd) -> io::Result<()> {
let mut path = PathBuf::new();
path.push(&*ZELLIJ_TMP_LOG_DIR);
path.push(format!("zellij-{}.log", pid));
let mut file = fs::OpenOptions::new()
.append(true)
.create(true)
.open(&path)?;
set_permissions(&path, 0o600)?;
file.write_all(message)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/shared.rs | zellij-utils/src/shared.rs | //! Some general utility functions.
use std::net::{IpAddr, Ipv4Addr};
use std::{iter, str::from_utf8};
use crate::data::{Palette, PaletteColor, PaletteSource, ThemeHue};
use crate::envs::get_session_name;
use crate::input::options::Options;
use colorsys::{Ansi256, Rgb};
use strip_ansi_escapes::strip;
use unicode_width::UnicodeWidthStr;
#[cfg(unix)]
pub use unix_only::*;
#[cfg(unix)]
mod unix_only {
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::{fs, io};
pub fn set_permissions(path: &Path, mode: u32) -> io::Result<()> {
let mut permissions = fs::metadata(path)?.permissions();
permissions.set_mode(mode);
fs::set_permissions(path, permissions)
}
}
#[cfg(not(unix))]
pub fn set_permissions(_path: &std::path::Path, _mode: u32) -> std::io::Result<()> {
Ok(())
}
pub fn ansi_len(s: &str) -> usize {
from_utf8(&strip(s).unwrap()).unwrap().width()
}
pub fn clean_string_from_control_and_linebreak(input: &str) -> String {
input
.chars()
.filter(|c| {
!c.is_control() &&
*c != '\n' && // line feed
*c != '\r' && // carriage return
*c != '\u{2028}' && // line separator
*c != '\u{2029}' // paragraph separator
})
.collect()
}
pub fn adjust_to_size(s: &str, rows: usize, columns: usize) -> String {
s.lines()
.map(|l| {
let actual_len = ansi_len(l);
if actual_len > columns {
let mut line = String::from(l);
line.truncate(columns);
line
} else {
[l, &str::repeat(" ", columns - ansi_len(l))].concat()
}
})
.chain(iter::repeat(str::repeat(" ", columns)))
.take(rows)
.collect::<Vec<_>>()
.join("\n\r")
}
pub fn make_terminal_title(pane_title: &str) -> String {
format!(
"\u{1b}]0;{}{}\u{07}",
get_session_name()
.map(|n| if pane_title.is_empty() {
format!("{}", n)
} else {
format!("{} | ", n)
})
.unwrap_or_default(),
pane_title
)
}
// Colors
pub mod colors {
pub const WHITE: u8 = 255;
pub const GREEN: u8 = 154;
pub const GRAY: u8 = 238;
pub const BRIGHT_GRAY: u8 = 245;
pub const RED: u8 = 124;
pub const ORANGE: u8 = 166;
pub const BLACK: u8 = 16;
pub const MAGENTA: u8 = 201;
pub const CYAN: u8 = 51;
pub const YELLOW: u8 = 226;
pub const BLUE: u8 = 45;
pub const PURPLE: u8 = 99;
pub const GOLD: u8 = 136;
pub const SILVER: u8 = 245;
pub const PINK: u8 = 207;
pub const BROWN: u8 = 215;
}
pub fn _hex_to_rgb(hex: &str) -> (u8, u8, u8) {
Rgb::from_hex_str(hex)
.expect("The passed argument must be a valid hex color")
.into()
}
pub fn eightbit_to_rgb(c: u8) -> (u8, u8, u8) {
Ansi256::new(c).as_rgb().into()
}
pub fn default_palette() -> Palette {
Palette {
source: PaletteSource::Default,
theme_hue: ThemeHue::Dark,
fg: PaletteColor::EightBit(colors::BRIGHT_GRAY),
bg: PaletteColor::EightBit(colors::GRAY),
black: PaletteColor::EightBit(colors::BLACK),
red: PaletteColor::EightBit(colors::RED),
green: PaletteColor::EightBit(colors::GREEN),
yellow: PaletteColor::EightBit(colors::YELLOW),
blue: PaletteColor::EightBit(colors::BLUE),
magenta: PaletteColor::EightBit(colors::MAGENTA),
cyan: PaletteColor::EightBit(colors::CYAN),
white: PaletteColor::EightBit(colors::WHITE),
orange: PaletteColor::EightBit(colors::ORANGE),
gray: PaletteColor::EightBit(colors::GRAY),
purple: PaletteColor::EightBit(colors::PURPLE),
gold: PaletteColor::EightBit(colors::GOLD),
silver: PaletteColor::EightBit(colors::SILVER),
pink: PaletteColor::EightBit(colors::PINK),
brown: PaletteColor::EightBit(colors::BROWN),
}
}
// Dark magic
pub fn detect_theme_hue(bg: PaletteColor) -> ThemeHue {
match bg {
PaletteColor::Rgb((r, g, b)) => {
// HSP, P stands for perceived brightness
let hsp: f64 = (0.299 * (r as f64 * r as f64)
+ 0.587 * (g as f64 * g as f64)
+ 0.114 * (b as f64 * b as f64))
.sqrt();
match hsp > 127.5 {
true => ThemeHue::Light,
false => ThemeHue::Dark,
}
},
_ => ThemeHue::Dark,
}
}
// (this was shamelessly copied from alacritty)
//
// This returns the current terminal version as a unique number based on the
// semver version. The different versions are padded to ensure that a higher semver version will
// always report a higher version number.
pub fn version_number(mut version: &str) -> usize {
if let Some(separator) = version.rfind('-') {
version = &version[..separator];
}
let mut version_number = 0;
let semver_versions = version.split('.');
for (i, semver_version) in semver_versions.rev().enumerate() {
let semver_number = semver_version.parse::<usize>().unwrap_or(0);
version_number += usize::pow(100, i as u32) * semver_number;
}
version_number
}
pub fn web_server_base_url(
web_server_ip: IpAddr,
web_server_port: u16,
has_certificate: bool,
enforce_https_for_localhost: bool,
) -> String {
let is_loopback = match web_server_ip {
IpAddr::V4(ipv4) => ipv4.is_loopback(),
IpAddr::V6(ipv6) => ipv6.is_loopback(),
};
let url_prefix = if is_loopback && !enforce_https_for_localhost && !has_certificate {
"http"
} else {
"https"
};
format!("{}://{}:{}", url_prefix, web_server_ip, web_server_port)
}
pub fn web_server_base_url_from_config(config_options: Options) -> String {
let web_server_ip = config_options
.web_server_ip
.unwrap_or_else(|| IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)));
let web_server_port = config_options.web_server_port.unwrap_or_else(|| 8082);
let has_certificate =
config_options.web_server_cert.is_some() && config_options.web_server_key.is_some();
let enforce_https_for_localhost = config_options.enforce_https_for_localhost.unwrap_or(false);
web_server_base_url(
web_server_ip,
web_server_port,
has_certificate,
enforce_https_for_localhost,
)
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/position.rs | zellij-utils/src/position.rs | use serde::{Deserialize, Serialize};
#[derive(Debug, Hash, Copy, Clone, PartialEq, Eq, PartialOrd, Deserialize, Serialize)]
pub struct Position {
pub line: Line,
pub column: Column,
}
impl Position {
pub fn new(line: i32, column: u16) -> Self {
Self {
line: Line(line as isize),
column: Column(column as usize),
}
}
pub fn change_line(&mut self, line: isize) {
self.line = Line(line);
}
pub fn change_column(&mut self, column: usize) {
self.column = Column(column);
}
pub fn relative_to(&self, line: usize, column: usize) -> Self {
Self {
line: Line(self.line.0 - line as isize),
column: Column(self.column.0.saturating_sub(column)),
}
}
pub fn line(&self) -> isize {
self.line.0
}
pub fn column(&self) -> usize {
self.column.0
}
}
impl Default for Position {
fn default() -> Self {
Position::new(0, 0)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, PartialOrd)]
pub struct Line(pub isize);
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, PartialOrd)]
pub struct Column(pub usize);
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/data.rs | zellij-utils/src/data.rs | use crate::home::default_layout_dir;
use crate::input::actions::{Action, RunCommandAction};
use crate::input::config::ConversionError;
use crate::input::keybinds::Keybinds;
use crate::input::layout::{RunPlugin, RunPluginOrAlias, SplitSize};
use crate::pane_size::PaneGeom;
use crate::position::Position;
use crate::shared::{colors as default_colors, eightbit_to_rgb};
use clap::ArgEnum;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fmt;
use std::fs::Metadata;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::str::{self, FromStr};
use std::time::Duration;
use strum_macros::{Display, EnumDiscriminants, EnumIter, EnumString};
use unicode_width::UnicodeWidthChar;
#[cfg(not(target_family = "wasm"))]
use termwiz::{
escape::csi::KittyKeyboardFlags,
input::{KeyCode, KeyCodeEncodeModes, KeyboardEncoding, Modifiers},
};
pub type ClientId = u16; // TODO: merge with crate type?
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum UnblockCondition {
/// Unblock only when exit status is 0 (success)
OnExitSuccess,
/// Unblock only when exit status is non-zero (failure)
OnExitFailure,
/// Unblock on any exit (success or failure)
OnAnyExit,
}
impl UnblockCondition {
/// Check if the condition is met for the given exit status
pub fn is_met(&self, exit_status: i32) -> bool {
match self {
UnblockCondition::OnExitSuccess => exit_status == 0,
UnblockCondition::OnExitFailure => exit_status != 0,
UnblockCondition::OnAnyExit => true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CommandOrPlugin {
Command(RunCommandAction),
Plugin(RunPluginOrAlias),
}
impl CommandOrPlugin {
pub fn new_command(command: Vec<String>) -> Self {
CommandOrPlugin::Command(RunCommandAction::new(command))
}
}
pub fn client_id_to_colors(
client_id: ClientId,
colors: MultiplayerColors,
) -> Option<(PaletteColor, PaletteColor)> {
// (primary color, secondary color)
let black = PaletteColor::EightBit(default_colors::BLACK);
match client_id {
1 => Some((colors.player_1, black)),
2 => Some((colors.player_2, black)),
3 => Some((colors.player_3, black)),
4 => Some((colors.player_4, black)),
5 => Some((colors.player_5, black)),
6 => Some((colors.player_6, black)),
7 => Some((colors.player_7, black)),
8 => Some((colors.player_8, black)),
9 => Some((colors.player_9, black)),
10 => Some((colors.player_10, black)),
_ => None,
}
}
pub fn single_client_color(colors: Palette) -> (PaletteColor, PaletteColor) {
(colors.green, colors.black)
}
impl FromStr for KeyWithModifier {
type Err = Box<dyn std::error::Error>;
fn from_str(key_str: &str) -> Result<Self, Self::Err> {
let mut key_string_parts: Vec<&str> = key_str.split_ascii_whitespace().collect();
let bare_key: BareKey = BareKey::from_str(key_string_parts.pop().ok_or("empty key")?)?;
let mut key_modifiers: BTreeSet<KeyModifier> = BTreeSet::new();
for stringified_modifier in key_string_parts {
key_modifiers.insert(KeyModifier::from_str(stringified_modifier)?);
}
Ok(KeyWithModifier {
bare_key,
key_modifiers,
})
}
}
#[derive(Debug, Clone, Eq, Serialize, Deserialize, PartialOrd, Ord)]
pub struct KeyWithModifier {
pub bare_key: BareKey,
pub key_modifiers: BTreeSet<KeyModifier>,
}
impl PartialEq for KeyWithModifier {
fn eq(&self, other: &Self) -> bool {
match (self.bare_key, other.bare_key) {
(BareKey::Char(self_char), BareKey::Char(other_char))
if self_char.to_ascii_lowercase() == other_char.to_ascii_lowercase() =>
{
let mut self_cloned = self.clone();
let mut other_cloned = other.clone();
if self_char.is_ascii_uppercase() {
self_cloned.bare_key = BareKey::Char(self_char.to_ascii_lowercase());
self_cloned.key_modifiers.insert(KeyModifier::Shift);
}
if other_char.is_ascii_uppercase() {
other_cloned.bare_key = BareKey::Char(self_char.to_ascii_lowercase());
other_cloned.key_modifiers.insert(KeyModifier::Shift);
}
self_cloned.bare_key == other_cloned.bare_key
&& self_cloned.key_modifiers == other_cloned.key_modifiers
},
_ => self.bare_key == other.bare_key && self.key_modifiers == other.key_modifiers,
}
}
}
impl Hash for KeyWithModifier {
fn hash<H: Hasher>(&self, state: &mut H) {
match self.bare_key {
BareKey::Char(character) if character.is_ascii_uppercase() => {
let mut to_hash = self.clone();
to_hash.bare_key = BareKey::Char(character.to_ascii_lowercase());
to_hash.key_modifiers.insert(KeyModifier::Shift);
to_hash.bare_key.hash(state);
to_hash.key_modifiers.hash(state);
},
_ => {
self.bare_key.hash(state);
self.key_modifiers.hash(state);
},
}
}
}
impl fmt::Display for KeyWithModifier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.key_modifiers.is_empty() {
write!(f, "{}", self.bare_key)
} else {
write!(
f,
"{} {}",
self.key_modifiers
.iter()
.map(|m| m.to_string())
.collect::<Vec<_>>()
.join(" "),
self.bare_key
)
}
}
}
#[cfg(not(target_family = "wasm"))]
impl Into<Modifiers> for &KeyModifier {
fn into(self) -> Modifiers {
match self {
KeyModifier::Shift => Modifiers::SHIFT,
KeyModifier::Alt => Modifiers::ALT,
KeyModifier::Ctrl => Modifiers::CTRL,
KeyModifier::Super => Modifiers::SUPER,
}
}
}
#[derive(Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
pub enum BareKey {
PageDown,
PageUp,
Left,
Down,
Up,
Right,
Home,
End,
Backspace,
Delete,
Insert,
F(u8),
Char(char),
Tab,
Esc,
Enter,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
Menu,
}
impl fmt::Display for BareKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BareKey::PageDown => write!(f, "PgDn"),
BareKey::PageUp => write!(f, "PgUp"),
BareKey::Left => write!(f, "←"),
BareKey::Down => write!(f, "↓"),
BareKey::Up => write!(f, "↑"),
BareKey::Right => write!(f, "→"),
BareKey::Home => write!(f, "HOME"),
BareKey::End => write!(f, "END"),
BareKey::Backspace => write!(f, "BACKSPACE"),
BareKey::Delete => write!(f, "DEL"),
BareKey::Insert => write!(f, "INS"),
BareKey::F(index) => write!(f, "F{}", index),
BareKey::Char(' ') => write!(f, "SPACE"),
BareKey::Char(character) => write!(f, "{}", character),
BareKey::Tab => write!(f, "TAB"),
BareKey::Esc => write!(f, "ESC"),
BareKey::Enter => write!(f, "ENTER"),
BareKey::CapsLock => write!(f, "CAPSlOCK"),
BareKey::ScrollLock => write!(f, "SCROLLlOCK"),
BareKey::NumLock => write!(f, "NUMLOCK"),
BareKey::PrintScreen => write!(f, "PRINTSCREEN"),
BareKey::Pause => write!(f, "PAUSE"),
BareKey::Menu => write!(f, "MENU"),
}
}
}
impl FromStr for BareKey {
type Err = Box<dyn std::error::Error>;
fn from_str(key_str: &str) -> Result<Self, Self::Err> {
match key_str.to_ascii_lowercase().as_str() {
"pagedown" => Ok(BareKey::PageDown),
"pageup" => Ok(BareKey::PageUp),
"left" => Ok(BareKey::Left),
"down" => Ok(BareKey::Down),
"up" => Ok(BareKey::Up),
"right" => Ok(BareKey::Right),
"home" => Ok(BareKey::Home),
"end" => Ok(BareKey::End),
"backspace" => Ok(BareKey::Backspace),
"delete" => Ok(BareKey::Delete),
"insert" => Ok(BareKey::Insert),
"f1" => Ok(BareKey::F(1)),
"f2" => Ok(BareKey::F(2)),
"f3" => Ok(BareKey::F(3)),
"f4" => Ok(BareKey::F(4)),
"f5" => Ok(BareKey::F(5)),
"f6" => Ok(BareKey::F(6)),
"f7" => Ok(BareKey::F(7)),
"f8" => Ok(BareKey::F(8)),
"f9" => Ok(BareKey::F(9)),
"f10" => Ok(BareKey::F(10)),
"f11" => Ok(BareKey::F(11)),
"f12" => Ok(BareKey::F(12)),
"tab" => Ok(BareKey::Tab),
"esc" => Ok(BareKey::Esc),
"enter" => Ok(BareKey::Enter),
"capslock" => Ok(BareKey::CapsLock),
"scrolllock" => Ok(BareKey::ScrollLock),
"numlock" => Ok(BareKey::NumLock),
"printscreen" => Ok(BareKey::PrintScreen),
"pause" => Ok(BareKey::Pause),
"menu" => Ok(BareKey::Menu),
"space" => Ok(BareKey::Char(' ')),
_ => {
if key_str.chars().count() == 1 {
if let Some(character) = key_str.chars().next() {
return Ok(BareKey::Char(character));
}
}
Err("unsupported key".into())
},
}
}
}
#[derive(
Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord, Display,
)]
pub enum KeyModifier {
Ctrl,
Alt,
Shift,
Super,
}
impl FromStr for KeyModifier {
type Err = Box<dyn std::error::Error>;
fn from_str(key_str: &str) -> Result<Self, Self::Err> {
match key_str.to_ascii_lowercase().as_str() {
"shift" => Ok(KeyModifier::Shift),
"alt" => Ok(KeyModifier::Alt),
"ctrl" => Ok(KeyModifier::Ctrl),
"super" => Ok(KeyModifier::Super),
_ => Err("unsupported modifier".into()),
}
}
}
impl BareKey {
pub fn from_bytes_with_u(bytes: &[u8]) -> Option<Self> {
match str::from_utf8(bytes) {
Ok("27") => Some(BareKey::Esc),
Ok("13") => Some(BareKey::Enter),
Ok("9") => Some(BareKey::Tab),
Ok("127") => Some(BareKey::Backspace),
Ok("57358") => Some(BareKey::CapsLock),
Ok("57359") => Some(BareKey::ScrollLock),
Ok("57360") => Some(BareKey::NumLock),
Ok("57361") => Some(BareKey::PrintScreen),
Ok("57362") => Some(BareKey::Pause),
Ok("57363") => Some(BareKey::Menu),
Ok("57399") => Some(BareKey::Char('0')),
Ok("57400") => Some(BareKey::Char('1')),
Ok("57401") => Some(BareKey::Char('2')),
Ok("57402") => Some(BareKey::Char('3')),
Ok("57403") => Some(BareKey::Char('4')),
Ok("57404") => Some(BareKey::Char('5')),
Ok("57405") => Some(BareKey::Char('6')),
Ok("57406") => Some(BareKey::Char('7')),
Ok("57407") => Some(BareKey::Char('8')),
Ok("57408") => Some(BareKey::Char('9')),
Ok("57409") => Some(BareKey::Char('.')),
Ok("57410") => Some(BareKey::Char('/')),
Ok("57411") => Some(BareKey::Char('*')),
Ok("57412") => Some(BareKey::Char('-')),
Ok("57413") => Some(BareKey::Char('+')),
Ok("57414") => Some(BareKey::Enter),
Ok("57415") => Some(BareKey::Char('=')),
Ok("57417") => Some(BareKey::Left),
Ok("57418") => Some(BareKey::Right),
Ok("57419") => Some(BareKey::Up),
Ok("57420") => Some(BareKey::Down),
Ok("57421") => Some(BareKey::PageUp),
Ok("57422") => Some(BareKey::PageDown),
Ok("57423") => Some(BareKey::Home),
Ok("57424") => Some(BareKey::End),
Ok("57425") => Some(BareKey::Insert),
Ok("57426") => Some(BareKey::Delete),
Ok(num) => u8::from_str_radix(num, 10)
.ok()
.map(|n| BareKey::Char((n as char).to_ascii_lowercase())),
_ => None,
}
}
pub fn from_bytes_with_tilde(bytes: &[u8]) -> Option<Self> {
match str::from_utf8(bytes) {
Ok("2") => Some(BareKey::Insert),
Ok("3") => Some(BareKey::Delete),
Ok("5") => Some(BareKey::PageUp),
Ok("6") => Some(BareKey::PageDown),
Ok("7") => Some(BareKey::Home),
Ok("8") => Some(BareKey::End),
Ok("11") => Some(BareKey::F(1)),
Ok("12") => Some(BareKey::F(2)),
Ok("13") => Some(BareKey::F(3)),
Ok("14") => Some(BareKey::F(4)),
Ok("15") => Some(BareKey::F(5)),
Ok("17") => Some(BareKey::F(6)),
Ok("18") => Some(BareKey::F(7)),
Ok("19") => Some(BareKey::F(8)),
Ok("20") => Some(BareKey::F(9)),
Ok("21") => Some(BareKey::F(10)),
Ok("23") => Some(BareKey::F(11)),
Ok("24") => Some(BareKey::F(12)),
_ => None,
}
}
pub fn from_bytes_with_no_ending_byte(bytes: &[u8]) -> Option<Self> {
match str::from_utf8(bytes) {
Ok("1D") | Ok("D") => Some(BareKey::Left),
Ok("1C") | Ok("C") => Some(BareKey::Right),
Ok("1A") | Ok("A") => Some(BareKey::Up),
Ok("1B") | Ok("B") => Some(BareKey::Down),
Ok("1H") | Ok("H") => Some(BareKey::Home),
Ok("1F") | Ok("F") => Some(BareKey::End),
Ok("1P") | Ok("P") => Some(BareKey::F(1)),
Ok("1Q") | Ok("Q") => Some(BareKey::F(2)),
Ok("1S") | Ok("S") => Some(BareKey::F(4)),
_ => None,
}
}
}
bitflags::bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ModifierFlags: u8 {
const SHIFT = 0b0000_0001;
const ALT = 0b0000_0010;
const CONTROL = 0b0000_0100;
const SUPER = 0b0000_1000;
// we don't actually use the below, left here for completeness in case we want to add them
// later
const HYPER = 0b0001_0000;
const META = 0b0010_0000;
const CAPS_LOCK = 0b0100_0000;
const NUM_LOCK = 0b1000_0000;
}
}
impl KeyModifier {
pub fn from_bytes(bytes: &[u8]) -> BTreeSet<KeyModifier> {
let modifier_flags = str::from_utf8(bytes)
.ok() // convert to string: (eg. "16")
.and_then(|s| u8::from_str_radix(&s, 10).ok()) // convert to u8: (eg. 16)
.map(|s| s.saturating_sub(1)) // subtract 1: (eg. 15)
.and_then(|b| ModifierFlags::from_bits(b)); // bitflags: (0b0000_1111: Shift, Alt, Control, Super)
let mut key_modifiers = BTreeSet::new();
if let Some(modifier_flags) = modifier_flags {
for name in modifier_flags.iter() {
match name {
ModifierFlags::SHIFT => key_modifiers.insert(KeyModifier::Shift),
ModifierFlags::ALT => key_modifiers.insert(KeyModifier::Alt),
ModifierFlags::CONTROL => key_modifiers.insert(KeyModifier::Ctrl),
ModifierFlags::SUPER => key_modifiers.insert(KeyModifier::Super),
_ => false,
};
}
}
key_modifiers
}
}
impl KeyWithModifier {
pub fn new(bare_key: BareKey) -> Self {
KeyWithModifier {
bare_key,
key_modifiers: BTreeSet::new(),
}
}
pub fn new_with_modifiers(bare_key: BareKey, key_modifiers: BTreeSet<KeyModifier>) -> Self {
KeyWithModifier {
bare_key,
key_modifiers,
}
}
pub fn with_shift_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Shift);
self
}
pub fn with_alt_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Alt);
self
}
pub fn with_ctrl_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Ctrl);
self
}
pub fn with_super_modifier(mut self) -> Self {
self.key_modifiers.insert(KeyModifier::Super);
self
}
pub fn from_bytes_with_u(number_bytes: &[u8], modifier_bytes: &[u8]) -> Option<Self> {
// CSI number ; modifiers u
let bare_key = BareKey::from_bytes_with_u(number_bytes);
match bare_key {
Some(bare_key) => {
let key_modifiers = KeyModifier::from_bytes(modifier_bytes);
Some(KeyWithModifier {
bare_key,
key_modifiers,
})
},
_ => None,
}
}
pub fn from_bytes_with_tilde(number_bytes: &[u8], modifier_bytes: &[u8]) -> Option<Self> {
// CSI number ; modifiers ~
let bare_key = BareKey::from_bytes_with_tilde(number_bytes);
match bare_key {
Some(bare_key) => {
let key_modifiers = KeyModifier::from_bytes(modifier_bytes);
Some(KeyWithModifier {
bare_key,
key_modifiers,
})
},
_ => None,
}
}
pub fn from_bytes_with_no_ending_byte(
number_bytes: &[u8],
modifier_bytes: &[u8],
) -> Option<Self> {
// CSI 1; modifiers [ABCDEFHPQS]
let bare_key = BareKey::from_bytes_with_no_ending_byte(number_bytes);
match bare_key {
Some(bare_key) => {
let key_modifiers = KeyModifier::from_bytes(modifier_bytes);
Some(KeyWithModifier {
bare_key,
key_modifiers,
})
},
_ => None,
}
}
pub fn strip_common_modifiers(&self, common_modifiers: &Vec<KeyModifier>) -> Self {
let common_modifiers: BTreeSet<&KeyModifier> = common_modifiers.into_iter().collect();
KeyWithModifier {
bare_key: self.bare_key.clone(),
key_modifiers: self
.key_modifiers
.iter()
.filter(|m| !common_modifiers.contains(m))
.cloned()
.collect(),
}
}
pub fn is_key_without_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.is_empty()
}
pub fn is_key_with_ctrl_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Ctrl)
}
pub fn is_key_with_alt_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Alt)
}
pub fn is_key_with_shift_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Shift)
}
pub fn is_key_with_super_modifier(&self, key: BareKey) -> bool {
self.bare_key == key && self.key_modifiers.contains(&KeyModifier::Super)
}
pub fn is_cancel_key(&self) -> bool {
// self.bare_key == BareKey::Esc || self.is_key_with_ctrl_modifier(BareKey::Char('c'))
self.bare_key == BareKey::Esc
}
#[cfg(not(target_family = "wasm"))]
pub fn to_termwiz_modifiers(&self) -> Modifiers {
let mut modifiers = Modifiers::empty();
for modifier in &self.key_modifiers {
modifiers.set(modifier.into(), true);
}
modifiers
}
#[cfg(not(target_family = "wasm"))]
pub fn to_termwiz_keycode(&self) -> KeyCode {
match self.bare_key {
BareKey::PageDown => KeyCode::PageDown,
BareKey::PageUp => KeyCode::PageUp,
BareKey::Left => KeyCode::LeftArrow,
BareKey::Down => KeyCode::DownArrow,
BareKey::Up => KeyCode::UpArrow,
BareKey::Right => KeyCode::RightArrow,
BareKey::Home => KeyCode::Home,
BareKey::End => KeyCode::End,
BareKey::Backspace => KeyCode::Backspace,
BareKey::Delete => KeyCode::Delete,
BareKey::Insert => KeyCode::Insert,
BareKey::F(index) => KeyCode::Function(index),
BareKey::Char(character) => KeyCode::Char(character),
BareKey::Tab => KeyCode::Tab,
BareKey::Esc => KeyCode::Escape,
BareKey::Enter => KeyCode::Enter,
BareKey::CapsLock => KeyCode::CapsLock,
BareKey::ScrollLock => KeyCode::ScrollLock,
BareKey::NumLock => KeyCode::NumLock,
BareKey::PrintScreen => KeyCode::PrintScreen,
BareKey::Pause => KeyCode::Pause,
BareKey::Menu => KeyCode::Menu,
}
}
#[cfg(not(target_family = "wasm"))]
pub fn serialize_non_kitty(&self) -> Option<String> {
let modifiers = self.to_termwiz_modifiers();
let key_code_encode_modes = KeyCodeEncodeModes {
encoding: KeyboardEncoding::Xterm,
// all these flags are false because they have been dealt with before this
// serialization
application_cursor_keys: false,
newline_mode: false,
modify_other_keys: None,
};
self.to_termwiz_keycode()
.encode(modifiers, key_code_encode_modes, true)
.ok()
}
#[cfg(not(target_family = "wasm"))]
pub fn serialize_kitty(&self) -> Option<String> {
let modifiers = self.to_termwiz_modifiers();
let key_code_encode_modes = KeyCodeEncodeModes {
encoding: KeyboardEncoding::Kitty(KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES),
// all these flags are false because they have been dealt with before this
// serialization
application_cursor_keys: false,
newline_mode: false,
modify_other_keys: None,
};
self.to_termwiz_keycode()
.encode(modifiers, key_code_encode_modes, true)
.ok()
}
pub fn has_no_modifiers(&self) -> bool {
self.key_modifiers.is_empty()
}
pub fn has_modifiers(&self, modifiers: &[KeyModifier]) -> bool {
for modifier in modifiers {
if !self.key_modifiers.contains(modifier) {
return false;
}
}
true
}
}
#[derive(Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
pub enum Direction {
Left,
Right,
Up,
Down,
}
impl Default for Direction {
fn default() -> Self {
Direction::Left
}
}
impl Direction {
pub fn invert(&self) -> Direction {
match *self {
Direction::Left => Direction::Right,
Direction::Down => Direction::Up,
Direction::Up => Direction::Down,
Direction::Right => Direction::Left,
}
}
pub fn is_horizontal(&self) -> bool {
matches!(self, Direction::Left | Direction::Right)
}
pub fn is_vertical(&self) -> bool {
matches!(self, Direction::Down | Direction::Up)
}
}
impl fmt::Display for Direction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Direction::Left => write!(f, "←"),
Direction::Right => write!(f, "→"),
Direction::Up => write!(f, "↑"),
Direction::Down => write!(f, "↓"),
}
}
}
impl FromStr for Direction {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Left" | "left" => Ok(Direction::Left),
"Right" | "right" => Ok(Direction::Right),
"Up" | "up" => Ok(Direction::Up),
"Down" | "down" => Ok(Direction::Down),
_ => Err(format!(
"Failed to parse Direction. Unknown Direction: {}",
s
)),
}
}
}
/// Resize operation to perform.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum Resize {
Increase,
Decrease,
}
impl Default for Resize {
fn default() -> Self {
Resize::Increase
}
}
impl Resize {
pub fn invert(&self) -> Self {
match self {
Resize::Increase => Resize::Decrease,
Resize::Decrease => Resize::Increase,
}
}
}
impl fmt::Display for Resize {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Resize::Increase => write!(f, "+"),
Resize::Decrease => write!(f, "-"),
}
}
}
impl FromStr for Resize {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"Increase" | "increase" | "+" => Ok(Resize::Increase),
"Decrease" | "decrease" | "-" => Ok(Resize::Decrease),
_ => Err(format!(
"failed to parse resize type. Unknown specifier '{}'",
s
)),
}
}
}
/// Container type that fully describes resize operations.
///
/// This is best thought of as follows:
///
/// - `resize` commands how the total *area* of the pane will change as part of this resize
/// operation.
/// - `direction` has two meanings:
/// - `None` means to resize all borders equally
/// - Anything else means to move the named border to achieve the change in area
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct ResizeStrategy {
/// Whether to increase or resize total area
pub resize: Resize,
/// With which border, if any, to change area
pub direction: Option<Direction>,
/// If set to true (default), increasing resizes towards a viewport border will be inverted.
/// I.e. a scenario like this ("increase right"):
///
/// ```text
/// +---+---+
/// | | X |->
/// +---+---+
/// ```
///
/// turns into this ("decrease left"):
///
/// ```text
/// +---+---+
/// | |-> |
/// +---+---+
/// ```
pub invert_on_boundaries: bool,
}
impl From<Direction> for ResizeStrategy {
fn from(direction: Direction) -> Self {
ResizeStrategy::new(Resize::Increase, Some(direction))
}
}
impl From<Resize> for ResizeStrategy {
fn from(resize: Resize) -> Self {
ResizeStrategy::new(resize, None)
}
}
impl ResizeStrategy {
pub fn new(resize: Resize, direction: Option<Direction>) -> Self {
ResizeStrategy {
resize,
direction,
invert_on_boundaries: true,
}
}
pub fn invert(&self) -> ResizeStrategy {
let resize = match self.resize {
Resize::Increase => Resize::Decrease,
Resize::Decrease => Resize::Increase,
};
let direction = match self.direction {
Some(direction) => Some(direction.invert()),
None => None,
};
ResizeStrategy::new(resize, direction)
}
pub fn resize_type(&self) -> Resize {
self.resize
}
pub fn direction(&self) -> Option<Direction> {
self.direction
}
pub fn direction_horizontal(&self) -> bool {
matches!(
self.direction,
Some(Direction::Left) | Some(Direction::Right)
)
}
pub fn direction_vertical(&self) -> bool {
matches!(self.direction, Some(Direction::Up) | Some(Direction::Down))
}
pub fn resize_increase(&self) -> bool {
self.resize == Resize::Increase
}
pub fn resize_decrease(&self) -> bool {
self.resize == Resize::Decrease
}
pub fn move_left_border_left(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Left))
}
pub fn move_left_border_right(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Left))
}
pub fn move_lower_border_down(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Down))
}
pub fn move_lower_border_up(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Down))
}
pub fn move_upper_border_up(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Up))
}
pub fn move_upper_border_down(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Up))
}
pub fn move_right_border_right(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == Some(Direction::Right))
}
pub fn move_right_border_left(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == Some(Direction::Right))
}
pub fn move_all_borders_out(&self) -> bool {
(self.resize == Resize::Increase) && (self.direction == None)
}
pub fn move_all_borders_in(&self) -> bool {
(self.resize == Resize::Decrease) && (self.direction == None)
}
}
impl fmt::Display for ResizeStrategy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let resize = match self.resize {
Resize::Increase => "increase",
Resize::Decrease => "decrease",
};
let border = match self.direction {
Some(Direction::Left) => "left",
Some(Direction::Down) => "bottom",
Some(Direction::Up) => "top",
Some(Direction::Right) => "right",
None => "every",
};
write!(f, "{} size on {} border", resize, border)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
// FIXME: This should be extended to handle different button clicks (not just
// left click) and the `ScrollUp` and `ScrollDown` events could probably be
// merged into a single `Scroll(isize)` event.
pub enum Mouse {
ScrollUp(usize), // number of lines
ScrollDown(usize), // number of lines
LeftClick(isize, usize), // line and column
RightClick(isize, usize), // line and column
Hold(isize, usize), // line and column
Release(isize, usize), // line and column
Hover(isize, usize), // line and column
}
impl Mouse {
pub fn position(&self) -> Option<(usize, usize)> {
// (line, column)
match self {
Mouse::LeftClick(line, column) => Some((*line as usize, *column as usize)),
Mouse::RightClick(line, column) => Some((*line as usize, *column as usize)),
Mouse::Hold(line, column) => Some((*line as usize, *column as usize)),
Mouse::Release(line, column) => Some((*line as usize, *column as usize)),
Mouse::Hover(line, column) => Some((*line as usize, *column as usize)),
_ => None,
}
}
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct FileMetadata {
pub is_dir: bool,
pub is_file: bool,
pub is_symlink: bool,
pub len: u64,
}
impl From<Metadata> for FileMetadata {
fn from(metadata: Metadata) -> Self {
FileMetadata {
is_dir: metadata.is_dir(),
is_file: metadata.is_file(),
is_symlink: metadata.is_symlink(),
len: metadata.len(),
}
}
}
/// These events can be subscribed to with subscribe method exported by `zellij-tile`.
/// Once subscribed to, they will trigger the `update` method of the `ZellijPlugin` trait.
#[derive(Debug, Clone, PartialEq, EnumDiscriminants, Display, Serialize, Deserialize)]
#[strum_discriminants(derive(EnumString, Hash, Serialize, Deserialize))]
#[strum_discriminants(name(EventType))]
#[non_exhaustive]
pub enum Event {
ModeUpdate(ModeInfo),
TabUpdate(Vec<TabInfo>),
PaneUpdate(PaneManifest),
/// A key was pressed while the user is focused on this plugin's pane
Key(KeyWithModifier),
/// A mouse event happened while the user is focused on this plugin's pane
Mouse(Mouse),
/// A timer expired set by the `set_timeout` method exported by `zellij-tile`.
Timer(f64),
/// Text was copied to the clipboard anywhere in the app
CopyToClipboard(CopyDestination),
/// Failed to copy text to clipboard anywhere in the app
SystemClipboardFailure,
/// Input was received anywhere in the app
InputReceived,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/envs.rs | zellij-utils/src/envs.rs | /// Uniformly operates ZELLIJ* environment variables
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, HashMap},
env::{set_var, var},
};
use std::fmt;
pub const ZELLIJ_ENV_KEY: &str = "ZELLIJ";
pub fn get_zellij() -> Result<String> {
Ok(var(ZELLIJ_ENV_KEY)?)
}
pub fn set_zellij(v: String) {
set_var(ZELLIJ_ENV_KEY, v);
}
pub const SESSION_NAME_ENV_KEY: &str = "ZELLIJ_SESSION_NAME";
pub fn get_session_name() -> Result<String> {
Ok(var(SESSION_NAME_ENV_KEY)?)
}
pub fn set_session_name(v: String) {
set_var(SESSION_NAME_ENV_KEY, v);
}
pub const SOCKET_DIR_ENV_KEY: &str = "ZELLIJ_SOCKET_DIR";
pub fn get_socket_dir() -> Result<String> {
Ok(var(SOCKET_DIR_ENV_KEY)?)
}
/// Manage ENVIRONMENT VARIABLES from the configuration and the layout files
#[derive(Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnvironmentVariables {
env: HashMap<String, String>,
}
impl fmt::Debug for EnvironmentVariables {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut stable_sorted = BTreeMap::new();
for (env_var_name, env_var_value) in self.env.iter() {
stable_sorted.insert(env_var_name, env_var_value);
}
write!(f, "{:#?}", stable_sorted)
}
}
impl EnvironmentVariables {
/// Merges two structs, keys from `other` supersede keys from `self`
pub fn merge(&self, other: Self) -> Self {
let mut env = self.clone();
env.env.extend(other.env);
env
}
pub fn from_data(data: HashMap<String, String>) -> Self {
EnvironmentVariables { env: data }
}
/// Set all the ENVIRONMENT VARIABLES, that are configured
/// in the configuration and layout files
pub fn set_vars(&self) {
for (k, v) in &self.env {
set_var(k, v);
}
}
pub fn inner(&self) -> &HashMap<String, String> {
&self.env
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/ipc.rs | zellij-utils/src/ipc.rs | //! IPC stuff for starting to split things into a client and server model.
use crate::{
data::{ClientId, ConnectToSession, KeyWithModifier, Style},
errors::{prelude::*, ErrorContext},
input::{actions::Action, cli_assets::CliAssets},
pane_size::{Size, SizeInPixels},
};
use interprocess::local_socket::LocalSocketStream;
use log::warn;
use nix::unistd::dup;
use serde::{Deserialize, Serialize};
use std::{
fmt::{Display, Error, Formatter},
io::{self, Read, Write},
marker::PhantomData,
os::unix::io::{AsRawFd, FromRawFd},
};
// Protobuf imports
use crate::client_server_contract::client_server_contract::{
ClientToServerMsg as ProtoClientToServerMsg, ServerToClientMsg as ProtoServerToClientMsg,
};
use prost::Message;
mod enum_conversions;
mod protobuf_conversion;
#[cfg(test)]
mod tests;
type SessionId = u64;
#[derive(PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct Session {
// Unique ID for this session
id: SessionId,
// Identifier for the underlying IPC primitive (socket, pipe)
conn_name: String,
// User configured alias for the session
alias: String,
}
// How do we want to connect to a session?
#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClientType {
Reader,
Writer,
}
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
pub struct ClientAttributes {
pub size: Size,
pub style: Style,
}
#[derive(Default, Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub struct PixelDimensions {
pub text_area_size: Option<SizeInPixels>,
pub character_cell_size: Option<SizeInPixels>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct PaneReference {
pub pane_id: u32,
pub is_plugin: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct ColorRegister {
pub index: usize,
pub color: String,
}
impl PixelDimensions {
pub fn merge(&mut self, other: PixelDimensions) {
if let Some(text_area_size) = other.text_area_size {
self.text_area_size = Some(text_area_size);
}
if let Some(character_cell_size) = other.character_cell_size {
self.character_cell_size = Some(character_cell_size);
}
}
}
// Types of messages sent from the client to the server
#[allow(clippy::large_enum_variant)]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum ClientToServerMsg {
DetachSession {
client_ids: Vec<ClientId>,
},
TerminalPixelDimensions {
pixel_dimensions: PixelDimensions,
},
BackgroundColor {
color: String,
},
ForegroundColor {
color: String,
},
ColorRegisters {
color_registers: Vec<ColorRegister>,
},
TerminalResize {
new_size: Size,
},
FirstClientConnected {
cli_assets: CliAssets,
is_web_client: bool,
},
AttachClient {
cli_assets: CliAssets,
tab_position_to_focus: Option<usize>,
pane_to_focus: Option<PaneReference>,
is_web_client: bool,
},
AttachWatcherClient {
terminal_size: Size,
is_web_client: bool,
},
Action {
action: Action,
terminal_id: Option<u32>,
client_id: Option<ClientId>,
is_cli_client: bool,
},
Key {
key: KeyWithModifier,
raw_bytes: Vec<u8>,
is_kitty_keyboard_protocol: bool,
},
ClientExited,
KillSession,
ConnStatus,
WebServerStarted {
base_url: String,
},
FailedToStartWebServer {
error: String,
},
}
// Types of messages sent from the server to the client
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum ServerToClientMsg {
Render {
content: String,
},
UnblockInputThread,
Exit {
exit_reason: ExitReason,
},
Connected,
Log {
lines: Vec<String>,
},
LogError {
lines: Vec<String>,
},
SwitchSession {
connect_to_session: ConnectToSession,
},
UnblockCliPipeInput {
pipe_name: String,
},
CliPipeOutput {
pipe_name: String,
output: String,
},
QueryTerminalSize,
StartWebServer,
RenamedSession {
name: String,
},
ConfigFileUpdated,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub enum ExitReason {
Normal,
NormalDetached,
ForceDetached,
CannotAttach,
Disconnect,
WebClientsForbidden,
CustomExitStatus(i32),
Error(String),
}
impl Display for ExitReason {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match self {
Self::Normal => write!(f, "Bye from Zellij!"),
Self::NormalDetached => write!(f, "Session detached"),
Self::ForceDetached => write!(
f,
"Session was detached from this client (possibly because another client connected)"
),
Self::CannotAttach => write!(
f,
"Session attached to another client. Use --force flag to force connect."
),
Self::WebClientsForbidden => write!(
f,
"Web clients are not allowed in this session - cannot attach"
),
Self::Disconnect => {
let session_tip = match crate::envs::get_session_name() {
Ok(name) => format!("`zellij attach {}`", name),
Err(_) => "see `zellij ls` and `zellij attach`".to_string(),
};
write!(
f,
"
Your zellij client lost connection to the zellij server.
As a safety measure, you have been disconnected from the current zellij session.
However, the session should still exist and none of your data should be lost.
This usually means that your terminal didn't process server messages quick
enough. Maybe your system is currently under high load, or your terminal
isn't performant enough.
There are a few things you can try now:
- Reattach to your previous session and see if it works out better this
time: {session_tip}
- Try using a faster (maybe GPU-accelerated) terminal emulator
"
)
},
Self::CustomExitStatus(exit_status) => write!(f, "Exit {}", exit_status),
Self::Error(e) => write!(f, "Error occurred in server:\n{}", e),
}
}
}
/// Sends messages on a stream socket, along with an [`ErrorContext`].
pub struct IpcSenderWithContext<T: Serialize> {
sender: io::BufWriter<LocalSocketStream>,
_phantom: PhantomData<T>,
}
impl<T: Serialize> IpcSenderWithContext<T> {
/// Returns a sender to the given [LocalSocketStream](interprocess::local_socket::LocalSocketStream).
pub fn new(sender: LocalSocketStream) -> Self {
Self {
sender: io::BufWriter::new(sender),
_phantom: PhantomData,
}
}
pub fn send_client_msg(&mut self, msg: ClientToServerMsg) -> Result<()> {
let proto_msg: ProtoClientToServerMsg = msg.into();
write_protobuf_message(&mut self.sender, &proto_msg)?;
let _ = self.sender.flush();
Ok(())
}
pub fn send_server_msg(&mut self, msg: ServerToClientMsg) -> Result<()> {
let proto_msg: ProtoServerToClientMsg = msg.into();
write_protobuf_message(&mut self.sender, &proto_msg)?;
let _ = self.sender.flush();
Ok(())
}
/// Returns an [`IpcReceiverWithContext`] with the same socket as this sender.
pub fn get_receiver<F>(&self) -> IpcReceiverWithContext<F>
where
F: for<'de> Deserialize<'de> + Serialize,
{
let sock_fd = self.sender.get_ref().as_raw_fd();
let dup_sock = dup(sock_fd).unwrap();
let socket = unsafe { LocalSocketStream::from_raw_fd(dup_sock) };
IpcReceiverWithContext::new(socket)
}
}
/// Receives messages on a stream socket, along with an [`ErrorContext`].
pub struct IpcReceiverWithContext<T> {
receiver: io::BufReader<LocalSocketStream>,
_phantom: PhantomData<T>,
}
impl<T> IpcReceiverWithContext<T>
where
T: for<'de> Deserialize<'de> + Serialize,
{
/// Returns a receiver to the given [LocalSocketStream](interprocess::local_socket::LocalSocketStream).
pub fn new(receiver: LocalSocketStream) -> Self {
Self {
receiver: io::BufReader::new(receiver),
_phantom: PhantomData,
}
}
pub fn recv_client_msg(&mut self) -> Option<(ClientToServerMsg, ErrorContext)> {
match read_protobuf_message::<ProtoClientToServerMsg>(&mut self.receiver) {
Ok(proto_msg) => match proto_msg.try_into() {
Ok(rust_msg) => Some((rust_msg, ErrorContext::default())),
Err(e) => {
warn!("Error converting protobuf to ClientToServerMsg: {:?}", e);
None
},
},
Err(_e) => None,
}
}
pub fn recv_server_msg(&mut self) -> Option<(ServerToClientMsg, ErrorContext)> {
match read_protobuf_message::<ProtoServerToClientMsg>(&mut self.receiver) {
Ok(proto_msg) => match proto_msg.try_into() {
Ok(rust_msg) => Some((rust_msg, ErrorContext::default())),
Err(e) => {
warn!("Error converting protobuf to ServerToClientMsg: {:?}", e);
None
},
},
Err(_e) => None,
}
}
/// Returns an [`IpcSenderWithContext`] with the same socket as this receiver.
pub fn get_sender<F: Serialize>(&self) -> IpcSenderWithContext<F> {
let sock_fd = self.receiver.get_ref().as_raw_fd();
let dup_sock = dup(sock_fd).unwrap();
let socket = unsafe { LocalSocketStream::from_raw_fd(dup_sock) };
IpcSenderWithContext::new(socket)
}
}
// Protobuf wire format utilities
fn read_protobuf_message<T: Message + Default>(reader: &mut impl Read) -> Result<T> {
// Read length-prefixed protobuf message
let mut len_bytes = [0u8; 4];
reader.read_exact(&mut len_bytes)?;
let len = u32::from_le_bytes(len_bytes) as usize;
let mut buf = vec![0u8; len];
reader.read_exact(&mut buf)?;
T::decode(&buf[..]).map_err(Into::into)
}
fn write_protobuf_message<T: Message>(writer: &mut impl Write, msg: &T) -> Result<()> {
let encoded = msg.encode_to_vec();
let len = encoded.len() as u32;
// we measure the length of the message and transmit it first so that the reader will be able
// to first read exactly 4 bytes (representing this length) and then read that amount of bytes
// as the actual message - this is so that we are able to distinct whole messages over the wire
// stream
writer.write_all(&len.to_le_bytes())?;
writer.write_all(&encoded)?;
Ok(())
}
// Protobuf helper functions
pub fn send_protobuf_client_to_server(
sender: &mut IpcSenderWithContext<ClientToServerMsg>,
msg: ClientToServerMsg,
) -> Result<()> {
let proto_msg: ProtoClientToServerMsg = msg.into();
write_protobuf_message(&mut sender.sender, &proto_msg)?;
let _ = sender.sender.flush();
Ok(())
}
pub fn send_protobuf_server_to_client(
sender: &mut IpcSenderWithContext<ServerToClientMsg>,
msg: ServerToClientMsg,
) -> Result<()> {
let proto_msg: ProtoServerToClientMsg = msg.into();
write_protobuf_message(&mut sender.sender, &proto_msg)?;
let _ = sender.sender.flush();
Ok(())
}
pub fn recv_protobuf_client_to_server(
receiver: &mut IpcReceiverWithContext<ClientToServerMsg>,
) -> Option<(ClientToServerMsg, ErrorContext)> {
match read_protobuf_message::<ProtoClientToServerMsg>(&mut receiver.receiver) {
Ok(proto_msg) => match proto_msg.try_into() {
Ok(rust_msg) => Some((rust_msg, ErrorContext::default())),
Err(e) => {
warn!("Error converting protobuf message: {:?}", e);
None
},
},
Err(_e) => None,
}
}
pub fn recv_protobuf_server_to_client(
receiver: &mut IpcReceiverWithContext<ServerToClientMsg>,
) -> Option<(ServerToClientMsg, ErrorContext)> {
match read_protobuf_message::<ProtoServerToClientMsg>(&mut receiver.receiver) {
Ok(proto_msg) => match proto_msg.try_into() {
Ok(rust_msg) => Some((rust_msg, ErrorContext::default())),
Err(e) => {
warn!("Error converting protobuf message: {:?}", e);
None
},
},
Err(_e) => None,
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/web_server_contract/protobuf_conversion.rs | zellij-utils/src/web_server_contract/protobuf_conversion.rs | use crate::errors::prelude::*;
use crate::web_server_commands::InstructionForWebServer as RustInstructionForWebServer;
use crate::web_server_contract::web_server_contract::{
instruction_for_web_server, InstructionForWebServer as ProtoInstructionForWebServer,
ShutdownWebServerMsg,
};
// Convert Rust InstructionForWebServer to protobuf
impl From<RustInstructionForWebServer> for ProtoInstructionForWebServer {
fn from(instruction: RustInstructionForWebServer) -> Self {
let instruction = match instruction {
RustInstructionForWebServer::ShutdownWebServer => {
instruction_for_web_server::Instruction::ShutdownWebServer(ShutdownWebServerMsg {})
},
};
ProtoInstructionForWebServer {
instruction: Some(instruction),
}
}
}
// Convert protobuf InstructionForWebServer to Rust
impl TryFrom<ProtoInstructionForWebServer> for RustInstructionForWebServer {
type Error = anyhow::Error;
fn try_from(proto_instruction: ProtoInstructionForWebServer) -> Result<Self> {
match proto_instruction.instruction {
Some(instruction_for_web_server::Instruction::ShutdownWebServer(_)) => {
Ok(RustInstructionForWebServer::ShutdownWebServer)
},
None => Err(anyhow!("Missing instruction in InstructionForWebServer")),
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/web_server_contract/mod.rs | zellij-utils/src/web_server_contract/mod.rs | include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/assets/prost_web_server/generated_web_server_api.rs"
));
mod protobuf_conversion;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/event.rs | zellij-utils/src/plugin_api/event.rs | pub use super::generated_api::api::{
action::{Action as ProtobufAction, Position as ProtobufPosition},
event::{
event::Payload as ProtobufEventPayload, pane_scrollback_response,
ActionCompletePayload as ProtobufActionCompletePayload, ClientInfo as ProtobufClientInfo,
ClientPaneHistory as ProtobufClientPaneHistory,
ClientTabHistory as ProtobufClientTabHistory, ContextItem as ProtobufContextItem,
CopyDestination as ProtobufCopyDestination, CwdChangedPayload as ProtobufCwdChangedPayload,
Event as ProtobufEvent, EventNameList as ProtobufEventNameList,
EventType as ProtobufEventType, FileMetadata as ProtobufFileMetadata,
InputModeKeybinds as ProtobufInputModeKeybinds, KeyBind as ProtobufKeyBind,
LayoutInfo as ProtobufLayoutInfo, ModeUpdatePayload as ProtobufModeUpdatePayload,
PaneContents as ProtobufPaneContents, PaneContentsEntry as ProtobufPaneContentsEntry,
PaneId as ProtobufPaneId, PaneInfo as ProtobufPaneInfo,
PaneManifest as ProtobufPaneManifest,
PaneRenderReportPayload as ProtobufPaneRenderReportPayload,
PaneScrollbackResponse as ProtobufPaneScrollbackResponse, PaneType as ProtobufPaneType,
PluginInfo as ProtobufPluginInfo, ResurrectableSession as ProtobufResurrectableSession,
SelectedText as ProtobufSelectedText, SessionManifest as ProtobufSessionManifest,
TabInfo as ProtobufTabInfo, UserActionPayload as ProtobufUserActionPayload,
WebServerStatusPayload as ProtobufWebServerStatusPayload, WebSharing as ProtobufWebSharing,
*,
},
input_mode::InputMode as ProtobufInputMode,
key::Key as ProtobufKey,
style::Style as ProtobufStyle,
};
#[allow(hidden_glob_reexports)]
use crate::data::{
ClientId, ClientInfo, CopyDestination, Event, EventType, FileMetadata, InputMode,
KeyWithModifier, LayoutInfo, ModeInfo, Mouse, PaneContents, PaneId, PaneInfo, PaneManifest,
PaneScrollbackResponse, PermissionStatus, PluginCapabilities, PluginInfo, SelectedText,
SessionInfo, Style, TabInfo, WebServerStatus, WebSharing,
};
use crate::errors::prelude::*;
use crate::input::actions::Action;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::TryFrom;
use std::net::IpAddr;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;
impl TryFrom<ProtobufEvent> for Event {
type Error = &'static str;
fn try_from(protobuf_event: ProtobufEvent) -> Result<Self, &'static str> {
match ProtobufEventType::from_i32(protobuf_event.name) {
Some(ProtobufEventType::ModeUpdate) => match protobuf_event.payload {
Some(ProtobufEventPayload::ModeUpdatePayload(protobuf_mode_update_payload)) => {
let mode_info: ModeInfo = protobuf_mode_update_payload.try_into()?;
Ok(Event::ModeUpdate(mode_info))
},
_ => Err("Malformed payload for the ModeUpdate Event"),
},
Some(ProtobufEventType::TabUpdate) => match protobuf_event.payload {
Some(ProtobufEventPayload::TabUpdatePayload(protobuf_tab_info_payload)) => {
let mut tab_infos: Vec<TabInfo> = vec![];
for protobuf_tab_info in protobuf_tab_info_payload.tab_info {
tab_infos.push(TabInfo::try_from(protobuf_tab_info)?);
}
Ok(Event::TabUpdate(tab_infos))
},
_ => Err("Malformed payload for the TabUpdate Event"),
},
Some(ProtobufEventType::PaneUpdate) => match protobuf_event.payload {
Some(ProtobufEventPayload::PaneUpdatePayload(protobuf_pane_update_payload)) => {
let mut pane_manifest: HashMap<usize, Vec<PaneInfo>> = HashMap::new();
for protobuf_pane_manifest in protobuf_pane_update_payload.pane_manifest {
let tab_index = protobuf_pane_manifest.tab_index as usize;
let mut panes = vec![];
for protobuf_pane_info in protobuf_pane_manifest.panes {
panes.push(protobuf_pane_info.try_into()?);
}
if pane_manifest.contains_key(&tab_index) {
return Err("Duplicate tab definition in pane manifest");
}
pane_manifest.insert(tab_index, panes);
}
Ok(Event::PaneUpdate(PaneManifest {
panes: pane_manifest,
}))
},
_ => Err("Malformed payload for the PaneUpdate Event"),
},
Some(ProtobufEventType::Key) => match protobuf_event.payload {
Some(ProtobufEventPayload::KeyPayload(protobuf_key)) => {
Ok(Event::Key(protobuf_key.try_into()?))
},
_ => Err("Malformed payload for the Key Event"),
},
Some(ProtobufEventType::Mouse) => match protobuf_event.payload {
Some(ProtobufEventPayload::MouseEventPayload(protobuf_mouse)) => {
Ok(Event::Mouse(protobuf_mouse.try_into()?))
},
_ => Err("Malformed payload for the Mouse Event"),
},
Some(ProtobufEventType::Timer) => match protobuf_event.payload {
Some(ProtobufEventPayload::TimerPayload(seconds)) => {
Ok(Event::Timer(seconds as f64))
},
_ => Err("Malformed payload for the Timer Event"),
},
Some(ProtobufEventType::CopyToClipboard) => match protobuf_event.payload {
Some(ProtobufEventPayload::CopyToClipboardPayload(copy_to_clipboard)) => {
let protobuf_copy_to_clipboard =
ProtobufCopyDestination::from_i32(copy_to_clipboard)
.ok_or("Malformed copy to clipboard payload")?;
Ok(Event::CopyToClipboard(
protobuf_copy_to_clipboard.try_into()?,
))
},
_ => Err("Malformed payload for the Copy To Clipboard Event"),
},
Some(ProtobufEventType::SystemClipboardFailure) => match protobuf_event.payload {
None => Ok(Event::SystemClipboardFailure),
_ => Err("Malformed payload for the system clipboard failure Event"),
},
Some(ProtobufEventType::InputReceived) => match protobuf_event.payload {
None => Ok(Event::InputReceived),
_ => Err("Malformed payload for the input received Event"),
},
Some(ProtobufEventType::Visible) => match protobuf_event.payload {
Some(ProtobufEventPayload::VisiblePayload(is_visible)) => {
Ok(Event::Visible(is_visible))
},
_ => Err("Malformed payload for the visible Event"),
},
Some(ProtobufEventType::CustomMessage) => match protobuf_event.payload {
Some(ProtobufEventPayload::CustomMessagePayload(custom_message_payload)) => {
Ok(Event::CustomMessage(
custom_message_payload.message_name,
custom_message_payload.payload,
))
},
_ => Err("Malformed payload for the custom message Event"),
},
Some(ProtobufEventType::FileSystemCreate) => match protobuf_event.payload {
Some(ProtobufEventPayload::FileListPayload(file_list_payload)) => {
let file_paths = file_list_payload
.paths
.iter()
.zip(file_list_payload.paths_metadata.iter())
.map(|(p, m)| (PathBuf::from(p), m.into()))
.collect();
Ok(Event::FileSystemCreate(file_paths))
},
_ => Err("Malformed payload for the file system create Event"),
},
Some(ProtobufEventType::FileSystemRead) => match protobuf_event.payload {
Some(ProtobufEventPayload::FileListPayload(file_list_payload)) => {
let file_paths = file_list_payload
.paths
.iter()
.zip(file_list_payload.paths_metadata.iter())
.map(|(p, m)| (PathBuf::from(p), m.into()))
.collect();
Ok(Event::FileSystemRead(file_paths))
},
_ => Err("Malformed payload for the file system read Event"),
},
Some(ProtobufEventType::FileSystemUpdate) => match protobuf_event.payload {
Some(ProtobufEventPayload::FileListPayload(file_list_payload)) => {
let file_paths = file_list_payload
.paths
.iter()
.zip(file_list_payload.paths_metadata.iter())
.map(|(p, m)| (PathBuf::from(p), m.into()))
.collect();
Ok(Event::FileSystemUpdate(file_paths))
},
_ => Err("Malformed payload for the file system update Event"),
},
Some(ProtobufEventType::FileSystemDelete) => match protobuf_event.payload {
Some(ProtobufEventPayload::FileListPayload(file_list_payload)) => {
let file_paths = file_list_payload
.paths
.iter()
.zip(file_list_payload.paths_metadata.iter())
.map(|(p, m)| (PathBuf::from(p), m.into()))
.collect();
Ok(Event::FileSystemDelete(file_paths))
},
_ => Err("Malformed payload for the file system delete Event"),
},
Some(ProtobufEventType::PermissionRequestResult) => match protobuf_event.payload {
Some(ProtobufEventPayload::PermissionRequestResultPayload(payload)) => {
if payload.granted {
Ok(Event::PermissionRequestResult(PermissionStatus::Granted))
} else {
Ok(Event::PermissionRequestResult(PermissionStatus::Denied))
}
},
_ => Err("Malformed payload for the file system delete Event"),
},
Some(ProtobufEventType::SessionUpdate) => match protobuf_event.payload {
Some(ProtobufEventPayload::SessionUpdatePayload(
protobuf_session_update_payload,
)) => {
let mut session_infos: Vec<SessionInfo> = vec![];
let mut resurrectable_sessions: Vec<(String, Duration)> = vec![];
for protobuf_session_info in protobuf_session_update_payload.session_manifests {
session_infos.push(SessionInfo::try_from(protobuf_session_info)?);
}
for protobuf_resurrectable_session in
protobuf_session_update_payload.resurrectable_sessions
{
resurrectable_sessions.push(protobuf_resurrectable_session.into());
}
Ok(Event::SessionUpdate(
session_infos,
resurrectable_sessions.into(),
))
},
_ => Err("Malformed payload for the SessionUpdate Event"),
},
Some(ProtobufEventType::RunCommandResult) => match protobuf_event.payload {
Some(ProtobufEventPayload::RunCommandResultPayload(run_command_result_payload)) => {
Ok(Event::RunCommandResult(
run_command_result_payload.exit_code,
run_command_result_payload.stdout,
run_command_result_payload.stderr,
run_command_result_payload
.context
.into_iter()
.map(|c_i| (c_i.name, c_i.value))
.collect(),
))
},
_ => Err("Malformed payload for the RunCommandResult Event"),
},
Some(ProtobufEventType::WebRequestResult) => match protobuf_event.payload {
Some(ProtobufEventPayload::WebRequestResultPayload(web_request_result_payload)) => {
Ok(Event::WebRequestResult(
web_request_result_payload.status as u16,
web_request_result_payload
.headers
.into_iter()
.map(|h| (h.name, h.value))
.collect(),
web_request_result_payload.body,
web_request_result_payload
.context
.into_iter()
.map(|c_i| (c_i.name, c_i.value))
.collect(),
))
},
_ => Err("Malformed payload for the WebRequestResult Event"),
},
Some(ProtobufEventType::CommandPaneOpened) => match protobuf_event.payload {
Some(ProtobufEventPayload::CommandPaneOpenedPayload(
command_pane_opened_payload,
)) => Ok(Event::CommandPaneOpened(
command_pane_opened_payload.terminal_pane_id,
command_pane_opened_payload
.context
.into_iter()
.map(|c_i| (c_i.name, c_i.value))
.collect(),
)),
_ => Err("Malformed payload for the CommandPaneOpened Event"),
},
Some(ProtobufEventType::CommandPaneExited) => match protobuf_event.payload {
Some(ProtobufEventPayload::CommandPaneExitedPayload(
command_pane_exited_payload,
)) => Ok(Event::CommandPaneExited(
command_pane_exited_payload.terminal_pane_id,
command_pane_exited_payload.exit_code,
command_pane_exited_payload
.context
.into_iter()
.map(|c_i| (c_i.name, c_i.value))
.collect(),
)),
_ => Err("Malformed payload for the CommandPaneExited Event"),
},
Some(ProtobufEventType::PaneClosed) => match protobuf_event.payload {
Some(ProtobufEventPayload::PaneClosedPayload(pane_closed_payload)) => {
let pane_id = pane_closed_payload
.pane_id
.ok_or("Malformed payload for the PaneClosed Event")?;
Ok(Event::PaneClosed(PaneId::try_from(pane_id)?))
},
_ => Err("Malformed payload for the PaneClosed Event"),
},
Some(ProtobufEventType::EditPaneOpened) => match protobuf_event.payload {
Some(ProtobufEventPayload::EditPaneOpenedPayload(command_pane_opened_payload)) => {
Ok(Event::EditPaneOpened(
command_pane_opened_payload.terminal_pane_id,
command_pane_opened_payload
.context
.into_iter()
.map(|c_i| (c_i.name, c_i.value))
.collect(),
))
},
_ => Err("Malformed payload for the EditPaneOpened Event"),
},
Some(ProtobufEventType::EditPaneExited) => match protobuf_event.payload {
Some(ProtobufEventPayload::EditPaneExitedPayload(command_pane_exited_payload)) => {
Ok(Event::EditPaneExited(
command_pane_exited_payload.terminal_pane_id,
command_pane_exited_payload.exit_code,
command_pane_exited_payload
.context
.into_iter()
.map(|c_i| (c_i.name, c_i.value))
.collect(),
))
},
_ => Err("Malformed payload for the EditPaneExited Event"),
},
Some(ProtobufEventType::CommandPaneReRun) => match protobuf_event.payload {
Some(ProtobufEventPayload::CommandPaneRerunPayload(command_pane_rerun_payload)) => {
Ok(Event::CommandPaneReRun(
command_pane_rerun_payload.terminal_pane_id,
command_pane_rerun_payload
.context
.into_iter()
.map(|c_i| (c_i.name, c_i.value))
.collect(),
))
},
_ => Err("Malformed payload for the CommandPaneReRun Event"),
},
Some(ProtobufEventType::FailedToWriteConfigToDisk) => match protobuf_event.payload {
Some(ProtobufEventPayload::FailedToWriteConfigToDiskPayload(
failed_to_write_configuration_payload,
)) => Ok(Event::FailedToWriteConfigToDisk(
failed_to_write_configuration_payload.file_path,
)),
_ => Err("Malformed payload for the FailedToWriteConfigToDisk Event"),
},
Some(ProtobufEventType::ListClients) => match protobuf_event.payload {
Some(ProtobufEventPayload::ListClientsPayload(mut list_clients_payload)) => {
Ok(Event::ListClients(
list_clients_payload
.client_info
.drain(..)
.filter_map(|c| c.try_into().ok())
.collect(),
))
},
_ => Err("Malformed payload for the FailedToWriteConfigToDisk Event"),
},
Some(ProtobufEventType::HostFolderChanged) => match protobuf_event.payload {
Some(ProtobufEventPayload::HostFolderChangedPayload(
host_folder_changed_payload,
)) => Ok(Event::HostFolderChanged(PathBuf::from(
host_folder_changed_payload.new_host_folder_path,
))),
_ => Err("Malformed payload for the HostFolderChanged Event"),
},
Some(ProtobufEventType::FailedToChangeHostFolder) => match protobuf_event.payload {
Some(ProtobufEventPayload::FailedToChangeHostFolderPayload(
failed_to_change_host_folder_payload,
)) => Ok(Event::FailedToChangeHostFolder(
failed_to_change_host_folder_payload.error_message,
)),
_ => Err("Malformed payload for the FailedToChangeHostFolder Event"),
},
Some(ProtobufEventType::PastedText) => match protobuf_event.payload {
Some(ProtobufEventPayload::PastedTextPayload(pasted_text_payload)) => {
Ok(Event::PastedText(pasted_text_payload.pasted_text))
},
_ => Err("Malformed payload for the PastedText Event"),
},
Some(ProtobufEventType::ConfigWasWrittenToDisk) => match protobuf_event.payload {
None => Ok(Event::ConfigWasWrittenToDisk),
_ => Err("Malformed payload for the ConfigWasWrittenToDisk Event"),
},
Some(ProtobufEventType::WebServerStatus) => match protobuf_event.payload {
Some(ProtobufEventPayload::WebServerStatusPayload(web_server_status)) => {
Ok(Event::WebServerStatus(web_server_status.try_into()?))
},
_ => Err("Malformed payload for the WebServerStatus Event"),
},
Some(ProtobufEventType::BeforeClose) => match protobuf_event.payload {
None => Ok(Event::BeforeClose),
_ => Err("Malformed payload for the BeforeClose Event"),
},
Some(ProtobufEventType::FailedToStartWebServer) => match protobuf_event.payload {
Some(ProtobufEventPayload::FailedToStartWebServerPayload(
failed_to_start_web_server_payload,
)) => Ok(Event::FailedToStartWebServer(
failed_to_start_web_server_payload.error,
)),
_ => Err("Malformed payload for the FailedToStartWebServer Event"),
},
Some(ProtobufEventType::InterceptedKeyPress) => match protobuf_event.payload {
Some(ProtobufEventPayload::KeyPayload(protobuf_key)) => {
Ok(Event::InterceptedKeyPress(protobuf_key.try_into()?))
},
_ => Err("Malformed payload for the InterceptedKeyPress Event"),
},
Some(ProtobufEventType::PaneRenderReport) => match protobuf_event.payload {
Some(ProtobufEventPayload::PaneRenderReportPayload(protobuf_payload)) => {
Ok(Event::PaneRenderReport(protobuf_payload.try_into()?))
},
_ => Err("Malformed payload for the PaneRenderReport Event"),
},
Some(ProtobufEventType::UserAction) => match protobuf_event.payload {
Some(ProtobufEventPayload::UserActionPayload(protobuf_payload)) => {
let action: Action = protobuf_payload
.action
.ok_or("Missing action in UserAction payload")?
.try_into()
.map_err(|_| "Failed to convert Action in UserAction payload")?;
let client_id = protobuf_payload.client_id as u16;
let terminal_id = protobuf_payload.terminal_id;
let cli_client_id = protobuf_payload.cli_client_id.map(|id| id as u16);
Ok(Event::UserAction(
action,
client_id,
terminal_id,
cli_client_id,
))
},
_ => Err("Malformed payload for the UserAction Event"),
},
Some(ProtobufEventType::ActionComplete) => match protobuf_event.payload {
Some(ProtobufEventPayload::ActionCompletePayload(protobuf_payload)) => {
let action: Action = protobuf_payload
.action
.ok_or("Missing action in ActionComplete payload")?
.try_into()
.map_err(|_| "Failed to convert Action in ActionComplete payload")?;
let pane_id = protobuf_payload
.pane_id
.map(|id| id.try_into())
.transpose()
.map_err(|_| "Failed to convert PaneId in ActionComplete payload")?;
let context: BTreeMap<String, String> = protobuf_payload
.context
.into_iter()
.map(|item| (item.name, item.value))
.collect();
Ok(Event::ActionComplete(action, pane_id, context))
},
_ => Err("Malformed payload for the ActionComplete Event"),
},
Some(ProtobufEventType::CwdChanged) => match protobuf_event.payload {
Some(ProtobufEventPayload::CwdChangedPayload(protobuf_payload)) => {
let pane_id: PaneId = protobuf_payload
.pane_id
.ok_or("Missing pane_id in CwdChanged payload")?
.try_into()
.map_err(|_| "Failed to convert PaneId in CwdChanged payload")?;
let new_cwd = PathBuf::from(protobuf_payload.new_cwd);
let focused_client_ids: Vec<ClientId> = protobuf_payload
.focused_client_ids
.into_iter()
.map(|id| id as u16)
.collect();
Ok(Event::CwdChanged(pane_id, new_cwd, focused_client_ids))
},
_ => Err("Malformed payload for the CwdChanged Event"),
},
None => Err("Unknown Protobuf Event"),
}
}
}
impl TryFrom<ProtobufClientInfo> for ClientInfo {
type Error = &'static str;
fn try_from(protobuf_client_info: ProtobufClientInfo) -> Result<Self, &'static str> {
Ok(ClientInfo::new(
protobuf_client_info.client_id as u16,
protobuf_client_info
.pane_id
.ok_or("No pane id found")?
.try_into()?,
protobuf_client_info.running_command,
protobuf_client_info.is_current_client,
))
}
}
impl TryFrom<ClientInfo> for ProtobufClientInfo {
type Error = &'static str;
fn try_from(client_info: ClientInfo) -> Result<Self, &'static str> {
Ok(ProtobufClientInfo {
client_id: client_info.client_id as u32,
pane_id: Some(client_info.pane_id.try_into()?),
running_command: client_info.running_command,
is_current_client: client_info.is_current_client,
})
}
}
impl TryFrom<Event> for ProtobufEvent {
type Error = &'static str;
fn try_from(event: Event) -> Result<Self, &'static str> {
match event {
Event::ModeUpdate(mode_info) => {
let protobuf_mode_update_payload = mode_info.try_into()?;
Ok(ProtobufEvent {
name: ProtobufEventType::ModeUpdate as i32,
payload: Some(event::Payload::ModeUpdatePayload(
protobuf_mode_update_payload,
)),
})
},
Event::TabUpdate(tab_infos) => {
let mut protobuf_tab_infos = vec![];
for tab_info in tab_infos {
protobuf_tab_infos.push(tab_info.try_into()?);
}
let tab_update_payload = TabUpdatePayload {
tab_info: protobuf_tab_infos,
};
Ok(ProtobufEvent {
name: ProtobufEventType::TabUpdate as i32,
payload: Some(event::Payload::TabUpdatePayload(tab_update_payload)),
})
},
Event::PaneUpdate(pane_manifest) => {
let mut protobuf_pane_manifests = vec![];
for (tab_index, pane_infos) in pane_manifest.panes {
let mut protobuf_pane_infos = vec![];
for pane_info in pane_infos {
protobuf_pane_infos.push(pane_info.try_into()?);
}
protobuf_pane_manifests.push(ProtobufPaneManifest {
tab_index: tab_index as u32,
panes: protobuf_pane_infos,
});
}
Ok(ProtobufEvent {
name: ProtobufEventType::PaneUpdate as i32,
payload: Some(event::Payload::PaneUpdatePayload(PaneUpdatePayload {
pane_manifest: protobuf_pane_manifests,
})),
})
},
Event::Key(key) => Ok(ProtobufEvent {
name: ProtobufEventType::Key as i32,
payload: Some(event::Payload::KeyPayload(key.try_into()?)),
}),
Event::Mouse(mouse_event) => {
let protobuf_mouse_payload = mouse_event.try_into()?;
Ok(ProtobufEvent {
name: ProtobufEventType::Mouse as i32,
payload: Some(event::Payload::MouseEventPayload(protobuf_mouse_payload)),
})
},
Event::Timer(seconds) => Ok(ProtobufEvent {
name: ProtobufEventType::Timer as i32,
payload: Some(event::Payload::TimerPayload(seconds as f32)),
}),
Event::CopyToClipboard(clipboard_destination) => {
let protobuf_copy_destination: ProtobufCopyDestination =
clipboard_destination.try_into()?;
Ok(ProtobufEvent {
name: ProtobufEventType::CopyToClipboard as i32,
payload: Some(event::Payload::CopyToClipboardPayload(
protobuf_copy_destination as i32,
)),
})
},
Event::SystemClipboardFailure => Ok(ProtobufEvent {
name: ProtobufEventType::SystemClipboardFailure as i32,
payload: None,
}),
Event::InputReceived => Ok(ProtobufEvent {
name: ProtobufEventType::InputReceived as i32,
payload: None,
}),
Event::Visible(is_visible) => Ok(ProtobufEvent {
name: ProtobufEventType::Visible as i32,
payload: Some(event::Payload::VisiblePayload(is_visible)),
}),
Event::CustomMessage(message, payload) => Ok(ProtobufEvent {
name: ProtobufEventType::CustomMessage as i32,
payload: Some(event::Payload::CustomMessagePayload(CustomMessagePayload {
message_name: message,
payload,
})),
}),
Event::FileSystemCreate(event_paths) => {
let mut paths = vec![];
let mut paths_metadata = vec![];
for (path, path_metadata) in event_paths {
paths.push(path.display().to_string());
paths_metadata.push(path_metadata.into());
}
let file_list_payload = FileListPayload {
paths,
paths_metadata,
};
Ok(ProtobufEvent {
name: ProtobufEventType::FileSystemCreate as i32,
payload: Some(event::Payload::FileListPayload(file_list_payload)),
})
},
Event::FileSystemRead(event_paths) => {
let mut paths = vec![];
let mut paths_metadata = vec![];
for (path, path_metadata) in event_paths {
paths.push(path.display().to_string());
paths_metadata.push(path_metadata.into());
}
let file_list_payload = FileListPayload {
paths,
paths_metadata,
};
Ok(ProtobufEvent {
name: ProtobufEventType::FileSystemRead as i32,
payload: Some(event::Payload::FileListPayload(file_list_payload)),
})
},
Event::FileSystemUpdate(event_paths) => {
let mut paths = vec![];
let mut paths_metadata = vec![];
for (path, path_metadata) in event_paths {
paths.push(path.display().to_string());
paths_metadata.push(path_metadata.into());
}
let file_list_payload = FileListPayload {
paths,
paths_metadata,
};
Ok(ProtobufEvent {
name: ProtobufEventType::FileSystemUpdate as i32,
payload: Some(event::Payload::FileListPayload(file_list_payload)),
})
},
Event::FileSystemDelete(event_paths) => {
let mut paths = vec![];
let mut paths_metadata = vec![];
for (path, path_metadata) in event_paths {
paths.push(path.display().to_string());
paths_metadata.push(path_metadata.into());
}
let file_list_payload = FileListPayload {
paths,
paths_metadata,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/key.rs | zellij-utils/src/plugin_api/key.rs | pub use super::generated_api::api::key::{
key::{
KeyModifier as ProtobufKeyModifier, MainKey as ProtobufMainKey,
NamedKey as ProtobufNamedKey,
},
Key as ProtobufKey,
};
use crate::data::{BareKey, KeyModifier, KeyWithModifier};
use std::collections::BTreeSet;
use std::convert::TryFrom;
impl TryFrom<ProtobufMainKey> for BareKey {
type Error = &'static str;
fn try_from(protobuf_main_key: ProtobufMainKey) -> Result<Self, &'static str> {
match protobuf_main_key {
ProtobufMainKey::Char(character) => Ok(BareKey::Char(char_index_to_char(character))),
ProtobufMainKey::Key(key_index) => {
let key = ProtobufNamedKey::from_i32(key_index).ok_or("invalid_key")?;
Ok(named_key_to_bare_key(key))
},
}
}
}
impl TryFrom<BareKey> for ProtobufMainKey {
type Error = &'static str;
fn try_from(bare_key: BareKey) -> Result<Self, &'static str> {
match bare_key {
BareKey::PageDown => Ok(ProtobufMainKey::Key(ProtobufNamedKey::PageDown as i32)),
BareKey::PageUp => Ok(ProtobufMainKey::Key(ProtobufNamedKey::PageUp as i32)),
BareKey::Left => Ok(ProtobufMainKey::Key(ProtobufNamedKey::LeftArrow as i32)),
BareKey::Down => Ok(ProtobufMainKey::Key(ProtobufNamedKey::DownArrow as i32)),
BareKey::Up => Ok(ProtobufMainKey::Key(ProtobufNamedKey::UpArrow as i32)),
BareKey::Right => Ok(ProtobufMainKey::Key(ProtobufNamedKey::RightArrow as i32)),
BareKey::Home => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Home as i32)),
BareKey::End => Ok(ProtobufMainKey::Key(ProtobufNamedKey::End as i32)),
BareKey::Backspace => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Backspace as i32)),
BareKey::Delete => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Delete as i32)),
BareKey::Insert => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Insert as i32)),
BareKey::F(f_index) => fn_index_to_main_key(f_index),
BareKey::Char(character) => Ok(ProtobufMainKey::Char(character as i32)),
BareKey::Tab => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Tab as i32)),
BareKey::Esc => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Esc as i32)),
BareKey::Enter => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Enter as i32)),
BareKey::CapsLock => Ok(ProtobufMainKey::Key(ProtobufNamedKey::CapsLock as i32)),
BareKey::ScrollLock => Ok(ProtobufMainKey::Key(ProtobufNamedKey::ScrollLock as i32)),
BareKey::NumLock => Ok(ProtobufMainKey::Key(ProtobufNamedKey::NumLock as i32)),
BareKey::PrintScreen => Ok(ProtobufMainKey::Key(ProtobufNamedKey::PrintScreen as i32)),
BareKey::Pause => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Pause as i32)),
BareKey::Menu => Ok(ProtobufMainKey::Key(ProtobufNamedKey::Menu as i32)),
}
}
}
impl TryFrom<ProtobufKeyModifier> for KeyModifier {
type Error = &'static str;
fn try_from(protobuf_key_modifier: ProtobufKeyModifier) -> Result<Self, &'static str> {
match protobuf_key_modifier {
ProtobufKeyModifier::Ctrl => Ok(KeyModifier::Ctrl),
ProtobufKeyModifier::Alt => Ok(KeyModifier::Alt),
ProtobufKeyModifier::Shift => Ok(KeyModifier::Shift),
ProtobufKeyModifier::Super => Ok(KeyModifier::Super),
}
}
}
impl TryFrom<KeyModifier> for ProtobufKeyModifier {
type Error = &'static str;
fn try_from(key_modifier: KeyModifier) -> Result<Self, &'static str> {
match key_modifier {
KeyModifier::Ctrl => Ok(ProtobufKeyModifier::Ctrl),
KeyModifier::Alt => Ok(ProtobufKeyModifier::Alt),
KeyModifier::Shift => Ok(ProtobufKeyModifier::Shift),
KeyModifier::Super => Ok(ProtobufKeyModifier::Super),
}
}
}
impl TryFrom<ProtobufKey> for KeyWithModifier {
type Error = &'static str;
fn try_from(protobuf_key: ProtobufKey) -> Result<Self, &'static str> {
let bare_key = protobuf_key
.main_key
.ok_or("Key must have main_key")?
.try_into()?;
let mut key_modifiers = BTreeSet::new();
if let Some(main_modifier) = protobuf_key.modifier {
key_modifiers.insert(
ProtobufKeyModifier::from_i32(main_modifier)
.ok_or("invalid key modifier")?
.try_into()?,
);
}
for key_modifier in protobuf_key.additional_modifiers {
key_modifiers.insert(
ProtobufKeyModifier::from_i32(key_modifier)
.ok_or("invalid key modifier")?
.try_into()?,
);
}
Ok(KeyWithModifier {
bare_key,
key_modifiers,
})
}
}
impl TryFrom<KeyWithModifier> for ProtobufKey {
type Error = &'static str;
fn try_from(key_with_modifier: KeyWithModifier) -> Result<Self, &'static str> {
let mut modifiers: Vec<ProtobufKeyModifier> = vec![];
for key_modifier in key_with_modifier.key_modifiers {
modifiers.push(key_modifier.try_into()?);
}
Ok(ProtobufKey {
main_key: Some(key_with_modifier.bare_key.try_into()?),
modifier: modifiers.pop().map(|m| m as i32),
additional_modifiers: modifiers.into_iter().map(|m| m as i32).collect(),
})
}
}
fn fn_index_to_main_key(index: u8) -> Result<ProtobufMainKey, &'static str> {
match index {
1 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F1 as i32)),
2 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F2 as i32)),
3 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F3 as i32)),
4 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F4 as i32)),
5 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F5 as i32)),
6 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F6 as i32)),
7 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F7 as i32)),
8 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F8 as i32)),
9 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F9 as i32)),
10 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F10 as i32)),
11 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F11 as i32)),
12 => Ok(ProtobufMainKey::Key(ProtobufNamedKey::F12 as i32)),
_ => Err("Invalid key"),
}
}
fn char_index_to_char(char_index: i32) -> char {
char_index as u8 as char
}
fn named_key_to_bare_key(named_key: ProtobufNamedKey) -> BareKey {
match named_key {
ProtobufNamedKey::PageDown => BareKey::PageDown,
ProtobufNamedKey::PageUp => BareKey::PageUp,
ProtobufNamedKey::LeftArrow => BareKey::Left,
ProtobufNamedKey::DownArrow => BareKey::Down,
ProtobufNamedKey::UpArrow => BareKey::Up,
ProtobufNamedKey::RightArrow => BareKey::Right,
ProtobufNamedKey::Home => BareKey::Home,
ProtobufNamedKey::End => BareKey::End,
ProtobufNamedKey::Backspace => BareKey::Backspace,
ProtobufNamedKey::Delete => BareKey::Delete,
ProtobufNamedKey::Insert => BareKey::Insert,
ProtobufNamedKey::F1 => BareKey::F(1),
ProtobufNamedKey::F2 => BareKey::F(2),
ProtobufNamedKey::F3 => BareKey::F(3),
ProtobufNamedKey::F4 => BareKey::F(4),
ProtobufNamedKey::F5 => BareKey::F(5),
ProtobufNamedKey::F6 => BareKey::F(6),
ProtobufNamedKey::F7 => BareKey::F(7),
ProtobufNamedKey::F8 => BareKey::F(8),
ProtobufNamedKey::F9 => BareKey::F(9),
ProtobufNamedKey::F10 => BareKey::F(10),
ProtobufNamedKey::F11 => BareKey::F(11),
ProtobufNamedKey::F12 => BareKey::F(12),
ProtobufNamedKey::Tab => BareKey::Tab,
ProtobufNamedKey::Esc => BareKey::Esc,
ProtobufNamedKey::CapsLock => BareKey::CapsLock,
ProtobufNamedKey::ScrollLock => BareKey::ScrollLock,
ProtobufNamedKey::PrintScreen => BareKey::PrintScreen,
ProtobufNamedKey::Pause => BareKey::Pause,
ProtobufNamedKey::Menu => BareKey::Menu,
ProtobufNamedKey::NumLock => BareKey::NumLock,
ProtobufNamedKey::Enter => BareKey::Enter,
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/command.rs | zellij-utils/src/plugin_api/command.rs | pub use super::generated_api::api::command::Command as ProtobufCommand;
use crate::data::CommandToRun;
use std::convert::TryFrom;
use std::path::PathBuf;
impl TryFrom<ProtobufCommand> for CommandToRun {
type Error = &'static str;
fn try_from(protobuf_command: ProtobufCommand) -> Result<Self, &'static str> {
let path = PathBuf::from(protobuf_command.path);
let args = protobuf_command.args;
let cwd = protobuf_command.cwd.map(|c| PathBuf::from(c));
Ok(CommandToRun { path, args, cwd })
}
}
impl TryFrom<CommandToRun> for ProtobufCommand {
type Error = &'static str;
fn try_from(command_to_run: CommandToRun) -> Result<Self, &'static str> {
Ok(ProtobufCommand {
path: command_to_run.path.display().to_string(),
args: command_to_run.args,
cwd: command_to_run.cwd.map(|c| c.display().to_string()),
})
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/pipe_message.rs | zellij-utils/src/plugin_api/pipe_message.rs | pub use super::generated_api::api::pipe_message::{
Arg as ProtobufArg, PipeMessage as ProtobufPipeMessage, PipeSource as ProtobufPipeSource,
};
use crate::data::{PipeMessage, PipeSource};
use std::convert::TryFrom;
impl TryFrom<ProtobufPipeMessage> for PipeMessage {
type Error = &'static str;
fn try_from(protobuf_pipe_message: ProtobufPipeMessage) -> Result<Self, &'static str> {
let source = match (
ProtobufPipeSource::from_i32(protobuf_pipe_message.source),
protobuf_pipe_message.cli_source_id,
protobuf_pipe_message.plugin_source_id,
) {
(Some(ProtobufPipeSource::Cli), Some(cli_source_id), _) => {
PipeSource::Cli(cli_source_id)
},
(Some(ProtobufPipeSource::Plugin), _, Some(plugin_source_id)) => {
PipeSource::Plugin(plugin_source_id)
},
(Some(ProtobufPipeSource::Keybind), _, _) => PipeSource::Keybind,
_ => return Err("Invalid PipeSource or payload"),
};
let name = protobuf_pipe_message.name;
let payload = protobuf_pipe_message.payload;
let args = protobuf_pipe_message
.args
.into_iter()
.map(|arg| (arg.key, arg.value))
.collect();
let is_private = protobuf_pipe_message.is_private;
Ok(PipeMessage {
source,
name,
payload,
args,
is_private,
})
}
}
impl TryFrom<PipeMessage> for ProtobufPipeMessage {
type Error = &'static str;
fn try_from(pipe_message: PipeMessage) -> Result<Self, &'static str> {
let (source, cli_source_id, plugin_source_id) = match pipe_message.source {
PipeSource::Cli(input_pipe_id) => {
(ProtobufPipeSource::Cli as i32, Some(input_pipe_id), None)
},
PipeSource::Plugin(plugin_id) => {
(ProtobufPipeSource::Plugin as i32, None, Some(plugin_id))
},
PipeSource::Keybind => (ProtobufPipeSource::Keybind as i32, None, None),
};
let name = pipe_message.name;
let payload = pipe_message.payload;
let args: Vec<_> = pipe_message
.args
.into_iter()
.map(|(key, value)| ProtobufArg { key, value })
.collect();
let is_private = pipe_message.is_private;
Ok(ProtobufPipeMessage {
source,
cli_source_id,
plugin_source_id,
name,
payload,
args,
is_private,
})
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/file.rs | zellij-utils/src/plugin_api/file.rs | pub use super::generated_api::api::file::File as ProtobufFile;
use crate::data::FileToOpen;
use std::convert::TryFrom;
use std::path::PathBuf;
impl TryFrom<ProtobufFile> for FileToOpen {
type Error = &'static str;
fn try_from(protobuf_file: ProtobufFile) -> Result<Self, &'static str> {
let path = PathBuf::from(protobuf_file.path);
let line_number = protobuf_file.line_number.map(|l| l as usize);
let cwd = protobuf_file.cwd.map(|c| PathBuf::from(c));
Ok(FileToOpen {
path,
line_number,
cwd,
})
}
}
impl TryFrom<FileToOpen> for ProtobufFile {
type Error = &'static str;
fn try_from(file_to_open: FileToOpen) -> Result<Self, &'static str> {
Ok(ProtobufFile {
path: file_to_open.path.display().to_string(),
line_number: file_to_open.line_number.map(|l| l as i32),
cwd: file_to_open.cwd.map(|c| c.display().to_string()),
})
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/plugin_command.rs | zellij-utils/src/plugin_api/plugin_command.rs | pub use super::generated_api::api::{
action::{Action as ProtobufAction, PaneIdAndShouldFloat, SwitchToModePayload},
event::{EventNameList as ProtobufEventNameList, Header},
input_mode::InputMode as ProtobufInputMode,
plugin_command::{
get_pane_pid_response, plugin_command::Payload, BreakPanesToNewTabPayload,
BreakPanesToTabWithIndexPayload, ChangeFloatingPanesCoordinatesPayload,
ChangeHostFolderPayload, ClearScreenForPaneIdPayload, CliPipeOutputPayload,
CloseMultiplePanesPayload, CloseTabWithIndexPayload, CommandName, ContextItem,
CopyToClipboardPayload, CreateTokenResponse as ProtobufCreateTokenResponse,
CreateTokenResponse, CursorPosition, EditScrollbackForPaneWithIdPayload,
EmbedMultiplePanesPayload, EnvVariable, ExecCmdPayload,
FixedOrPercent as ProtobufFixedOrPercent,
FixedOrPercentValue as ProtobufFixedOrPercentValue, FloatMultiplePanesPayload,
FloatingPaneCoordinates as ProtobufFloatingPaneCoordinates, GenerateWebLoginTokenPayload,
GetPanePidPayload, GetPanePidResponse as ProtobufGetPanePidResponse,
GetPaneScrollbackPayload, GroupAndUngroupPanesPayload, HidePaneWithIdPayload,
HighlightAndUnhighlightPanesPayload, HttpVerb as ProtobufHttpVerb, IdAndNewName,
KeyToRebind, KeyToUnbind, KillSessionsPayload, ListTokensResponse, LoadNewPluginPayload,
MessageToPluginPayload, MovePaneWithPaneIdInDirectionPayload, MovePaneWithPaneIdPayload,
MovePayload, NewPluginArgs as ProtobufNewPluginArgs, NewTabPayload,
NewTabsWithLayoutInfoPayload, OpenCommandPaneFloatingNearPluginPayload,
OpenCommandPaneInPlaceOfPluginPayload, OpenCommandPaneNearPluginPayload,
OpenCommandPanePayload, OpenFileFloatingNearPluginPayload, OpenFileInPlaceOfPluginPayload,
OpenFileNearPluginPayload, OpenFilePayload, OpenTerminalFloatingNearPluginPayload,
OpenTerminalInPlaceOfPluginPayload, OpenTerminalNearPluginPayload,
PageScrollDownInPaneIdPayload, PageScrollUpInPaneIdPayload, PaneId as ProtobufPaneId,
PaneIdAndFloatingPaneCoordinates, PaneType as ProtobufPaneType,
PluginCommand as ProtobufPluginCommand, PluginMessagePayload, RebindKeysPayload,
ReconfigurePayload, ReloadPluginPayload, RenameWebLoginTokenPayload,
RenameWebTokenResponse, ReplacePaneWithExistingPanePayload, RequestPluginPermissionPayload,
RerunCommandPanePayload, ResizePaneIdWithDirectionPayload, ResizePayload,
RevokeAllWebTokensResponse, RevokeTokenResponse, RevokeWebLoginTokenPayload,
RunActionPayload, RunCommandPayload, ScrollDownInPaneIdPayload,
ScrollToBottomInPaneIdPayload, ScrollToTopInPaneIdPayload, ScrollUpInPaneIdPayload,
SetFloatingPanePinnedPayload, SetSelfMouseSelectionSupportPayload, SetTimeoutPayload,
ShowCursorPayload, ShowPaneWithIdPayload, StackPanesPayload, SubscribePayload,
SwitchSessionPayload, SwitchTabToPayload, TogglePaneEmbedOrEjectForPaneIdPayload,
TogglePaneIdFullscreenPayload, UnsubscribePayload, WebRequestPayload,
WriteCharsToPaneIdPayload, WriteToPaneIdPayload,
},
plugin_permission::PermissionType as ProtobufPermissionType,
resize::ResizeAction as ProtobufResizeAction,
};
use crate::data::{
ConnectToSession, FloatingPaneCoordinates, GetPanePidResponse, HttpVerb, InputMode,
KeyWithModifier, MessageToPlugin, NewPluginArgs, PaneId, PermissionType, PluginCommand,
};
use crate::input::actions::Action;
use crate::input::layout::SplitSize;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::path::PathBuf;
impl Into<FloatingPaneCoordinates> for ProtobufFloatingPaneCoordinates {
fn into(self) -> FloatingPaneCoordinates {
FloatingPaneCoordinates {
x: self
.x
.and_then(|x| match ProtobufFixedOrPercent::from_i32(x.r#type) {
Some(ProtobufFixedOrPercent::Percent) => {
Some(SplitSize::Percent(x.value as usize))
},
Some(ProtobufFixedOrPercent::Fixed) => Some(SplitSize::Fixed(x.value as usize)),
None => None,
}),
y: self
.y
.and_then(|y| match ProtobufFixedOrPercent::from_i32(y.r#type) {
Some(ProtobufFixedOrPercent::Percent) => {
Some(SplitSize::Percent(y.value as usize))
},
Some(ProtobufFixedOrPercent::Fixed) => Some(SplitSize::Fixed(y.value as usize)),
None => None,
}),
width: self.width.and_then(|width| {
match ProtobufFixedOrPercent::from_i32(width.r#type) {
Some(ProtobufFixedOrPercent::Percent) => {
Some(SplitSize::Percent(width.value as usize))
},
Some(ProtobufFixedOrPercent::Fixed) => {
Some(SplitSize::Fixed(width.value as usize))
},
None => None,
}
}),
height: self.height.and_then(|height| {
match ProtobufFixedOrPercent::from_i32(height.r#type) {
Some(ProtobufFixedOrPercent::Percent) => {
Some(SplitSize::Percent(height.value as usize))
},
Some(ProtobufFixedOrPercent::Fixed) => {
Some(SplitSize::Fixed(height.value as usize))
},
None => None,
}
}),
pinned: self.pinned,
}
}
}
impl Into<ProtobufFloatingPaneCoordinates> for FloatingPaneCoordinates {
fn into(self) -> ProtobufFloatingPaneCoordinates {
ProtobufFloatingPaneCoordinates {
x: match self.x {
Some(SplitSize::Percent(percent)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Percent as i32,
value: percent as u32,
}),
Some(SplitSize::Fixed(fixed)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Fixed as i32,
value: fixed as u32,
}),
None => None,
},
y: match self.y {
Some(SplitSize::Percent(percent)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Percent as i32,
value: percent as u32,
}),
Some(SplitSize::Fixed(fixed)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Fixed as i32,
value: fixed as u32,
}),
None => None,
},
width: match self.width {
Some(SplitSize::Percent(percent)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Percent as i32,
value: percent as u32,
}),
Some(SplitSize::Fixed(fixed)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Fixed as i32,
value: fixed as u32,
}),
None => None,
},
height: match self.height {
Some(SplitSize::Percent(percent)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Percent as i32,
value: percent as u32,
}),
Some(SplitSize::Fixed(fixed)) => Some(ProtobufFixedOrPercentValue {
r#type: ProtobufFixedOrPercent::Fixed as i32,
value: fixed as u32,
}),
None => None,
},
pinned: self.pinned,
}
}
}
impl Into<HttpVerb> for ProtobufHttpVerb {
fn into(self) -> HttpVerb {
match self {
ProtobufHttpVerb::Get => HttpVerb::Get,
ProtobufHttpVerb::Post => HttpVerb::Post,
ProtobufHttpVerb::Put => HttpVerb::Put,
ProtobufHttpVerb::Delete => HttpVerb::Delete,
}
}
}
impl Into<ProtobufHttpVerb> for HttpVerb {
fn into(self) -> ProtobufHttpVerb {
match self {
HttpVerb::Get => ProtobufHttpVerb::Get,
HttpVerb::Post => ProtobufHttpVerb::Post,
HttpVerb::Put => ProtobufHttpVerb::Put,
HttpVerb::Delete => ProtobufHttpVerb::Delete,
}
}
}
impl TryFrom<ProtobufPaneId> for PaneId {
type Error = &'static str;
fn try_from(protobuf_pane_id: ProtobufPaneId) -> Result<Self, &'static str> {
match ProtobufPaneType::from_i32(protobuf_pane_id.pane_type) {
Some(ProtobufPaneType::Terminal) => Ok(PaneId::Terminal(protobuf_pane_id.id)),
Some(ProtobufPaneType::Plugin) => Ok(PaneId::Plugin(protobuf_pane_id.id)),
None => Err("Failed to convert PaneId"),
}
}
}
impl TryFrom<PaneId> for ProtobufPaneId {
type Error = &'static str;
fn try_from(pane_id: PaneId) -> Result<Self, &'static str> {
match pane_id {
PaneId::Terminal(id) => Ok(ProtobufPaneId {
pane_type: ProtobufPaneType::Terminal as i32,
id,
}),
PaneId::Plugin(id) => Ok(ProtobufPaneId {
pane_type: ProtobufPaneType::Plugin as i32,
id,
}),
}
}
}
impl TryFrom<ProtobufGetPanePidResponse> for GetPanePidResponse {
type Error = &'static str;
fn try_from(protobuf_response: ProtobufGetPanePidResponse) -> Result<Self, &'static str> {
match protobuf_response.result {
Some(get_pane_pid_response::Result::Pid(pid)) => Ok(GetPanePidResponse::Ok(pid)),
Some(get_pane_pid_response::Result::Error(error)) => Ok(GetPanePidResponse::Err(error)),
None => Err("Empty GetPanePidResponse"),
}
}
}
impl From<GetPanePidResponse> for ProtobufGetPanePidResponse {
fn from(response: GetPanePidResponse) -> Self {
match response {
GetPanePidResponse::Ok(pid) => ProtobufGetPanePidResponse {
result: Some(get_pane_pid_response::Result::Pid(pid)),
},
GetPanePidResponse::Err(error) => ProtobufGetPanePidResponse {
result: Some(get_pane_pid_response::Result::Error(error)),
},
}
}
}
impl TryFrom<(InputMode, KeyWithModifier, Vec<Action>)> for KeyToRebind {
type Error = &'static str;
fn try_from(
key_to_rebind: (InputMode, KeyWithModifier, Vec<Action>),
) -> Result<Self, &'static str> {
Ok(KeyToRebind {
input_mode: key_to_rebind.0 as i32,
key: Some(key_to_rebind.1.try_into()?),
actions: key_to_rebind
.2
.into_iter()
.filter_map(|a| a.try_into().ok())
.collect(),
})
}
}
impl TryFrom<(InputMode, KeyWithModifier)> for KeyToUnbind {
type Error = &'static str;
fn try_from(key_to_unbind: (InputMode, KeyWithModifier)) -> Result<Self, &'static str> {
Ok(KeyToUnbind {
input_mode: key_to_unbind.0 as i32,
key: Some(key_to_unbind.1.try_into()?),
})
}
}
fn key_to_rebind_to_plugin_command_assets(
key_to_rebind: KeyToRebind,
) -> Option<(InputMode, KeyWithModifier, Vec<Action>)> {
Some((
ProtobufInputMode::from_i32(key_to_rebind.input_mode)?
.try_into()
.ok()?,
key_to_rebind.key?.try_into().ok()?,
key_to_rebind
.actions
.into_iter()
.filter_map(|a| a.try_into().ok())
.collect(),
))
}
fn key_to_unbind_to_plugin_command_assets(
key_to_unbind: KeyToUnbind,
) -> Option<(InputMode, KeyWithModifier)> {
Some((
ProtobufInputMode::from_i32(key_to_unbind.input_mode)?
.try_into()
.ok()?,
key_to_unbind.key?.try_into().ok()?,
))
}
impl TryFrom<ProtobufPluginCommand> for PluginCommand {
type Error = &'static str;
fn try_from(protobuf_plugin_command: ProtobufPluginCommand) -> Result<Self, &'static str> {
match CommandName::from_i32(protobuf_plugin_command.name) {
Some(CommandName::Subscribe) => match protobuf_plugin_command.payload {
Some(Payload::SubscribePayload(subscribe_payload)) => {
let protobuf_event_list = subscribe_payload.subscriptions;
match protobuf_event_list {
Some(protobuf_event_list) => {
Ok(PluginCommand::Subscribe(protobuf_event_list.try_into()?))
},
None => Err("malformed subscription event"),
}
},
_ => Err("Mismatched payload for Subscribe"),
},
Some(CommandName::Unsubscribe) => match protobuf_plugin_command.payload {
Some(Payload::UnsubscribePayload(unsubscribe_payload)) => {
let protobuf_event_list = unsubscribe_payload.subscriptions;
match protobuf_event_list {
Some(protobuf_event_list) => {
Ok(PluginCommand::Unsubscribe(protobuf_event_list.try_into()?))
},
None => Err("malformed unsubscription event"),
}
},
_ => Err("Mismatched payload for Unsubscribe"),
},
Some(CommandName::SetSelectable) => match protobuf_plugin_command.payload {
Some(Payload::SetSelectablePayload(should_be_selectable)) => {
Ok(PluginCommand::SetSelectable(should_be_selectable))
},
_ => Err("Mismatched payload for SetSelectable"),
},
Some(CommandName::ShowCursor) => match protobuf_plugin_command.payload {
Some(Payload::ShowCursorPayload(payload)) => {
let cursor_position =
payload.position.map(|pos| (pos.x as usize, pos.y as usize));
Ok(PluginCommand::ShowCursor(cursor_position))
},
_ => Err("Mismatched payload for ShowCursor"),
},
Some(CommandName::GetPluginIds) => {
if protobuf_plugin_command.payload.is_some() {
Err("GetPluginIds should not have a payload")
} else {
Ok(PluginCommand::GetPluginIds)
}
},
Some(CommandName::GetZellijVersion) => {
if protobuf_plugin_command.payload.is_some() {
Err("GetZellijVersion should not have a payload")
} else {
Ok(PluginCommand::GetZellijVersion)
}
},
Some(CommandName::OpenFile) => match protobuf_plugin_command.payload {
Some(Payload::OpenFilePayload(file_to_open_payload)) => {
match file_to_open_payload.file_to_open {
Some(file_to_open) => {
let context: BTreeMap<String, String> = file_to_open_payload
.context
.into_iter()
.map(|e| (e.name, e.value))
.collect();
Ok(PluginCommand::OpenFile(file_to_open.try_into()?, context))
},
None => Err("Malformed open file payload"),
}
},
_ => Err("Mismatched payload for OpenFile"),
},
Some(CommandName::OpenFileFloating) => match protobuf_plugin_command.payload {
Some(Payload::OpenFileFloatingPayload(file_to_open_payload)) => {
let floating_pane_coordinates = file_to_open_payload
.floating_pane_coordinates
.map(|f| f.into());
let context: BTreeMap<String, String> = file_to_open_payload
.context
.into_iter()
.map(|e| (e.name, e.value))
.collect();
match file_to_open_payload.file_to_open {
Some(file_to_open) => Ok(PluginCommand::OpenFileFloating(
file_to_open.try_into()?,
floating_pane_coordinates,
context,
)),
None => Err("Malformed open file payload"),
}
},
_ => Err("Mismatched payload for OpenFileFloating"),
},
Some(CommandName::OpenTerminal) => match protobuf_plugin_command.payload {
Some(Payload::OpenTerminalPayload(file_to_open_payload)) => {
match file_to_open_payload.file_to_open {
Some(file_to_open) => {
Ok(PluginCommand::OpenTerminal(file_to_open.try_into()?))
},
None => Err("Malformed open terminal payload"),
}
},
_ => Err("Mismatched payload for OpenTerminal"),
},
Some(CommandName::OpenTerminalFloating) => match protobuf_plugin_command.payload {
Some(Payload::OpenTerminalFloatingPayload(file_to_open_payload)) => {
let floating_pane_coordinates = file_to_open_payload
.floating_pane_coordinates
.map(|f| f.into());
match file_to_open_payload.file_to_open {
Some(file_to_open) => Ok(PluginCommand::OpenTerminalFloating(
file_to_open.try_into()?,
floating_pane_coordinates,
)),
None => Err("Malformed open terminal floating payload"),
}
},
_ => Err("Mismatched payload for OpenTerminalFloating"),
},
Some(CommandName::OpenCommandPane) => match protobuf_plugin_command.payload {
Some(Payload::OpenCommandPanePayload(command_to_run_payload)) => {
match command_to_run_payload.command_to_run {
Some(command_to_run) => {
let context: BTreeMap<String, String> = command_to_run_payload
.context
.into_iter()
.map(|e| (e.name, e.value))
.collect();
Ok(PluginCommand::OpenCommandPane(
command_to_run.try_into()?,
context,
))
},
None => Err("Malformed open open command pane payload"),
}
},
_ => Err("Mismatched payload for OpenCommandPane"),
},
Some(CommandName::OpenCommandPaneFloating) => match protobuf_plugin_command.payload {
Some(Payload::OpenCommandPaneFloatingPayload(command_to_run_payload)) => {
let floating_pane_coordinates = command_to_run_payload
.floating_pane_coordinates
.map(|f| f.into());
match command_to_run_payload.command_to_run {
Some(command_to_run) => {
let context: BTreeMap<String, String> = command_to_run_payload
.context
.into_iter()
.map(|e| (e.name, e.value))
.collect();
Ok(PluginCommand::OpenCommandPaneFloating(
command_to_run.try_into()?,
floating_pane_coordinates,
context,
))
},
None => Err("Malformed open command pane floating payload"),
}
},
_ => Err("Mismatched payload for OpenCommandPaneFloating"),
},
Some(CommandName::SwitchTabTo) => match protobuf_plugin_command.payload {
Some(Payload::SwitchTabToPayload(switch_to_tab_payload)) => Ok(
PluginCommand::SwitchTabTo(switch_to_tab_payload.tab_index as u32),
),
_ => Err("Mismatched payload for SwitchToTab"),
},
Some(CommandName::SetTimeout) => match protobuf_plugin_command.payload {
Some(Payload::SetTimeoutPayload(set_timeout_payload)) => {
Ok(PluginCommand::SetTimeout(set_timeout_payload.seconds))
},
_ => Err("Mismatched payload for SetTimeout"),
},
Some(CommandName::ExecCmd) => match protobuf_plugin_command.payload {
Some(Payload::ExecCmdPayload(exec_cmd_payload)) => {
Ok(PluginCommand::ExecCmd(exec_cmd_payload.command_line))
},
_ => Err("Mismatched payload for ExecCmd"),
},
Some(CommandName::PostMessageTo) => match protobuf_plugin_command.payload {
Some(Payload::PostMessageToPayload(post_message_to_payload)) => {
match post_message_to_payload.message {
Some(message) => Ok(PluginCommand::PostMessageTo(message.try_into()?)),
None => Err("Malformed post message to payload"),
}
},
_ => Err("Mismatched payload for PostMessageTo"),
},
Some(CommandName::PostMessageToPlugin) => match protobuf_plugin_command.payload {
Some(Payload::PostMessageToPluginPayload(post_message_to_payload)) => {
match post_message_to_payload.message {
Some(message) => {
Ok(PluginCommand::PostMessageToPlugin(message.try_into()?))
},
None => Err("Malformed post message to plugin payload"),
}
},
_ => Err("Mismatched payload for PostMessageToPlugin"),
},
Some(CommandName::HideSelf) => {
if protobuf_plugin_command.payload.is_some() {
return Err("HideSelf should not have a payload");
}
Ok(PluginCommand::HideSelf)
},
Some(CommandName::ShowSelf) => match protobuf_plugin_command.payload {
Some(Payload::ShowSelfPayload(should_float_if_hidden)) => {
Ok(PluginCommand::ShowSelf(should_float_if_hidden))
},
_ => Err("Mismatched payload for ShowSelf"),
},
Some(CommandName::SwitchToMode) => match protobuf_plugin_command.payload {
Some(Payload::SwitchToModePayload(switch_to_mode_payload)) => {
match ProtobufInputMode::from_i32(switch_to_mode_payload.input_mode) {
Some(protobuf_input_mode) => {
Ok(PluginCommand::SwitchToMode(protobuf_input_mode.try_into()?))
},
None => Err("Malformed switch to mode payload"),
}
},
_ => Err("Mismatched payload for SwitchToMode"),
},
Some(CommandName::NewTabsWithLayout) => match protobuf_plugin_command.payload {
Some(Payload::NewTabsWithLayoutPayload(raw_layout)) => {
Ok(PluginCommand::NewTabsWithLayout(raw_layout))
},
_ => Err("Mismatched payload for NewTabsWithLayout"),
},
Some(CommandName::NewTab) => match protobuf_plugin_command.payload {
Some(Payload::NewTabPayload(protobuf_new_tab_payload)) => {
Ok(PluginCommand::NewTab {
name: protobuf_new_tab_payload.name,
cwd: protobuf_new_tab_payload.cwd,
})
},
None => Ok(PluginCommand::NewTab {
name: None,
cwd: None,
}),
_ => Err("Mismatched payload for NewTab"),
},
Some(CommandName::GoToNextTab) => {
if protobuf_plugin_command.payload.is_some() {
return Err("GoToNextTab should not have a payload");
}
Ok(PluginCommand::GoToNextTab)
},
Some(CommandName::GoToPreviousTab) => {
if protobuf_plugin_command.payload.is_some() {
return Err("GoToPreviousTab should not have a payload");
}
Ok(PluginCommand::GoToPreviousTab)
},
Some(CommandName::Resize) => match protobuf_plugin_command.payload {
Some(Payload::ResizePayload(resize_payload)) => match resize_payload.resize {
Some(resize) => Ok(PluginCommand::Resize(resize.try_into()?)),
None => Err("Malformed switch resize payload"),
},
_ => Err("Mismatched payload for Resize"),
},
Some(CommandName::ResizeWithDirection) => match protobuf_plugin_command.payload {
Some(Payload::ResizeWithDirectionPayload(resize_with_direction_payload)) => {
match resize_with_direction_payload.resize {
Some(resize) => Ok(PluginCommand::ResizeWithDirection(resize.try_into()?)),
None => Err("Malformed switch resize payload"),
}
},
_ => Err("Mismatched payload for Resize"),
},
Some(CommandName::FocusNextPane) => {
if protobuf_plugin_command.payload.is_some() {
return Err("FocusNextPane should not have a payload");
}
Ok(PluginCommand::FocusNextPane)
},
Some(CommandName::FocusPreviousPane) => {
if protobuf_plugin_command.payload.is_some() {
return Err("FocusPreviousPane should not have a payload");
}
Ok(PluginCommand::FocusPreviousPane)
},
Some(CommandName::MoveFocus) => match protobuf_plugin_command.payload {
Some(Payload::MoveFocusPayload(move_payload)) => match move_payload.direction {
Some(direction) => Ok(PluginCommand::MoveFocus(direction.try_into()?)),
None => Err("Malformed move focus payload"),
},
_ => Err("Mismatched payload for MoveFocus"),
},
Some(CommandName::MoveFocusOrTab) => match protobuf_plugin_command.payload {
Some(Payload::MoveFocusOrTabPayload(move_payload)) => {
match move_payload.direction {
Some(direction) => Ok(PluginCommand::MoveFocusOrTab(direction.try_into()?)),
None => Err("Malformed move focus or tab payload"),
}
},
_ => Err("Mismatched payload for MoveFocusOrTab"),
},
Some(CommandName::Detach) => {
if protobuf_plugin_command.payload.is_some() {
return Err("Detach should not have a payload");
}
Ok(PluginCommand::Detach)
},
Some(CommandName::EditScrollback) => {
if protobuf_plugin_command.payload.is_some() {
return Err("EditScrollback should not have a payload");
}
Ok(PluginCommand::EditScrollback)
},
Some(CommandName::Write) => match protobuf_plugin_command.payload {
Some(Payload::WritePayload(bytes)) => Ok(PluginCommand::Write(bytes)),
_ => Err("Mismatched payload for Write"),
},
Some(CommandName::WriteChars) => match protobuf_plugin_command.payload {
Some(Payload::WriteCharsPayload(chars)) => Ok(PluginCommand::WriteChars(chars)),
_ => Err("Mismatched payload for WriteChars"),
},
Some(CommandName::ToggleTab) => {
if protobuf_plugin_command.payload.is_some() {
return Err("ToggleTab should not have a payload");
}
Ok(PluginCommand::ToggleTab)
},
Some(CommandName::MovePane) => {
if protobuf_plugin_command.payload.is_some() {
return Err("MovePane should not have a payload");
}
Ok(PluginCommand::MovePane)
},
Some(CommandName::MovePaneWithDirection) => match protobuf_plugin_command.payload {
Some(Payload::MovePaneWithDirectionPayload(move_payload)) => {
match move_payload.direction {
Some(direction) => {
Ok(PluginCommand::MovePaneWithDirection(direction.try_into()?))
},
None => Err("Malformed MovePaneWithDirection payload"),
}
},
_ => Err("Mismatched payload for MovePaneWithDirection"),
},
Some(CommandName::ClearScreen) => {
if protobuf_plugin_command.payload.is_some() {
return Err("ClearScreen should not have a payload");
}
Ok(PluginCommand::ClearScreen)
},
Some(CommandName::ScrollUp) => {
if protobuf_plugin_command.payload.is_some() {
return Err("ScrollUp should not have a payload");
}
Ok(PluginCommand::ScrollUp)
},
Some(CommandName::ScrollDown) => {
if protobuf_plugin_command.payload.is_some() {
return Err("ScrollDown should not have a payload");
}
Ok(PluginCommand::ScrollDown)
},
Some(CommandName::ScrollToTop) => {
if protobuf_plugin_command.payload.is_some() {
return Err("ScrollToTop should not have a payload");
}
Ok(PluginCommand::ScrollToTop)
},
Some(CommandName::ScrollToBottom) => {
if protobuf_plugin_command.payload.is_some() {
return Err("ScrollToBottom should not have a payload");
}
Ok(PluginCommand::ScrollToBottom)
},
Some(CommandName::PageScrollUp) => {
if protobuf_plugin_command.payload.is_some() {
return Err("PageScrollUp should not have a payload");
}
Ok(PluginCommand::PageScrollUp)
},
Some(CommandName::PageScrollDown) => {
if protobuf_plugin_command.payload.is_some() {
return Err("PageScrollDown should not have a payload");
}
Ok(PluginCommand::PageScrollDown)
},
Some(CommandName::ToggleFocusFullscreen) => {
if protobuf_plugin_command.payload.is_some() {
return Err("ToggleFocusFullscreen should not have a payload");
}
Ok(PluginCommand::ToggleFocusFullscreen)
},
Some(CommandName::TogglePaneFrames) => {
if protobuf_plugin_command.payload.is_some() {
return Err("TogglePaneFrames should not have a payload");
}
Ok(PluginCommand::TogglePaneFrames)
},
Some(CommandName::TogglePaneEmbedOrEject) => {
if protobuf_plugin_command.payload.is_some() {
return Err("TogglePaneEmbedOrEject should not have a payload");
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/mod.rs | zellij-utils/src/plugin_api/mod.rs | pub mod action;
pub mod command;
pub mod event;
pub mod file;
pub mod input_mode;
pub mod key;
pub mod message;
pub mod pipe_message;
pub mod plugin_command;
pub mod plugin_ids;
pub mod plugin_permission;
pub mod resize;
pub mod style;
// NOTE: This code is currently out of order.
// Refer to [the PR introducing this change][1] to learn more about the reasons.
// TL;DR: When running `cargo release --dry-run` the build-script in zellij-utils is not executed
// for unknown reasons, causing compilation to fail. To make a new release possible in the
// meantime, we decided to temporarily include the protobuf plugin API definitions
// statically.
//
// [1]: https://github.com/zellij-org/zellij/pull/2711#issuecomment-1695015818
//pub mod generated_api {
// include!(concat!(env!("OUT_DIR"), "/generated_plugin_api.rs"));
//}
pub mod generated_api {
include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/assets/prost/generated_plugin_api.rs"
));
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/style.rs | zellij-utils/src/plugin_api/style.rs | use super::generated_api::api::style::{
color::Payload as ProtobufColorPayload, Color as ProtobufColor, ColorType as ProtobufColorType,
Palette as ProtobufPalette, RgbColorPayload as ProtobufRgbColorPayload, Style as ProtobufStyle,
Styling as ProtobufStyling, ThemeHue as ProtobufThemeHue,
};
use crate::data::{
MultiplayerColors, Palette, PaletteColor, Style, StyleDeclaration, Styling, ThemeHue,
};
use crate::errors::prelude::*;
use std::convert::TryFrom;
impl TryFrom<ProtobufStyle> for Style {
type Error = &'static str;
fn try_from(protobuf_style: ProtobufStyle) -> Result<Self, &'static str> {
let s = protobuf_style
.styling
.ok_or("malformed style payload")?
.try_into()?;
Ok(Style {
colors: s,
rounded_corners: protobuf_style.rounded_corners,
hide_session_name: protobuf_style.hide_session_name,
})
}
}
#[allow(deprecated)]
impl TryFrom<Style> for ProtobufStyle {
type Error = &'static str;
fn try_from(style: Style) -> Result<Self, &'static str> {
let s = ProtobufStyling::try_from(style.colors)?;
let palette = Palette::try_from(style.colors).map_err(|_| "malformed style payload")?;
Ok(ProtobufStyle {
palette: Some(palette.try_into()?),
rounded_corners: style.rounded_corners,
hide_session_name: style.hide_session_name,
styling: Some(s),
})
}
}
fn to_array<T, const N: usize>(v: Vec<T>) -> std::result::Result<[T; N], &'static str> {
v.try_into()
.map_err(|_| "Could not obtain array from protobuf field")
}
fn to_style_declaration(
parsed_array: Result<[PaletteColor; 6], &'static str>,
) -> Result<StyleDeclaration, &'static str> {
parsed_array.map(|arr| StyleDeclaration {
base: arr[0],
background: arr[1],
emphasis_0: arr[2],
emphasis_1: arr[3],
emphasis_2: arr[4],
emphasis_3: arr[5],
})
}
fn to_multiplayer_colors(
parsed_array: Result<[PaletteColor; 10], &'static str>,
) -> Result<MultiplayerColors, &'static str> {
parsed_array.map(|arr| MultiplayerColors {
player_1: arr[0],
player_2: arr[1],
player_3: arr[2],
player_4: arr[3],
player_5: arr[4],
player_6: arr[5],
player_7: arr[6],
player_8: arr[7],
player_9: arr[8],
player_10: arr[9],
})
}
#[macro_export]
macro_rules! color_definitions {
($proto:expr, $declaration:ident, $size:expr) => {
to_style_declaration(to_array::<PaletteColor, $size>(
$proto
.$declaration
.into_iter()
.map(PaletteColor::try_from)
.collect::<Result<Vec<PaletteColor>, _>>()?,
))?
};
}
#[macro_export]
macro_rules! multiplayer_colors {
($proto:expr, $size: expr) => {
to_multiplayer_colors(to_array::<PaletteColor, $size>(
$proto
.multiplayer_user_colors
.into_iter()
.map(PaletteColor::try_from)
.collect::<Result<Vec<PaletteColor>, _>>()?,
))?
};
}
impl TryFrom<ProtobufStyling> for Styling {
type Error = &'static str;
fn try_from(proto: ProtobufStyling) -> std::result::Result<Self, Self::Error> {
let frame_unselected = if proto.frame_unselected.len() > 0 {
Some(color_definitions!(proto, frame_unselected, 6))
} else {
None
};
Ok(Styling {
text_unselected: color_definitions!(proto, text_unselected, 6),
text_selected: color_definitions!(proto, text_selected, 6),
ribbon_unselected: color_definitions!(proto, ribbon_unselected, 6),
ribbon_selected: color_definitions!(proto, ribbon_selected, 6),
table_title: color_definitions!(proto, table_title, 6),
table_cell_unselected: color_definitions!(proto, table_cell_unselected, 6),
table_cell_selected: color_definitions!(proto, table_cell_selected, 6),
list_unselected: color_definitions!(proto, list_unselected, 6),
list_selected: color_definitions!(proto, list_selected, 6),
frame_unselected,
frame_selected: color_definitions!(proto, frame_selected, 6),
frame_highlight: color_definitions!(proto, frame_highlight, 6),
exit_code_success: color_definitions!(proto, exit_code_success, 6),
exit_code_error: color_definitions!(proto, exit_code_error, 6),
multiplayer_user_colors: multiplayer_colors!(proto, 10),
})
}
}
impl TryFrom<StyleDeclaration> for Vec<ProtobufColor> {
type Error = &'static str;
fn try_from(colors: StyleDeclaration) -> std::result::Result<Self, Self::Error> {
Ok(vec![
colors.base.try_into()?,
colors.background.try_into()?,
colors.emphasis_0.try_into()?,
colors.emphasis_1.try_into()?,
colors.emphasis_2.try_into()?,
colors.emphasis_3.try_into()?,
])
}
}
impl TryFrom<MultiplayerColors> for Vec<ProtobufColor> {
type Error = &'static str;
fn try_from(value: MultiplayerColors) -> std::result::Result<Self, Self::Error> {
Ok(vec![
value.player_1.try_into()?,
value.player_2.try_into()?,
value.player_3.try_into()?,
value.player_4.try_into()?,
value.player_5.try_into()?,
value.player_6.try_into()?,
value.player_7.try_into()?,
value.player_8.try_into()?,
value.player_9.try_into()?,
value.player_10.try_into()?,
])
}
}
impl TryFrom<Styling> for ProtobufStyling {
type Error = &'static str;
fn try_from(style: Styling) -> std::result::Result<Self, Self::Error> {
let frame_unselected_vec = match style.frame_unselected {
None => Ok(Vec::new()),
Some(frame_unselected) => frame_unselected.try_into(),
};
Ok(ProtobufStyling {
text_unselected: style.text_unselected.try_into()?,
text_selected: style.text_selected.try_into()?,
ribbon_unselected: style.ribbon_unselected.try_into()?,
ribbon_selected: style.ribbon_selected.try_into()?,
table_title: style.table_title.try_into()?,
table_cell_unselected: style.table_cell_unselected.try_into()?,
table_cell_selected: style.table_cell_selected.try_into()?,
list_unselected: style.list_unselected.try_into()?,
list_selected: style.list_selected.try_into()?,
frame_unselected: frame_unselected_vec?,
frame_selected: style.frame_selected.try_into()?,
frame_highlight: style.frame_highlight.try_into()?,
exit_code_success: style.exit_code_success.try_into()?,
exit_code_error: style.exit_code_error.try_into()?,
multiplayer_user_colors: style.multiplayer_user_colors.try_into()?,
})
}
}
impl TryFrom<ProtobufPalette> for Palette {
type Error = &'static str;
fn try_from(protobuf_palette: ProtobufPalette) -> Result<Self, &'static str> {
Ok(Palette {
theme_hue: ProtobufThemeHue::from_i32(protobuf_palette.theme_hue)
.ok_or("malformed theme_hue payload for Palette")?
.try_into()?,
fg: protobuf_palette
.fg
.ok_or("malformed palette payload")?
.try_into()?,
bg: protobuf_palette
.bg
.ok_or("malformed palette payload")?
.try_into()?,
black: protobuf_palette
.black
.ok_or("malformed palette payload")?
.try_into()?,
red: protobuf_palette
.red
.ok_or("malformed palette payload")?
.try_into()?,
green: protobuf_palette
.green
.ok_or("malformed palette payload")?
.try_into()?,
yellow: protobuf_palette
.yellow
.ok_or("malformed palette payload")?
.try_into()?,
blue: protobuf_palette
.blue
.ok_or("malformed palette payload")?
.try_into()?,
magenta: protobuf_palette
.magenta
.ok_or("malformed palette payload")?
.try_into()?,
cyan: protobuf_palette
.cyan
.ok_or("malformed palette payload")?
.try_into()?,
white: protobuf_palette
.white
.ok_or("malformed palette payload")?
.try_into()?,
orange: protobuf_palette
.orange
.ok_or("malformed palette payload")?
.try_into()?,
gray: protobuf_palette
.gray
.ok_or("malformed palette payload")?
.try_into()?,
purple: protobuf_palette
.purple
.ok_or("malformed palette payload")?
.try_into()?,
gold: protobuf_palette
.gold
.ok_or("malformed palette payload")?
.try_into()?,
silver: protobuf_palette
.silver
.ok_or("malformed palette payload")?
.try_into()?,
pink: protobuf_palette
.pink
.ok_or("malformed palette payload")?
.try_into()?,
brown: protobuf_palette
.brown
.ok_or("malformed palette payload")?
.try_into()?,
..Default::default()
})
}
}
impl TryFrom<Palette> for ProtobufPalette {
type Error = &'static str;
fn try_from(palette: Palette) -> Result<Self, &'static str> {
let theme_hue: ProtobufThemeHue = palette
.theme_hue
.try_into()
.map_err(|_| "malformed payload for palette")?;
Ok(ProtobufPalette {
theme_hue: theme_hue as i32,
fg: Some(palette.fg.try_into()?),
bg: Some(palette.bg.try_into()?),
black: Some(palette.black.try_into()?),
red: Some(palette.red.try_into()?),
green: Some(palette.green.try_into()?),
yellow: Some(palette.yellow.try_into()?),
blue: Some(palette.blue.try_into()?),
magenta: Some(palette.magenta.try_into()?),
cyan: Some(palette.cyan.try_into()?),
white: Some(palette.white.try_into()?),
orange: Some(palette.orange.try_into()?),
gray: Some(palette.gray.try_into()?),
purple: Some(palette.purple.try_into()?),
gold: Some(palette.gold.try_into()?),
silver: Some(palette.silver.try_into()?),
pink: Some(palette.pink.try_into()?),
brown: Some(palette.brown.try_into()?),
..Default::default()
})
}
}
impl TryFrom<ProtobufColor> for PaletteColor {
type Error = &'static str;
fn try_from(protobuf_color: ProtobufColor) -> Result<Self, &'static str> {
match ProtobufColorType::from_i32(protobuf_color.color_type) {
Some(ProtobufColorType::Rgb) => match protobuf_color.payload {
Some(ProtobufColorPayload::RgbColorPayload(rgb_color_payload)) => {
Ok(PaletteColor::Rgb((
rgb_color_payload.red as u8,
rgb_color_payload.green as u8,
rgb_color_payload.blue as u8,
)))
},
_ => Err("malformed payload for Rgb color"),
},
Some(ProtobufColorType::EightBit) => match protobuf_color.payload {
Some(ProtobufColorPayload::EightBitColorPayload(eight_bit_payload)) => {
Ok(PaletteColor::EightBit(eight_bit_payload as u8))
},
_ => Err("malformed payload for 8bit color"),
},
None => Err("malformed payload for Color"),
}
}
}
impl TryFrom<PaletteColor> for ProtobufColor {
type Error = &'static str;
fn try_from(color: PaletteColor) -> Result<Self, &'static str> {
match color {
PaletteColor::Rgb((red, green, blue)) => {
let red = red as u32;
let green = green as u32;
let blue = blue as u32;
Ok(ProtobufColor {
color_type: ProtobufColorType::Rgb as i32,
payload: Some(ProtobufColorPayload::RgbColorPayload(
ProtobufRgbColorPayload { red, green, blue },
)),
})
},
PaletteColor::EightBit(color) => Ok(ProtobufColor {
color_type: ProtobufColorType::EightBit as i32,
payload: Some(ProtobufColorPayload::EightBitColorPayload(color as u32)),
}),
}
}
}
impl TryFrom<ThemeHue> for ProtobufThemeHue {
type Error = &'static str;
fn try_from(theme_hue: ThemeHue) -> Result<Self, &'static str> {
match theme_hue {
ThemeHue::Light => Ok(ProtobufThemeHue::Light),
ThemeHue::Dark => Ok(ProtobufThemeHue::Dark),
}
}
}
impl TryFrom<ProtobufThemeHue> for ThemeHue {
type Error = &'static str;
fn try_from(protobuf_theme_hue: ProtobufThemeHue) -> Result<Self, &'static str> {
match protobuf_theme_hue {
ProtobufThemeHue::Light => Ok(ThemeHue::Light),
ProtobufThemeHue::Dark => Ok(ThemeHue::Dark),
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/plugin_ids.rs | zellij-utils/src/plugin_api/plugin_ids.rs | pub use super::generated_api::api::plugin_ids::{
PluginIds as ProtobufPluginIds, ZellijVersion as ProtobufZellijVersion,
};
use crate::data::PluginIds;
use std::convert::TryFrom;
use std::path::PathBuf;
impl TryFrom<ProtobufPluginIds> for PluginIds {
type Error = &'static str;
fn try_from(protobuf_plugin_ids: ProtobufPluginIds) -> Result<Self, &'static str> {
Ok(PluginIds {
plugin_id: protobuf_plugin_ids.plugin_id as u32,
zellij_pid: protobuf_plugin_ids.zellij_pid as u32,
initial_cwd: PathBuf::from(protobuf_plugin_ids.initial_cwd),
client_id: protobuf_plugin_ids.client_id as u16,
})
}
}
impl TryFrom<PluginIds> for ProtobufPluginIds {
type Error = &'static str;
fn try_from(plugin_ids: PluginIds) -> Result<Self, &'static str> {
Ok(ProtobufPluginIds {
plugin_id: plugin_ids.plugin_id as i32,
zellij_pid: plugin_ids.zellij_pid as i32,
initial_cwd: plugin_ids.initial_cwd.display().to_string(),
client_id: plugin_ids.client_id as u32,
})
}
}
impl TryFrom<&str> for ProtobufZellijVersion {
type Error = &'static str;
fn try_from(zellij_version: &str) -> Result<Self, &'static str> {
Ok(ProtobufZellijVersion {
version: zellij_version.to_owned(),
})
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/input_mode.rs | zellij-utils/src/plugin_api/input_mode.rs | pub use super::generated_api::api::input_mode::{
InputMode as ProtobufInputMode, InputModeMessage as ProtobufInputModeMessage,
};
use crate::data::InputMode;
use std::convert::TryFrom;
impl TryFrom<ProtobufInputMode> for InputMode {
type Error = &'static str;
fn try_from(protobuf_input_mode: ProtobufInputMode) -> Result<Self, &'static str> {
match protobuf_input_mode {
ProtobufInputMode::Normal => Ok(InputMode::Normal),
ProtobufInputMode::Locked => Ok(InputMode::Locked),
ProtobufInputMode::Resize => Ok(InputMode::Resize),
ProtobufInputMode::Pane => Ok(InputMode::Pane),
ProtobufInputMode::Tab => Ok(InputMode::Tab),
ProtobufInputMode::Scroll => Ok(InputMode::Scroll),
ProtobufInputMode::EnterSearch => Ok(InputMode::EnterSearch),
ProtobufInputMode::Search => Ok(InputMode::Search),
ProtobufInputMode::RenameTab => Ok(InputMode::RenameTab),
ProtobufInputMode::RenamePane => Ok(InputMode::RenamePane),
ProtobufInputMode::Session => Ok(InputMode::Session),
ProtobufInputMode::Move => Ok(InputMode::Move),
ProtobufInputMode::Prompt => Ok(InputMode::Prompt),
ProtobufInputMode::Tmux => Ok(InputMode::Tmux),
}
}
}
impl TryFrom<InputMode> for ProtobufInputMode {
type Error = &'static str;
fn try_from(input_mode: InputMode) -> Result<Self, &'static str> {
Ok(match input_mode {
InputMode::Normal => ProtobufInputMode::Normal,
InputMode::Locked => ProtobufInputMode::Locked,
InputMode::Resize => ProtobufInputMode::Resize,
InputMode::Pane => ProtobufInputMode::Pane,
InputMode::Tab => ProtobufInputMode::Tab,
InputMode::Scroll => ProtobufInputMode::Scroll,
InputMode::EnterSearch => ProtobufInputMode::EnterSearch,
InputMode::Search => ProtobufInputMode::Search,
InputMode::RenameTab => ProtobufInputMode::RenameTab,
InputMode::RenamePane => ProtobufInputMode::RenamePane,
InputMode::Session => ProtobufInputMode::Session,
InputMode::Move => ProtobufInputMode::Move,
InputMode::Prompt => ProtobufInputMode::Prompt,
InputMode::Tmux => ProtobufInputMode::Tmux,
})
}
}
impl TryFrom<ProtobufInputModeMessage> for InputMode {
type Error = &'static str;
fn try_from(protobuf_input_mode: ProtobufInputModeMessage) -> Result<Self, &'static str> {
ProtobufInputMode::from_i32(protobuf_input_mode.input_mode)
.and_then(|p| p.try_into().ok())
.ok_or("Invalid input mode")
}
}
impl TryFrom<InputMode> for ProtobufInputModeMessage {
type Error = &'static str;
fn try_from(input_mode: InputMode) -> Result<Self, &'static str> {
let protobuf_input_mode: ProtobufInputMode = input_mode.try_into()?;
Ok(ProtobufInputModeMessage {
input_mode: protobuf_input_mode as i32,
})
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/action.rs | zellij-utils/src/plugin_api/action.rs | pub use super::generated_api::api::{
action::{
action::OptionalPayload,
command_or_plugin::CommandOrPluginType,
pane_run::RunType,
run_plugin_location_data::LocationData,
run_plugin_or_alias::PluginType,
Action as ProtobufAction,
ActionName as ProtobufActionName,
BareKey as ProtobufBareKey,
// New layout-related types
CommandOrPlugin as ProtobufCommandOrPlugin,
DumpScreenPayload,
EditFilePayload,
FloatingPaneCoordinates as ProtobufFloatingPaneCoordinates,
FloatingPaneLayout as ProtobufFloatingPaneLayout,
FloatingPlacement as ProtobufFloatingPlacement,
GoToTabNamePayload,
IdAndName,
InPlaceConfig as ProtobufInPlaceConfig,
KeyModifier as ProtobufKeyModifier,
KeyWithModifier as ProtobufKeyWithModifier,
LaunchOrFocusPluginPayload,
LayoutConstraint as ProtobufLayoutConstraint,
LayoutConstraintFloatingPair as ProtobufLayoutConstraintFloatingPair,
LayoutConstraintTiledPair as ProtobufLayoutConstraintTiledPair,
LayoutConstraintWithValue as ProtobufLayoutConstraintWithValue,
MouseEventPayload as ProtobufMouseEventPayload,
MovePanePayload,
MoveTabDirection as ProtobufMoveTabDirection,
NameAndValue as ProtobufNameAndValue,
NewBlockingPanePayload,
NewFloatingPanePayload,
NewInPlacePanePayload,
NewPanePayload,
NewPanePlacement as ProtobufNewPanePlacement,
NewPluginPanePayload,
NewTabPayload,
NewTiledPanePayload,
OverrideLayoutPayload,
PaneId as ProtobufPaneId,
PaneIdAndShouldFloat,
PaneRun as ProtobufPaneRun,
PercentOrFixed as ProtobufPercentOrFixed,
PluginAlias as ProtobufPluginAlias,
PluginConfiguration as ProtobufPluginConfiguration,
PluginTag as ProtobufPluginTag,
PluginUserConfiguration as ProtobufPluginUserConfiguration,
Position as ProtobufPosition,
RunCommandAction as ProtobufRunCommandAction,
RunEditFileAction as ProtobufRunEditFileAction,
RunPlugin as ProtobufRunPlugin,
RunPluginLocation as ProtobufRunPluginLocation,
RunPluginLocationData as ProtobufRunPluginLocationData,
RunPluginOrAlias as ProtobufRunPluginOrAlias,
ScrollAtPayload,
SearchDirection as ProtobufSearchDirection,
SearchOption as ProtobufSearchOption,
SplitDirection as ProtobufSplitDirection,
SplitSize as ProtobufSplitSize,
StackedPlacement as ProtobufStackedPlacement,
SwapFloatingLayout as ProtobufSwapFloatingLayout,
SwapTiledLayout as ProtobufSwapTiledLayout,
SwitchToModePayload,
TiledPaneLayout as ProtobufTiledPaneLayout,
TiledPlacement as ProtobufTiledPlacement,
UnblockCondition as ProtobufUnblockCondition,
WriteCharsPayload,
WritePayload,
},
input_mode::InputMode as ProtobufInputMode,
resize::{Resize as ProtobufResize, ResizeDirection as ProtobufResizeDirection},
};
use crate::data::{
CommandOrPlugin, Direction, FloatingPaneCoordinates, InputMode, KeyWithModifier,
NewPanePlacement, PaneId, PluginTag, ResizeStrategy, UnblockCondition,
};
use crate::errors::prelude::*;
use crate::input::actions::Action;
use crate::input::actions::{SearchDirection, SearchOption};
use crate::input::command::{OpenFilePayload, RunCommandAction};
use crate::input::layout::SplitSize;
use crate::input::layout::{
FloatingPaneLayout, LayoutConstraint, PercentOrFixed, PluginAlias, PluginUserConfiguration,
Run, RunPlugin, RunPluginLocation, RunPluginOrAlias, SplitDirection, SwapFloatingLayout,
SwapTiledLayout, TiledPaneLayout,
};
use crate::input::mouse::{MouseEvent, MouseEventType};
use crate::position::Position;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::path::PathBuf;
impl TryFrom<ProtobufAction> for Action {
type Error = &'static str;
fn try_from(protobuf_action: ProtobufAction) -> Result<Self, &'static str> {
match ProtobufActionName::from_i32(protobuf_action.name) {
Some(ProtobufActionName::Quit) => match protobuf_action.optional_payload {
Some(_) => Err("The Quit Action should not have a payload"),
None => Ok(Action::Quit),
},
Some(ProtobufActionName::Write) => match protobuf_action.optional_payload {
Some(OptionalPayload::WritePayload(write_payload)) => {
let key_with_modifier = write_payload
.key_with_modifier
.and_then(|k| k.try_into().ok());
Ok(Action::Write {
key_with_modifier,
bytes: write_payload.bytes_to_write,
is_kitty_keyboard_protocol: write_payload.is_kitty_keyboard_protocol,
})
},
_ => Err("Wrong payload for Action::Write"),
},
Some(ProtobufActionName::WriteChars) => match protobuf_action.optional_payload {
Some(OptionalPayload::WriteCharsPayload(write_chars_payload)) => {
Ok(Action::WriteChars {
chars: write_chars_payload.chars,
})
},
_ => Err("Wrong payload for Action::WriteChars"),
},
Some(ProtobufActionName::SwitchToMode) => match protobuf_action.optional_payload {
Some(OptionalPayload::SwitchToModePayload(switch_to_mode_payload)) => {
let input_mode: InputMode =
ProtobufInputMode::from_i32(switch_to_mode_payload.input_mode)
.ok_or("Malformed input mode for SwitchToMode Action")?
.try_into()?;
Ok(Action::SwitchToMode { input_mode })
},
_ => Err("Wrong payload for Action::SwitchToModePayload"),
},
Some(ProtobufActionName::SwitchModeForAllClients) => {
match protobuf_action.optional_payload {
Some(OptionalPayload::SwitchModeForAllClientsPayload(
switch_to_mode_payload,
)) => {
let input_mode: InputMode =
ProtobufInputMode::from_i32(switch_to_mode_payload.input_mode)
.ok_or("Malformed input mode for SwitchToMode Action")?
.try_into()?;
Ok(Action::SwitchModeForAllClients { input_mode })
},
_ => Err("Wrong payload for Action::SwitchModeForAllClients"),
}
},
Some(ProtobufActionName::Resize) => match protobuf_action.optional_payload {
Some(OptionalPayload::ResizePayload(resize_payload)) => {
let resize_strategy: ResizeStrategy = resize_payload.try_into()?;
Ok(Action::Resize {
resize: resize_strategy.resize,
direction: resize_strategy.direction,
})
},
_ => Err("Wrong payload for Action::Resize"),
},
Some(ProtobufActionName::FocusNextPane) => match protobuf_action.optional_payload {
Some(_) => Err("FocusNextPane should not have a payload"),
None => Ok(Action::FocusNextPane),
},
Some(ProtobufActionName::FocusPreviousPane) => match protobuf_action.optional_payload {
Some(_) => Err("FocusPreviousPane should not have a payload"),
None => Ok(Action::FocusPreviousPane),
},
Some(ProtobufActionName::SwitchFocus) => match protobuf_action.optional_payload {
Some(_) => Err("SwitchFocus should not have a payload"),
None => Ok(Action::SwitchFocus),
},
Some(ProtobufActionName::MoveFocus) => match protobuf_action.optional_payload {
Some(OptionalPayload::MoveFocusPayload(move_focus_payload)) => {
let direction: Direction =
ProtobufResizeDirection::from_i32(move_focus_payload)
.ok_or("Malformed resize direction for Action::MoveFocus")?
.try_into()?;
Ok(Action::MoveFocus { direction })
},
_ => Err("Wrong payload for Action::MoveFocus"),
},
Some(ProtobufActionName::MoveFocusOrTab) => match protobuf_action.optional_payload {
Some(OptionalPayload::MoveFocusOrTabPayload(move_focus_or_tab_payload)) => {
let direction: Direction =
ProtobufResizeDirection::from_i32(move_focus_or_tab_payload)
.ok_or("Malformed resize direction for Action::MoveFocusOrTab")?
.try_into()?;
Ok(Action::MoveFocusOrTab { direction })
},
_ => Err("Wrong payload for Action::MoveFocusOrTab"),
},
Some(ProtobufActionName::MovePane) => match protobuf_action.optional_payload {
Some(OptionalPayload::MovePanePayload(payload)) => {
let direction: Option<Direction> = payload
.direction
.and_then(|d| ProtobufResizeDirection::from_i32(d))
.and_then(|d| d.try_into().ok());
Ok(Action::MovePane { direction })
},
_ => Err("Wrong payload for Action::MovePane"),
},
Some(ProtobufActionName::MovePaneBackwards) => match protobuf_action.optional_payload {
Some(_) => Err("MovePaneBackwards should not have a payload"),
None => Ok(Action::MovePaneBackwards),
},
Some(ProtobufActionName::ClearScreen) => match protobuf_action.optional_payload {
Some(_) => Err("ClearScreen should not have a payload"),
None => Ok(Action::ClearScreen),
},
Some(ProtobufActionName::DumpScreen) => match protobuf_action.optional_payload {
Some(OptionalPayload::DumpScreenPayload(payload)) => {
let file_path = payload.file_path;
let include_scrollback = payload.include_scrollback;
Ok(Action::DumpScreen {
file_path,
include_scrollback,
})
},
_ => Err("Wrong payload for Action::DumpScreen"),
},
Some(ProtobufActionName::EditScrollback) => match protobuf_action.optional_payload {
Some(_) => Err("EditScrollback should not have a payload"),
None => Ok(Action::EditScrollback),
},
Some(ProtobufActionName::ScrollUp) => match protobuf_action.optional_payload {
Some(_) => Err("ScrollUp should not have a payload"),
None => Ok(Action::ScrollUp),
},
Some(ProtobufActionName::ScrollDown) => match protobuf_action.optional_payload {
Some(_) => Err("ScrollDown should not have a payload"),
None => Ok(Action::ScrollDown),
},
Some(ProtobufActionName::ScrollUpAt) => match protobuf_action.optional_payload {
Some(OptionalPayload::ScrollUpAtPayload(payload)) => {
let position = payload
.position
.ok_or("ScrollUpAtPayload must have a position")?
.try_into()?;
Ok(Action::ScrollUpAt { position })
},
_ => Err("Wrong payload for Action::ScrollUpAt"),
},
Some(ProtobufActionName::ScrollDownAt) => match protobuf_action.optional_payload {
Some(OptionalPayload::ScrollDownAtPayload(payload)) => {
let position = payload
.position
.ok_or("ScrollDownAtPayload must have a position")?
.try_into()?;
Ok(Action::ScrollDownAt { position })
},
_ => Err("Wrong payload for Action::ScrollDownAt"),
},
Some(ProtobufActionName::ScrollToBottom) => match protobuf_action.optional_payload {
Some(_) => Err("ScrollToBottom should not have a payload"),
None => Ok(Action::ScrollToBottom),
},
Some(ProtobufActionName::ScrollToTop) => match protobuf_action.optional_payload {
Some(_) => Err("ScrollToTop should not have a payload"),
None => Ok(Action::ScrollToTop),
},
Some(ProtobufActionName::PageScrollUp) => match protobuf_action.optional_payload {
Some(_) => Err("PageScrollUp should not have a payload"),
None => Ok(Action::PageScrollUp),
},
Some(ProtobufActionName::PageScrollDown) => match protobuf_action.optional_payload {
Some(_) => Err("PageScrollDown should not have a payload"),
None => Ok(Action::PageScrollDown),
},
Some(ProtobufActionName::HalfPageScrollUp) => match protobuf_action.optional_payload {
Some(_) => Err("HalfPageScrollUp should not have a payload"),
None => Ok(Action::HalfPageScrollUp),
},
Some(ProtobufActionName::HalfPageScrollDown) => {
match protobuf_action.optional_payload {
Some(_) => Err("HalfPageScrollDown should not have a payload"),
None => Ok(Action::HalfPageScrollDown),
}
},
Some(ProtobufActionName::ToggleFocusFullscreen) => {
match protobuf_action.optional_payload {
Some(_) => Err("ToggleFocusFullscreen should not have a payload"),
None => Ok(Action::ToggleFocusFullscreen),
}
},
Some(ProtobufActionName::TogglePaneFrames) => match protobuf_action.optional_payload {
Some(_) => Err("TogglePaneFrames should not have a payload"),
None => Ok(Action::TogglePaneFrames),
},
Some(ProtobufActionName::ToggleActiveSyncTab) => {
match protobuf_action.optional_payload {
Some(_) => Err("ToggleActiveSyncTab should not have a payload"),
None => Ok(Action::ToggleActiveSyncTab),
}
},
Some(ProtobufActionName::NewPane) => match protobuf_action.optional_payload {
Some(OptionalPayload::NewPanePayload(payload)) => {
let direction: Option<Direction> = payload
.direction
.and_then(|d| ProtobufResizeDirection::from_i32(d))
.and_then(|d| d.try_into().ok());
let pane_name = payload.pane_name;
Ok(Action::NewPane {
direction,
pane_name,
start_suppressed: false,
})
},
_ => Err("Wrong payload for Action::NewPane"),
},
Some(ProtobufActionName::EditFile) => match protobuf_action.optional_payload {
Some(OptionalPayload::EditFilePayload(payload)) => {
let file_to_edit = PathBuf::from(payload.file_to_edit);
let line_number: Option<usize> = payload.line_number.map(|l| l as usize);
let cwd: Option<PathBuf> = payload.cwd.map(|p| PathBuf::from(p));
let direction: Option<Direction> = payload
.direction
.and_then(|d| ProtobufResizeDirection::from_i32(d))
.and_then(|d| d.try_into().ok());
let near_current_pane = payload.near_current_pane;
let should_float = payload.should_float;
let should_be_in_place = false;
Ok(Action::EditFile {
payload: OpenFilePayload::new(file_to_edit, line_number, cwd),
direction,
floating: should_float,
in_place: should_be_in_place,
start_suppressed: false,
coordinates: None,
near_current_pane,
})
},
_ => Err("Wrong payload for Action::NewPane"),
},
Some(ProtobufActionName::NewFloatingPane) => match protobuf_action.optional_payload {
Some(OptionalPayload::NewFloatingPanePayload(payload)) => {
let near_current_pane = payload.near_current_pane;
if let Some(payload) = payload.command {
let pane_name = payload.pane_name.clone();
let run_command_action: RunCommandAction = payload.try_into()?;
Ok(Action::NewFloatingPane {
command: Some(run_command_action),
pane_name,
coordinates: None,
near_current_pane,
})
} else {
Ok(Action::NewFloatingPane {
command: None,
pane_name: None,
coordinates: None,
near_current_pane,
})
}
},
_ => Err("Wrong payload for Action::NewFloatingPane"),
},
Some(ProtobufActionName::NewTiledPane) => match protobuf_action.optional_payload {
Some(OptionalPayload::NewTiledPanePayload(payload)) => {
let direction: Option<Direction> = payload
.direction
.and_then(|d| ProtobufResizeDirection::from_i32(d))
.and_then(|d| d.try_into().ok());
let near_current_pane = payload.near_current_pane;
if let Some(payload) = payload.command {
let pane_name = payload.pane_name.clone();
let run_command_action: RunCommandAction = payload.try_into()?;
Ok(Action::NewTiledPane {
direction,
command: Some(run_command_action),
pane_name,
near_current_pane,
})
} else {
Ok(Action::NewTiledPane {
direction,
command: None,
pane_name: None,
near_current_pane,
})
}
},
_ => Err("Wrong payload for Action::NewTiledPane"),
},
Some(ProtobufActionName::TogglePaneEmbedOrFloating) => {
match protobuf_action.optional_payload {
Some(_) => Err("TogglePaneEmbedOrFloating should not have a payload"),
None => Ok(Action::TogglePaneEmbedOrFloating),
}
},
Some(ProtobufActionName::ToggleFloatingPanes) => {
match protobuf_action.optional_payload {
Some(_) => Err("ToggleFloatingPanes should not have a payload"),
None => Ok(Action::ToggleFloatingPanes),
}
},
Some(ProtobufActionName::CloseFocus) => match protobuf_action.optional_payload {
Some(_) => Err("CloseFocus should not have a payload"),
None => Ok(Action::CloseFocus),
},
Some(ProtobufActionName::PaneNameInput) => match protobuf_action.optional_payload {
Some(OptionalPayload::PaneNameInputPayload(bytes)) => {
Ok(Action::PaneNameInput { input: bytes })
},
_ => Err("Wrong payload for Action::PaneNameInput"),
},
Some(ProtobufActionName::UndoRenamePane) => match protobuf_action.optional_payload {
Some(_) => Err("UndoRenamePane should not have a payload"),
None => Ok(Action::UndoRenamePane),
},
Some(ProtobufActionName::NewTab) => {
match protobuf_action.optional_payload {
Some(OptionalPayload::NewTabPayload(payload)) => {
// New behavior: extract all fields from payload
let tiled_layout =
payload.tiled_layout.map(|l| l.try_into()).transpose()?;
let floating_layouts = payload
.floating_layouts
.into_iter()
.map(|l| l.try_into())
.collect::<Result<Vec<_>, _>>()?;
let swap_tiled_layouts = if payload.swap_tiled_layouts.is_empty() {
None
} else {
Some(
payload
.swap_tiled_layouts
.into_iter()
.map(|l| l.try_into())
.collect::<Result<Vec<_>, _>>()?,
)
};
let swap_floating_layouts = if payload.swap_floating_layouts.is_empty() {
None
} else {
Some(
payload
.swap_floating_layouts
.into_iter()
.map(|l| l.try_into())
.collect::<Result<Vec<_>, _>>()?,
)
};
let tab_name = payload.tab_name;
let should_change_focus_to_new_tab = payload.should_change_focus_to_new_tab;
let cwd = payload.cwd.map(PathBuf::from);
let initial_panes = if payload.initial_panes.is_empty() {
None
} else {
Some(
payload
.initial_panes
.into_iter()
.map(|p| p.try_into())
.collect::<Result<Vec<_>, _>>()?,
)
};
let first_pane_unblock_condition = payload
.first_pane_unblock_condition
.and_then(|uc| ProtobufUnblockCondition::from_i32(uc))
.and_then(|uc| uc.try_into().ok());
Ok(Action::NewTab {
tiled_layout,
floating_layouts,
swap_tiled_layouts,
swap_floating_layouts,
tab_name,
should_change_focus_to_new_tab,
cwd,
initial_panes,
first_pane_unblock_condition,
})
},
None => {
// Backwards compatibility: accept None payload for existing plugins
// Return the same defaults as before
Ok(Action::NewTab {
tiled_layout: None,
floating_layouts: vec![],
swap_tiled_layouts: None,
swap_floating_layouts: None,
tab_name: None,
should_change_focus_to_new_tab: true,
cwd: None,
initial_panes: None,
first_pane_unblock_condition: None,
})
},
_ => Err("Wrong payload for Action::NewTab"),
}
},
Some(ProtobufActionName::NoOp) => match protobuf_action.optional_payload {
Some(_) => Err("NoOp should not have a payload"),
None => Ok(Action::NoOp),
},
Some(ProtobufActionName::GoToNextTab) => match protobuf_action.optional_payload {
Some(_) => Err("GoToNextTab should not have a payload"),
None => Ok(Action::GoToNextTab),
},
Some(ProtobufActionName::GoToPreviousTab) => match protobuf_action.optional_payload {
Some(_) => Err("GoToPreviousTab should not have a payload"),
None => Ok(Action::GoToPreviousTab),
},
Some(ProtobufActionName::CloseTab) => match protobuf_action.optional_payload {
Some(_) => Err("CloseTab should not have a payload"),
None => Ok(Action::CloseTab),
},
Some(ProtobufActionName::GoToTab) => match protobuf_action.optional_payload {
Some(OptionalPayload::GoToTabPayload(index)) => Ok(Action::GoToTab { index }),
_ => Err("Wrong payload for Action::GoToTab"),
},
Some(ProtobufActionName::GoToTabName) => match protobuf_action.optional_payload {
Some(OptionalPayload::GoToTabNamePayload(payload)) => {
let tab_name = payload.tab_name;
let create = payload.create;
Ok(Action::GoToTabName {
name: tab_name,
create,
})
},
_ => Err("Wrong payload for Action::GoToTabName"),
},
Some(ProtobufActionName::ToggleTab) => match protobuf_action.optional_payload {
Some(_) => Err("ToggleTab should not have a payload"),
None => Ok(Action::ToggleTab),
},
Some(ProtobufActionName::TabNameInput) => match protobuf_action.optional_payload {
Some(OptionalPayload::TabNameInputPayload(bytes)) => {
Ok(Action::TabNameInput { input: bytes })
},
_ => Err("Wrong payload for Action::TabNameInput"),
},
Some(ProtobufActionName::UndoRenameTab) => match protobuf_action.optional_payload {
Some(_) => Err("UndoRenameTab should not have a payload"),
None => Ok(Action::UndoRenameTab),
},
Some(ProtobufActionName::MoveTab) => match protobuf_action.optional_payload {
Some(OptionalPayload::MoveTabPayload(move_tab_payload)) => {
let direction: Direction = ProtobufMoveTabDirection::from_i32(move_tab_payload)
.ok_or("Malformed move tab direction for Action::MoveTab")?
.try_into()?;
Ok(Action::MoveTab { direction })
},
_ => Err("Wrong payload for Action::MoveTab"),
},
Some(ProtobufActionName::Run) => match protobuf_action.optional_payload {
Some(OptionalPayload::RunPayload(run_command_action)) => {
let run_command_action = run_command_action.try_into()?;
Ok(Action::Run {
command: run_command_action,
near_current_pane: false,
})
},
_ => Err("Wrong payload for Action::Run"),
},
Some(ProtobufActionName::Detach) => match protobuf_action.optional_payload {
Some(_) => Err("Detach should not have a payload"),
None => Ok(Action::Detach),
},
Some(ProtobufActionName::LeftClick) => match protobuf_action.optional_payload {
Some(OptionalPayload::LeftClickPayload(payload)) => {
let position = payload.try_into()?;
Ok(Action::MouseEvent {
event: MouseEvent::new_left_press_event(position),
})
},
_ => Err("Wrong payload for Action::LeftClick"),
},
Some(ProtobufActionName::RightClick) => match protobuf_action.optional_payload {
Some(OptionalPayload::RightClickPayload(payload)) => {
let position = payload.try_into()?;
Ok(Action::MouseEvent {
event: MouseEvent::new_right_press_event(position),
})
},
_ => Err("Wrong payload for Action::RightClick"),
},
Some(ProtobufActionName::MiddleClick) => match protobuf_action.optional_payload {
Some(OptionalPayload::MiddleClickPayload(payload)) => {
let position = payload.try_into()?;
Ok(Action::MouseEvent {
event: MouseEvent::new_middle_press_event(position),
})
},
_ => Err("Wrong payload for Action::MiddleClick"),
},
Some(ProtobufActionName::LaunchOrFocusPlugin) => {
match protobuf_action.optional_payload {
Some(OptionalPayload::LaunchOrFocusPluginPayload(payload)) => {
let configuration: PluginUserConfiguration = payload
.plugin_configuration
.and_then(|p| PluginUserConfiguration::try_from(p).ok())
.unwrap_or_default();
let run_plugin_or_alias = RunPluginOrAlias::from_url(
&payload.plugin_url.as_str(),
&Some(configuration.inner().clone()),
None,
None,
)
.map_err(|_| "Malformed LaunchOrFocusPlugin payload")?;
let should_float = payload.should_float;
let move_to_focused_tab = payload.move_to_focused_tab;
let should_open_in_place = payload.should_open_in_place;
let skip_plugin_cache = payload.skip_plugin_cache;
Ok(Action::LaunchOrFocusPlugin {
plugin: run_plugin_or_alias,
should_float,
move_to_focused_tab,
should_open_in_place,
skip_cache: skip_plugin_cache,
})
},
_ => Err("Wrong payload for Action::LaunchOrFocusPlugin"),
}
},
Some(ProtobufActionName::LaunchPlugin) => match protobuf_action.optional_payload {
Some(OptionalPayload::LaunchOrFocusPluginPayload(payload)) => {
let configuration: PluginUserConfiguration = payload
.plugin_configuration
.and_then(|p| PluginUserConfiguration::try_from(p).ok())
.unwrap_or_default();
let run_plugin_or_alias = RunPluginOrAlias::from_url(
&payload.plugin_url.as_str(),
&Some(configuration.inner().clone()),
None,
None,
)
.map_err(|_| "Malformed LaunchOrFocusPlugin payload")?;
let should_float = payload.should_float;
let _move_to_focused_tab = payload.move_to_focused_tab; // not actually used in
// this action
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/message.rs | zellij-utils/src/plugin_api/message.rs | pub use super::generated_api::api::message::Message as ProtobufMessage;
use crate::data::PluginMessage;
use std::convert::TryFrom;
impl TryFrom<ProtobufMessage> for PluginMessage {
type Error = &'static str;
fn try_from(protobuf_message: ProtobufMessage) -> Result<Self, &'static str> {
let name = protobuf_message.name;
let payload = protobuf_message.payload;
let worker_name = protobuf_message.worker_name;
Ok(PluginMessage {
name,
payload,
worker_name,
})
}
}
impl TryFrom<PluginMessage> for ProtobufMessage {
type Error = &'static str;
fn try_from(plugin_message: PluginMessage) -> Result<Self, &'static str> {
Ok(ProtobufMessage {
name: plugin_message.name,
payload: plugin_message.payload,
worker_name: plugin_message.worker_name,
})
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/resize.rs | zellij-utils/src/plugin_api/resize.rs | pub use super::generated_api::api::resize::{
MoveDirection as ProtobufMoveDirection, Resize as ProtobufResize, ResizeAction,
ResizeDirection, ResizeDirection as ProtobufResizeDirection,
};
use crate::data::{Direction, Resize, ResizeStrategy};
use std::convert::TryFrom;
impl TryFrom<ProtobufResize> for Resize {
type Error = &'static str;
fn try_from(protobuf_resize: ProtobufResize) -> Result<Self, &'static str> {
if protobuf_resize.direction.is_some() {
return Err("Resize cannot have a direction");
}
match ResizeAction::from_i32(protobuf_resize.resize_action) {
Some(ResizeAction::Increase) => Ok(Resize::Increase),
Some(ResizeAction::Decrease) => Ok(Resize::Decrease),
None => Err("No resize action for the given index"),
}
}
}
impl TryFrom<Resize> for ProtobufResize {
type Error = &'static str;
fn try_from(resize: Resize) -> Result<Self, &'static str> {
Ok(ProtobufResize {
resize_action: match resize {
Resize::Increase => ResizeAction::Increase as i32,
Resize::Decrease => ResizeAction::Decrease as i32,
},
direction: None,
})
}
}
impl TryFrom<ProtobufResize> for ResizeStrategy {
type Error = &'static str;
fn try_from(protobuf_resize: ProtobufResize) -> Result<Self, &'static str> {
let direction = match protobuf_resize
.direction
.and_then(|r| ResizeDirection::from_i32(r))
{
Some(ResizeDirection::Left) => Some(Direction::Left),
Some(ResizeDirection::Right) => Some(Direction::Right),
Some(ResizeDirection::Up) => Some(Direction::Up),
Some(ResizeDirection::Down) => Some(Direction::Down),
None => None,
};
let resize = match ResizeAction::from_i32(protobuf_resize.resize_action) {
Some(ResizeAction::Increase) => Resize::Increase,
Some(ResizeAction::Decrease) => Resize::Decrease,
None => return Err("No resize action for the given index"),
};
Ok(ResizeStrategy {
direction,
resize,
invert_on_boundaries: false,
})
}
}
impl TryFrom<ResizeStrategy> for ProtobufResize {
type Error = &'static str;
fn try_from(resize_strategy: ResizeStrategy) -> Result<Self, &'static str> {
Ok(ProtobufResize {
resize_action: match resize_strategy.resize {
Resize::Increase => ResizeAction::Increase as i32,
Resize::Decrease => ResizeAction::Decrease as i32,
},
direction: match resize_strategy.direction {
Some(Direction::Left) => Some(ResizeDirection::Left as i32),
Some(Direction::Right) => Some(ResizeDirection::Right as i32),
Some(Direction::Up) => Some(ResizeDirection::Up as i32),
Some(Direction::Down) => Some(ResizeDirection::Down as i32),
None => None,
},
})
}
}
impl TryFrom<ProtobufMoveDirection> for Direction {
type Error = &'static str;
fn try_from(protobuf_move_direction: ProtobufMoveDirection) -> Result<Self, &'static str> {
match ResizeDirection::from_i32(protobuf_move_direction.direction) {
Some(ResizeDirection::Left) => Ok(Direction::Left),
Some(ResizeDirection::Right) => Ok(Direction::Right),
Some(ResizeDirection::Up) => Ok(Direction::Up),
Some(ResizeDirection::Down) => Ok(Direction::Down),
None => Err("No direction for the given index"),
}
}
}
impl TryFrom<Direction> for ProtobufMoveDirection {
type Error = &'static str;
fn try_from(direction: Direction) -> Result<Self, &'static str> {
Ok(ProtobufMoveDirection {
direction: match direction {
Direction::Left => ResizeDirection::Left as i32,
Direction::Right => ResizeDirection::Right as i32,
Direction::Up => ResizeDirection::Up as i32,
Direction::Down => ResizeDirection::Down as i32,
},
})
}
}
impl TryFrom<ProtobufResizeDirection> for Direction {
type Error = &'static str;
fn try_from(protobuf_resize_direction: ProtobufResizeDirection) -> Result<Self, &'static str> {
match protobuf_resize_direction {
ProtobufResizeDirection::Left => Ok(Direction::Left),
ProtobufResizeDirection::Right => Ok(Direction::Right),
ProtobufResizeDirection::Up => Ok(Direction::Up),
ProtobufResizeDirection::Down => Ok(Direction::Down),
}
}
}
impl TryFrom<Direction> for ProtobufResizeDirection {
type Error = &'static str;
fn try_from(direction: Direction) -> Result<Self, &'static str> {
Ok(match direction {
Direction::Left => ProtobufResizeDirection::Left,
Direction::Right => ProtobufResizeDirection::Right,
Direction::Up => ProtobufResizeDirection::Up,
Direction::Down => ProtobufResizeDirection::Down,
})
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/plugin_api/plugin_permission.rs | zellij-utils/src/plugin_api/plugin_permission.rs | pub use super::generated_api::api::plugin_permission::PermissionType as ProtobufPermissionType;
use crate::data::PermissionType;
use std::convert::TryFrom;
impl TryFrom<ProtobufPermissionType> for PermissionType {
type Error = &'static str;
fn try_from(protobuf_permission: ProtobufPermissionType) -> Result<Self, &'static str> {
match protobuf_permission {
ProtobufPermissionType::ReadApplicationState => {
Ok(PermissionType::ReadApplicationState)
},
ProtobufPermissionType::ChangeApplicationState => {
Ok(PermissionType::ChangeApplicationState)
},
ProtobufPermissionType::OpenFiles => Ok(PermissionType::OpenFiles),
ProtobufPermissionType::RunCommands => Ok(PermissionType::RunCommands),
ProtobufPermissionType::OpenTerminalsOrPlugins => {
Ok(PermissionType::OpenTerminalsOrPlugins)
},
ProtobufPermissionType::WriteToStdin => Ok(PermissionType::WriteToStdin),
ProtobufPermissionType::WebAccess => Ok(PermissionType::WebAccess),
ProtobufPermissionType::ReadCliPipes => Ok(PermissionType::ReadCliPipes),
ProtobufPermissionType::MessageAndLaunchOtherPlugins => {
Ok(PermissionType::MessageAndLaunchOtherPlugins)
},
ProtobufPermissionType::Reconfigure => Ok(PermissionType::Reconfigure),
ProtobufPermissionType::FullHdAccess => Ok(PermissionType::FullHdAccess),
ProtobufPermissionType::StartWebServer => Ok(PermissionType::StartWebServer),
ProtobufPermissionType::InterceptInput => Ok(PermissionType::InterceptInput),
ProtobufPermissionType::ReadPaneContents => Ok(PermissionType::ReadPaneContents),
ProtobufPermissionType::RunActionsAsUser => Ok(PermissionType::RunActionsAsUser),
ProtobufPermissionType::WriteToClipboard => Ok(PermissionType::WriteToClipboard),
}
}
}
impl TryFrom<PermissionType> for ProtobufPermissionType {
type Error = &'static str;
fn try_from(permission: PermissionType) -> Result<Self, &'static str> {
match permission {
PermissionType::ReadApplicationState => {
Ok(ProtobufPermissionType::ReadApplicationState)
},
PermissionType::ChangeApplicationState => {
Ok(ProtobufPermissionType::ChangeApplicationState)
},
PermissionType::OpenFiles => Ok(ProtobufPermissionType::OpenFiles),
PermissionType::RunCommands => Ok(ProtobufPermissionType::RunCommands),
PermissionType::OpenTerminalsOrPlugins => {
Ok(ProtobufPermissionType::OpenTerminalsOrPlugins)
},
PermissionType::WriteToStdin => Ok(ProtobufPermissionType::WriteToStdin),
PermissionType::WebAccess => Ok(ProtobufPermissionType::WebAccess),
PermissionType::ReadCliPipes => Ok(ProtobufPermissionType::ReadCliPipes),
PermissionType::MessageAndLaunchOtherPlugins => {
Ok(ProtobufPermissionType::MessageAndLaunchOtherPlugins)
},
PermissionType::Reconfigure => Ok(ProtobufPermissionType::Reconfigure),
PermissionType::FullHdAccess => Ok(ProtobufPermissionType::FullHdAccess),
PermissionType::StartWebServer => Ok(ProtobufPermissionType::StartWebServer),
PermissionType::InterceptInput => Ok(ProtobufPermissionType::InterceptInput),
PermissionType::ReadPaneContents => Ok(ProtobufPermissionType::ReadPaneContents),
PermissionType::RunActionsAsUser => Ok(ProtobufPermissionType::RunActionsAsUser),
PermissionType::WriteToClipboard => Ok(ProtobufPermissionType::WriteToClipboard),
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/client_server_contract/mod.rs | zellij-utils/src/client_server_contract/mod.rs | include!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/assets/prost_ipc/generated_client_server_api.rs"
));
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/ipc/enum_conversions.rs | zellij-utils/src/ipc/enum_conversions.rs | use crate::{
client_server_contract::client_server_contract::{
BareKey as ProtoBareKey, KeyModifier as ProtoKeyModifier,
},
data::{BareKey, KeyModifier},
errors::prelude::*,
};
// BareKey conversions
impl From<BareKey> for ProtoBareKey {
fn from(key: BareKey) -> Self {
match key {
BareKey::PageDown => ProtoBareKey::PageDown,
BareKey::PageUp => ProtoBareKey::PageUp,
BareKey::Left => ProtoBareKey::Left,
BareKey::Down => ProtoBareKey::Down,
BareKey::Up => ProtoBareKey::Up,
BareKey::Right => ProtoBareKey::Right,
BareKey::Home => ProtoBareKey::Home,
BareKey::End => ProtoBareKey::End,
BareKey::Backspace => ProtoBareKey::Backspace,
BareKey::Delete => ProtoBareKey::Delete,
BareKey::Insert => ProtoBareKey::Insert,
BareKey::F(1) => ProtoBareKey::F1,
BareKey::F(2) => ProtoBareKey::F2,
BareKey::F(3) => ProtoBareKey::F3,
BareKey::F(4) => ProtoBareKey::F4,
BareKey::F(5) => ProtoBareKey::F5,
BareKey::F(6) => ProtoBareKey::F6,
BareKey::F(7) => ProtoBareKey::F7,
BareKey::F(8) => ProtoBareKey::F8,
BareKey::F(9) => ProtoBareKey::F9,
BareKey::F(10) => ProtoBareKey::F10,
BareKey::F(11) => ProtoBareKey::F11,
BareKey::F(12) => ProtoBareKey::F12,
BareKey::F(_) => ProtoBareKey::Unspecified, // Unsupported F-key
BareKey::Char(_) => ProtoBareKey::Char, // Character stored separately
BareKey::Tab => ProtoBareKey::Tab,
BareKey::Esc => ProtoBareKey::Esc,
BareKey::Enter => ProtoBareKey::Enter,
BareKey::CapsLock => ProtoBareKey::CapsLock,
BareKey::ScrollLock => ProtoBareKey::ScrollLock,
BareKey::NumLock => ProtoBareKey::NumLock,
BareKey::PrintScreen => ProtoBareKey::PrintScreen,
BareKey::Pause => ProtoBareKey::Pause,
BareKey::Menu => ProtoBareKey::Menu,
}
}
}
impl TryFrom<ProtoBareKey> for BareKey {
type Error = anyhow::Error;
fn try_from(key: ProtoBareKey) -> Result<Self> {
match key {
ProtoBareKey::PageDown => Ok(BareKey::PageDown),
ProtoBareKey::PageUp => Ok(BareKey::PageUp),
ProtoBareKey::Left => Ok(BareKey::Left),
ProtoBareKey::Down => Ok(BareKey::Down),
ProtoBareKey::Up => Ok(BareKey::Up),
ProtoBareKey::Right => Ok(BareKey::Right),
ProtoBareKey::Home => Ok(BareKey::Home),
ProtoBareKey::End => Ok(BareKey::End),
ProtoBareKey::Backspace => Ok(BareKey::Backspace),
ProtoBareKey::Delete => Ok(BareKey::Delete),
ProtoBareKey::Insert => Ok(BareKey::Insert),
ProtoBareKey::F1 => Ok(BareKey::F(1)),
ProtoBareKey::F2 => Ok(BareKey::F(2)),
ProtoBareKey::F3 => Ok(BareKey::F(3)),
ProtoBareKey::F4 => Ok(BareKey::F(4)),
ProtoBareKey::F5 => Ok(BareKey::F(5)),
ProtoBareKey::F6 => Ok(BareKey::F(6)),
ProtoBareKey::F7 => Ok(BareKey::F(7)),
ProtoBareKey::F8 => Ok(BareKey::F(8)),
ProtoBareKey::F9 => Ok(BareKey::F(9)),
ProtoBareKey::F10 => Ok(BareKey::F(10)),
ProtoBareKey::F11 => Ok(BareKey::F(11)),
ProtoBareKey::F12 => Ok(BareKey::F(12)),
ProtoBareKey::Char => Err(anyhow!("Character key needs character data")),
ProtoBareKey::Tab => Ok(BareKey::Tab),
ProtoBareKey::Esc => Ok(BareKey::Esc),
ProtoBareKey::Enter => Ok(BareKey::Enter),
ProtoBareKey::CapsLock => Ok(BareKey::CapsLock),
ProtoBareKey::ScrollLock => Ok(BareKey::ScrollLock),
ProtoBareKey::NumLock => Ok(BareKey::NumLock),
ProtoBareKey::PrintScreen => Ok(BareKey::PrintScreen),
ProtoBareKey::Pause => Ok(BareKey::Pause),
ProtoBareKey::Menu => Ok(BareKey::Menu),
ProtoBareKey::Unspecified => Err(anyhow!("Unspecified bare key")),
}
}
}
// KeyModifier conversions
impl From<KeyModifier> for ProtoKeyModifier {
fn from(modifier: KeyModifier) -> Self {
match modifier {
KeyModifier::Ctrl => ProtoKeyModifier::Ctrl,
KeyModifier::Alt => ProtoKeyModifier::Alt,
KeyModifier::Shift => ProtoKeyModifier::Shift,
KeyModifier::Super => ProtoKeyModifier::Super,
}
}
}
impl TryFrom<ProtoKeyModifier> for KeyModifier {
type Error = anyhow::Error;
fn try_from(modifier: ProtoKeyModifier) -> Result<Self> {
match modifier {
ProtoKeyModifier::Ctrl => Ok(KeyModifier::Ctrl),
ProtoKeyModifier::Alt => Ok(KeyModifier::Alt),
ProtoKeyModifier::Shift => Ok(KeyModifier::Shift),
ProtoKeyModifier::Super => Ok(KeyModifier::Super),
ProtoKeyModifier::Unspecified => Err(anyhow!("Unspecified key modifier")),
}
}
}
// Helper functions for converting between protobuf i32 and enum types
pub fn bare_key_to_proto_i32(key: BareKey) -> i32 {
ProtoBareKey::from(key) as i32
}
pub fn bare_key_from_proto_i32(value: i32) -> Result<BareKey> {
let proto_key =
ProtoBareKey::from_i32(value).ok_or_else(|| anyhow!("Invalid BareKey value: {}", value))?;
proto_key.try_into()
}
pub fn key_modifier_to_proto_i32(modifier: KeyModifier) -> i32 {
ProtoKeyModifier::from(modifier) as i32
}
pub fn key_modifier_from_proto_i32(value: i32) -> Result<KeyModifier> {
let proto_modifier = ProtoKeyModifier::from_i32(value)
.ok_or_else(|| anyhow!("Invalid KeyModifier value: {}", value))?;
proto_modifier.try_into()
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/ipc/protobuf_conversion.rs | zellij-utils/src/ipc/protobuf_conversion.rs | use crate::{
client_server_contract::client_server_contract::{
client_to_server_msg, server_to_client_msg, ActionMsg, AttachClientMsg,
AttachWatcherClientMsg, BackgroundColorMsg, CliPipeOutputMsg, ClientExitedMsg,
ClientToServerMsg as ProtoClientToServerMsg, ColorRegistersMsg, ConfigFileUpdatedMsg,
ConnStatusMsg, ConnectedMsg, DetachSessionMsg, ExitMsg, ExitReason as ProtoExitReason,
FailedToStartWebServerMsg, FirstClientConnectedMsg, ForegroundColorMsg,
InputMode as ProtoInputMode, KeyMsg, KillSessionMsg, LogErrorMsg, LogMsg,
QueryTerminalSizeMsg, RenamedSessionMsg, RenderMsg,
ServerToClientMsg as ProtoServerToClientMsg, StartWebServerMsg, SwitchSessionMsg,
TerminalPixelDimensionsMsg, TerminalResizeMsg, UnblockCliPipeInputMsg,
UnblockInputThreadMsg, WebServerStartedMsg,
},
data::InputMode,
errors::prelude::*,
ipc::{
ClientToServerMsg, ColorRegister, ExitReason, PaneReference, PixelDimensions,
ServerToClientMsg,
},
};
use std::collections::BTreeMap;
use std::path::PathBuf;
// Convert Rust ClientToServerMsg to protobuf
impl From<ClientToServerMsg> for ProtoClientToServerMsg {
fn from(msg: ClientToServerMsg) -> Self {
let message = match msg {
ClientToServerMsg::DetachSession { client_ids } => {
client_to_server_msg::Message::DetachSession(DetachSessionMsg {
client_ids: client_ids.into_iter().map(|id| id as u32).collect(),
})
},
ClientToServerMsg::TerminalPixelDimensions { pixel_dimensions } => {
client_to_server_msg::Message::TerminalPixelDimensions(TerminalPixelDimensionsMsg {
pixel_dimensions: Some(pixel_dimensions.into()),
})
},
ClientToServerMsg::BackgroundColor { color } => {
client_to_server_msg::Message::BackgroundColor(BackgroundColorMsg { color })
},
ClientToServerMsg::ForegroundColor { color } => {
client_to_server_msg::Message::ForegroundColor(ForegroundColorMsg { color })
},
ClientToServerMsg::ColorRegisters { color_registers } => {
client_to_server_msg::Message::ColorRegisters(ColorRegistersMsg {
color_registers: color_registers.into_iter().map(|cr| cr.into()).collect(),
})
},
ClientToServerMsg::TerminalResize { new_size } => {
client_to_server_msg::Message::TerminalResize(TerminalResizeMsg {
new_size: Some(new_size.into()),
})
},
ClientToServerMsg::FirstClientConnected {
cli_assets,
is_web_client,
} => client_to_server_msg::Message::FirstClientConnected(FirstClientConnectedMsg {
cli_assets: Some(cli_assets.into()),
is_web_client,
}),
ClientToServerMsg::AttachClient {
cli_assets,
tab_position_to_focus,
pane_to_focus,
is_web_client,
} => client_to_server_msg::Message::AttachClient(AttachClientMsg {
cli_assets: Some(cli_assets.into()),
tab_position_to_focus: tab_position_to_focus.map(|pos| pos as u32),
pane_to_focus: pane_to_focus.map(|p| p.into()),
is_web_client,
}),
ClientToServerMsg::AttachWatcherClient {
terminal_size,
is_web_client,
} => client_to_server_msg::Message::AttachWatcherClient(AttachWatcherClientMsg {
terminal_size: Some(terminal_size.into()),
is_web_client,
}),
ClientToServerMsg::Action {
action,
terminal_id,
client_id,
is_cli_client,
} => client_to_server_msg::Message::Action(ActionMsg {
action: Some(action.into()),
terminal_id,
client_id: client_id.map(|id| id as u32),
is_cli_client,
}),
ClientToServerMsg::Key {
key,
raw_bytes,
is_kitty_keyboard_protocol,
} => client_to_server_msg::Message::Key(KeyMsg {
key: Some(key.into()),
raw_bytes: raw_bytes.into_iter().map(|b| b as u32).collect(),
is_kitty_keyboard_protocol,
}),
ClientToServerMsg::ClientExited => {
client_to_server_msg::Message::ClientExited(ClientExitedMsg {})
},
ClientToServerMsg::KillSession => {
client_to_server_msg::Message::KillSession(KillSessionMsg {})
},
ClientToServerMsg::ConnStatus => {
client_to_server_msg::Message::ConnStatus(ConnStatusMsg {})
},
ClientToServerMsg::WebServerStarted { base_url } => {
client_to_server_msg::Message::WebServerStarted(WebServerStartedMsg { base_url })
},
ClientToServerMsg::FailedToStartWebServer { error } => {
client_to_server_msg::Message::FailedToStartWebServer(FailedToStartWebServerMsg {
error,
})
},
};
ProtoClientToServerMsg {
message: Some(message),
}
}
}
// Convert protobuf ClientToServerMsg to Rust
impl TryFrom<ProtoClientToServerMsg> for ClientToServerMsg {
type Error = anyhow::Error;
fn try_from(msg: ProtoClientToServerMsg) -> Result<Self> {
match msg.message {
Some(client_to_server_msg::Message::DetachSession(detach)) => {
Ok(ClientToServerMsg::DetachSession {
client_ids: detach.client_ids.into_iter().map(|id| id as u16).collect(),
})
},
Some(client_to_server_msg::Message::TerminalPixelDimensions(pixel_dims)) => {
Ok(ClientToServerMsg::TerminalPixelDimensions {
pixel_dimensions: pixel_dims
.pixel_dimensions
.ok_or_else(|| anyhow!("Missing pixel_dimensions"))?
.try_into()?,
})
},
Some(client_to_server_msg::Message::BackgroundColor(bg_color)) => {
Ok(ClientToServerMsg::BackgroundColor {
color: bg_color.color,
})
},
Some(client_to_server_msg::Message::ForegroundColor(fg_color)) => {
Ok(ClientToServerMsg::ForegroundColor {
color: fg_color.color,
})
},
Some(client_to_server_msg::Message::ColorRegisters(color_regs)) => {
Ok(ClientToServerMsg::ColorRegisters {
color_registers: color_regs
.color_registers
.into_iter()
.map(|cr| cr.try_into())
.collect::<Result<Vec<_>>>()?,
})
},
Some(client_to_server_msg::Message::TerminalResize(resize)) => {
Ok(ClientToServerMsg::TerminalResize {
new_size: resize
.new_size
.ok_or_else(|| anyhow!("Missing new_size"))?
.try_into()?,
})
},
Some(client_to_server_msg::Message::FirstClientConnected(first_client)) => {
Ok(ClientToServerMsg::FirstClientConnected {
cli_assets: first_client
.cli_assets
.ok_or_else(|| anyhow!("Missing cli_assets"))?
.try_into()?,
is_web_client: first_client.is_web_client,
})
},
Some(client_to_server_msg::Message::AttachClient(attach)) => {
Ok(ClientToServerMsg::AttachClient {
cli_assets: attach
.cli_assets
.ok_or_else(|| anyhow!("Missing cli_assets"))?
.try_into()?,
tab_position_to_focus: attach.tab_position_to_focus.map(|pos| pos as usize),
pane_to_focus: attach.pane_to_focus.map(|p| p.try_into()).transpose()?,
is_web_client: attach.is_web_client,
})
},
Some(client_to_server_msg::Message::AttachWatcherClient(attach_watcher)) => {
Ok(ClientToServerMsg::AttachWatcherClient {
terminal_size: attach_watcher
.terminal_size
.ok_or_else(|| anyhow::anyhow!("Missing terminal_size"))?
.try_into()?,
is_web_client: attach_watcher.is_web_client,
})
},
Some(client_to_server_msg::Message::Action(action)) => Ok(ClientToServerMsg::Action {
action: action
.action
.ok_or_else(|| anyhow!("Missing action"))?
.try_into()?,
terminal_id: action.terminal_id,
client_id: action.client_id.map(|id| id as u16),
is_cli_client: action.is_cli_client,
}),
Some(client_to_server_msg::Message::Key(key)) => Ok(ClientToServerMsg::Key {
key: key.key.ok_or_else(|| anyhow!("Missing key"))?.try_into()?,
raw_bytes: key.raw_bytes.into_iter().map(|b| b as u8).collect(),
is_kitty_keyboard_protocol: key.is_kitty_keyboard_protocol,
}),
Some(client_to_server_msg::Message::ClientExited(_)) => {
Ok(ClientToServerMsg::ClientExited)
},
Some(client_to_server_msg::Message::KillSession(_)) => {
Ok(ClientToServerMsg::KillSession)
},
Some(client_to_server_msg::Message::ConnStatus(_)) => Ok(ClientToServerMsg::ConnStatus),
Some(client_to_server_msg::Message::WebServerStarted(web_server)) => {
Ok(ClientToServerMsg::WebServerStarted {
base_url: web_server.base_url,
})
},
Some(client_to_server_msg::Message::FailedToStartWebServer(failed)) => {
Ok(ClientToServerMsg::FailedToStartWebServer {
error: failed.error,
})
},
None => Err(anyhow!("Empty ClientToServerMsg message")),
}
}
}
// Convert Rust ServerToClientMsg to protobuf
impl From<ServerToClientMsg> for ProtoServerToClientMsg {
fn from(msg: ServerToClientMsg) -> Self {
let message = match msg {
ServerToClientMsg::Render { content } => {
server_to_client_msg::Message::Render(RenderMsg { content })
},
ServerToClientMsg::UnblockInputThread => {
server_to_client_msg::Message::UnblockInputThread(UnblockInputThreadMsg {})
},
ServerToClientMsg::Exit { exit_reason } => {
let (proto_exit_reason, payload) = match exit_reason {
ExitReason::Error(ref msg) => (ProtoExitReason::Error, Some(msg.clone())),
ExitReason::CustomExitStatus(status) => {
(ProtoExitReason::CustomExitStatus, Some(status.to_string()))
},
other => (ProtoExitReason::from(other), None),
};
server_to_client_msg::Message::Exit(ExitMsg {
exit_reason: proto_exit_reason as i32,
payload,
})
},
ServerToClientMsg::Connected => {
server_to_client_msg::Message::Connected(ConnectedMsg {})
},
ServerToClientMsg::Log { lines } => {
server_to_client_msg::Message::Log(LogMsg { lines })
},
ServerToClientMsg::LogError { lines } => {
server_to_client_msg::Message::LogError(LogErrorMsg { lines })
},
ServerToClientMsg::SwitchSession { connect_to_session } => {
server_to_client_msg::Message::SwitchSession(SwitchSessionMsg {
connect_to_session: Some(connect_to_session.into()),
})
},
ServerToClientMsg::UnblockCliPipeInput { pipe_name } => {
server_to_client_msg::Message::UnblockCliPipeInput(UnblockCliPipeInputMsg {
pipe_name,
})
},
ServerToClientMsg::CliPipeOutput { pipe_name, output } => {
server_to_client_msg::Message::CliPipeOutput(CliPipeOutputMsg { pipe_name, output })
},
ServerToClientMsg::QueryTerminalSize => {
server_to_client_msg::Message::QueryTerminalSize(QueryTerminalSizeMsg {})
},
ServerToClientMsg::StartWebServer => {
server_to_client_msg::Message::StartWebServer(StartWebServerMsg {})
},
ServerToClientMsg::RenamedSession { name } => {
server_to_client_msg::Message::RenamedSession(RenamedSessionMsg { name })
},
ServerToClientMsg::ConfigFileUpdated => {
server_to_client_msg::Message::ConfigFileUpdated(ConfigFileUpdatedMsg {})
},
};
ProtoServerToClientMsg {
message: Some(message),
}
}
}
// Convert protobuf ServerToClientMsg to Rust
impl TryFrom<ProtoServerToClientMsg> for ServerToClientMsg {
type Error = anyhow::Error;
fn try_from(msg: ProtoServerToClientMsg) -> Result<Self> {
match msg.message {
Some(server_to_client_msg::Message::Render(render)) => Ok(ServerToClientMsg::Render {
content: render.content,
}),
Some(server_to_client_msg::Message::UnblockInputThread(_)) => {
Ok(ServerToClientMsg::UnblockInputThread)
},
Some(server_to_client_msg::Message::Exit(exit)) => {
let proto_exit_reason = ProtoExitReason::from_i32(exit.exit_reason)
.ok_or_else(|| anyhow!("Invalid exit_reason"))?;
let exit_reason = match proto_exit_reason {
ProtoExitReason::Error => {
let error_msg =
exit.payload.unwrap_or_else(|| "Protobuf error".to_string());
ExitReason::Error(error_msg)
},
ProtoExitReason::CustomExitStatus => {
let status_str = exit.payload.unwrap_or_else(|| "0".to_string());
let status = status_str
.parse::<i32>()
.map_err(|_| anyhow!("Invalid custom exit status: {}", status_str))?;
ExitReason::CustomExitStatus(status)
},
other => other.try_into()?,
};
Ok(ServerToClientMsg::Exit { exit_reason })
},
Some(server_to_client_msg::Message::Connected(_)) => Ok(ServerToClientMsg::Connected),
Some(server_to_client_msg::Message::Log(log)) => {
Ok(ServerToClientMsg::Log { lines: log.lines })
},
Some(server_to_client_msg::Message::LogError(log_error)) => {
Ok(ServerToClientMsg::LogError {
lines: log_error.lines,
})
},
Some(server_to_client_msg::Message::SwitchSession(switch)) => {
Ok(ServerToClientMsg::SwitchSession {
connect_to_session: switch
.connect_to_session
.ok_or_else(|| anyhow!("Missing connect_to_session"))?
.try_into()?,
})
},
Some(server_to_client_msg::Message::UnblockCliPipeInput(unblock)) => {
Ok(ServerToClientMsg::UnblockCliPipeInput {
pipe_name: unblock.pipe_name,
})
},
Some(server_to_client_msg::Message::CliPipeOutput(pipe_output)) => {
Ok(ServerToClientMsg::CliPipeOutput {
pipe_name: pipe_output.pipe_name,
output: pipe_output.output,
})
},
Some(server_to_client_msg::Message::QueryTerminalSize(_)) => {
Ok(ServerToClientMsg::QueryTerminalSize)
},
Some(server_to_client_msg::Message::StartWebServer(_)) => {
Ok(ServerToClientMsg::StartWebServer)
},
Some(server_to_client_msg::Message::RenamedSession(renamed)) => {
Ok(ServerToClientMsg::RenamedSession { name: renamed.name })
},
Some(server_to_client_msg::Message::ConfigFileUpdated(_)) => {
Ok(ServerToClientMsg::ConfigFileUpdated)
},
None => Err(anyhow!("Empty ServerToClientMsg message")),
}
}
}
// Basic type conversions
impl From<crate::pane_size::Size> for crate::client_server_contract::client_server_contract::Size {
fn from(size: crate::pane_size::Size) -> Self {
Self {
cols: size.cols as u32,
rows: size.rows as u32,
}
}
}
impl TryFrom<crate::client_server_contract::client_server_contract::Size>
for crate::pane_size::Size
{
type Error = anyhow::Error;
fn try_from(size: crate::client_server_contract::client_server_contract::Size) -> Result<Self> {
Ok(Self {
rows: size.rows as usize,
cols: size.cols as usize,
})
}
}
impl From<PixelDimensions>
for crate::client_server_contract::client_server_contract::PixelDimensions
{
fn from(pixel_dims: PixelDimensions) -> Self {
Self {
text_area_size: pixel_dims.text_area_size.map(|size| {
crate::client_server_contract::client_server_contract::SizeInPixels {
width: size.width as u32,
height: size.height as u32,
}
}),
character_cell_size: pixel_dims.character_cell_size.map(|size| {
crate::client_server_contract::client_server_contract::SizeInPixels {
width: size.width as u32,
height: size.height as u32,
}
}),
}
}
}
impl TryFrom<crate::client_server_contract::client_server_contract::PixelDimensions>
for PixelDimensions
{
type Error = anyhow::Error;
fn try_from(
pixel_dims: crate::client_server_contract::client_server_contract::PixelDimensions,
) -> Result<Self> {
Ok(Self {
text_area_size: pixel_dims
.text_area_size
.map(|size| crate::pane_size::SizeInPixels {
width: size.width as usize,
height: size.height as usize,
}),
character_cell_size: pixel_dims.character_cell_size.map(|size| {
crate::pane_size::SizeInPixels {
width: size.width as usize,
height: size.height as usize,
}
}),
})
}
}
impl From<PaneReference> for crate::client_server_contract::client_server_contract::PaneReference {
fn from(pane_ref: PaneReference) -> Self {
Self {
pane_id: pane_ref.pane_id,
is_plugin: pane_ref.is_plugin,
}
}
}
impl TryFrom<crate::client_server_contract::client_server_contract::PaneReference>
for PaneReference
{
type Error = anyhow::Error;
fn try_from(
pane_ref: crate::client_server_contract::client_server_contract::PaneReference,
) -> Result<Self> {
Ok(Self {
pane_id: pane_ref.pane_id,
is_plugin: pane_ref.is_plugin,
})
}
}
impl From<ColorRegister> for crate::client_server_contract::client_server_contract::ColorRegister {
fn from(color_reg: ColorRegister) -> Self {
Self {
index: color_reg.index as u32,
color: color_reg.color,
}
}
}
impl TryFrom<crate::client_server_contract::client_server_contract::ColorRegister>
for ColorRegister
{
type Error = anyhow::Error;
fn try_from(
color_reg: crate::client_server_contract::client_server_contract::ColorRegister,
) -> Result<Self> {
Ok(Self {
index: color_reg.index as usize,
color: color_reg.color,
})
}
}
impl From<crate::input::cli_assets::CliAssets>
for crate::client_server_contract::client_server_contract::CliAssets
{
fn from(cli_assets: crate::input::cli_assets::CliAssets) -> Self {
Self {
config_file_path: cli_assets
.config_file_path
.map(|p| p.to_string_lossy().to_string()),
config_dir: cli_assets
.config_dir
.map(|p| p.to_string_lossy().to_string()),
should_ignore_config: cli_assets.should_ignore_config,
configuration_options: cli_assets.configuration_options.map(|o| o.into()),
layout: cli_assets.layout.map(|l| l.into()),
terminal_window_size: Some(cli_assets.terminal_window_size.into()),
data_dir: cli_assets.data_dir.map(|p| p.to_string_lossy().to_string()),
is_debug: cli_assets.is_debug,
max_panes: cli_assets.max_panes.map(|m| m as u32),
force_run_layout_commands: cli_assets.force_run_layout_commands,
cwd: cli_assets.cwd.map(|p| p.to_string_lossy().to_string()),
}
}
}
impl TryFrom<crate::client_server_contract::client_server_contract::CliAssets>
for crate::input::cli_assets::CliAssets
{
type Error = anyhow::Error;
fn try_from(
cli_assets: crate::client_server_contract::client_server_contract::CliAssets,
) -> Result<Self> {
Ok(Self {
config_file_path: cli_assets.config_file_path.map(PathBuf::from),
config_dir: cli_assets.config_dir.map(PathBuf::from),
should_ignore_config: cli_assets.should_ignore_config,
configuration_options: cli_assets
.configuration_options
.map(|o| o.try_into())
.transpose()?,
layout: cli_assets.layout.map(|l| l.try_into()).transpose()?,
terminal_window_size: cli_assets
.terminal_window_size
.ok_or_else(|| anyhow!("CliAssets missing terminal_window_size"))?
.try_into()?,
data_dir: cli_assets.data_dir.map(PathBuf::from),
is_debug: cli_assets.is_debug,
max_panes: cli_assets.max_panes.map(|m| m as usize),
force_run_layout_commands: cli_assets.force_run_layout_commands,
cwd: cli_assets.cwd.map(PathBuf::from),
})
}
}
impl From<crate::input::options::Options>
for crate::client_server_contract::client_server_contract::Options
{
fn from(options: crate::input::options::Options) -> Self {
use crate::client_server_contract::client_server_contract::{
Clipboard as ProtoClipboard, OnForceClose as ProtoOnForceClose,
WebSharing as ProtoWebSharing,
};
Self {
simplified_ui: options.simplified_ui,
theme: options.theme,
default_mode: options.default_mode.map(|m| input_mode_to_proto_i32(m)),
default_shell: options
.default_shell
.map(|p| p.to_string_lossy().to_string()),
default_cwd: options.default_cwd.map(|p| p.to_string_lossy().to_string()),
default_layout: options
.default_layout
.map(|p| p.to_string_lossy().to_string()),
layout_dir: options.layout_dir.map(|p| p.to_string_lossy().to_string()),
theme_dir: options.theme_dir.map(|p| p.to_string_lossy().to_string()),
mouse_mode: options.mouse_mode,
pane_frames: options.pane_frames,
mirror_session: options.mirror_session,
on_force_close: options.on_force_close.map(|o| match o {
crate::input::options::OnForceClose::Quit => ProtoOnForceClose::Quit as i32,
crate::input::options::OnForceClose::Detach => ProtoOnForceClose::Detach as i32,
}),
scroll_buffer_size: options.scroll_buffer_size.map(|s| s as u32),
copy_command: options.copy_command,
copy_clipboard: options.copy_clipboard.map(|c| match c {
crate::input::options::Clipboard::System => ProtoClipboard::System as i32,
crate::input::options::Clipboard::Primary => ProtoClipboard::Primary as i32,
}),
copy_on_select: options.copy_on_select,
scrollback_editor: options
.scrollback_editor
.map(|p| p.to_string_lossy().to_string()),
session_name: options.session_name,
attach_to_session: options.attach_to_session,
auto_layout: options.auto_layout,
session_serialization: options.session_serialization,
serialize_pane_viewport: options.serialize_pane_viewport,
scrollback_lines_to_serialize: options.scrollback_lines_to_serialize.map(|s| s as u32),
styled_underlines: options.styled_underlines,
serialization_interval: options.serialization_interval,
disable_session_metadata: options.disable_session_metadata,
support_kitty_keyboard_protocol: options.support_kitty_keyboard_protocol,
web_server: options.web_server,
web_sharing: options.web_sharing.map(|w| match w {
crate::data::WebSharing::On => ProtoWebSharing::On as i32,
crate::data::WebSharing::Off => ProtoWebSharing::Off as i32,
crate::data::WebSharing::Disabled => ProtoWebSharing::Disabled as i32,
}),
stacked_resize: options.stacked_resize,
show_startup_tips: options.show_startup_tips,
show_release_notes: options.show_release_notes,
advanced_mouse_actions: options.advanced_mouse_actions,
web_server_ip: options.web_server_ip.map(|ip| ip.to_string()),
web_server_port: options.web_server_port.map(|p| p as u32),
web_server_cert: options
.web_server_cert
.map(|p| p.to_string_lossy().to_string()),
web_server_key: options
.web_server_key
.map(|p| p.to_string_lossy().to_string()),
enforce_https_for_localhost: options.enforce_https_for_localhost,
post_command_discovery_hook: options.post_command_discovery_hook,
}
}
}
impl TryFrom<crate::client_server_contract::client_server_contract::Options>
for crate::input::options::Options
{
type Error = anyhow::Error;
fn try_from(
options: crate::client_server_contract::client_server_contract::Options,
) -> Result<Self> {
use crate::client_server_contract::client_server_contract::{
Clipboard as ProtoClipboard, OnForceClose as ProtoOnForceClose,
WebSharing as ProtoWebSharing,
};
Ok(Self {
simplified_ui: options.simplified_ui,
theme: options.theme,
default_mode: options
.default_mode
.map(|m| proto_i32_to_input_mode(m))
.transpose()?,
default_shell: options.default_shell.map(std::path::PathBuf::from),
default_cwd: options.default_cwd.map(std::path::PathBuf::from),
default_layout: options.default_layout.map(std::path::PathBuf::from),
layout_dir: options.layout_dir.map(std::path::PathBuf::from),
theme_dir: options.theme_dir.map(std::path::PathBuf::from),
mouse_mode: options.mouse_mode,
pane_frames: options.pane_frames,
mirror_session: options.mirror_session,
on_force_close: options
.on_force_close
.map(|o| match ProtoOnForceClose::from_i32(o) {
Some(ProtoOnForceClose::Quit) => Ok(crate::input::options::OnForceClose::Quit),
Some(ProtoOnForceClose::Detach) => {
Ok(crate::input::options::OnForceClose::Detach)
},
_ => Err(anyhow!("Invalid OnForceClose value: {}", o)),
})
.transpose()?,
scroll_buffer_size: options.scroll_buffer_size.map(|s| s as usize),
copy_command: options.copy_command,
copy_clipboard: options
.copy_clipboard
.map(|c| match ProtoClipboard::from_i32(c) {
Some(ProtoClipboard::System) => Ok(crate::input::options::Clipboard::System),
Some(ProtoClipboard::Primary) => Ok(crate::input::options::Clipboard::Primary),
_ => Err(anyhow!("Invalid Clipboard value: {}", c)),
})
.transpose()?,
copy_on_select: options.copy_on_select,
scrollback_editor: options.scrollback_editor.map(std::path::PathBuf::from),
session_name: options.session_name,
attach_to_session: options.attach_to_session,
auto_layout: options.auto_layout,
session_serialization: options.session_serialization,
serialize_pane_viewport: options.serialize_pane_viewport,
scrollback_lines_to_serialize: options
.scrollback_lines_to_serialize
.map(|s| s as usize),
styled_underlines: options.styled_underlines,
serialization_interval: options.serialization_interval,
disable_session_metadata: options.disable_session_metadata,
support_kitty_keyboard_protocol: options.support_kitty_keyboard_protocol,
web_server: options.web_server,
web_sharing: options
.web_sharing
.map(|w| match ProtoWebSharing::from_i32(w) {
Some(ProtoWebSharing::On) => Ok(crate::data::WebSharing::On),
Some(ProtoWebSharing::Off) => Ok(crate::data::WebSharing::Off),
Some(ProtoWebSharing::Disabled) => Ok(crate::data::WebSharing::Disabled),
_ => Err(anyhow!("Invalid WebSharing value: {}", w)),
})
.transpose()?,
stacked_resize: options.stacked_resize,
show_startup_tips: options.show_startup_tips,
show_release_notes: options.show_release_notes,
advanced_mouse_actions: options.advanced_mouse_actions,
web_server_ip: options
.web_server_ip
.map(|ip| ip.parse())
.transpose()
.map_err(|e| anyhow!("Invalid IP address: {}", e))?,
web_server_port: options.web_server_port.map(|p| p as u16),
web_server_cert: options.web_server_cert.map(std::path::PathBuf::from),
web_server_key: options.web_server_key.map(std::path::PathBuf::from),
enforce_https_for_localhost: options.enforce_https_for_localhost,
post_command_discovery_hook: options.post_command_discovery_hook,
})
}
}
// Complete Action conversion implementation - all 91 variants
impl From<crate::input::actions::Action>
for crate::client_server_contract::client_server_contract::Action
{
fn from(action: crate::input::actions::Action) -> Self {
use crate::client_server_contract::client_server_contract::{
action::ActionType, BreakPaneAction, BreakPaneLeftAction, BreakPaneRightAction,
ChangeFloatingPaneCoordinatesAction, ClearScreenAction, CliPipeAction,
CloseFocusAction, ClosePluginPaneAction, CloseTabAction, CloseTerminalPaneAction,
ConfirmAction, CopyAction, DenyAction, DetachAction, DumpLayoutAction,
DumpScreenAction, EditFileAction, EditScrollbackAction, FocusNextPaneAction,
FocusPluginPaneWithIdAction, FocusPreviousPaneAction, FocusTerminalPaneWithIdAction,
GoToNextTabAction, GoToPreviousTabAction, GoToTabAction, GoToTabNameAction,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/ipc/tests/roundtrip_tests.rs | zellij-utils/src/ipc/tests/roundtrip_tests.rs | use super::test_framework::*;
use crate::data::{
BareKey, CommandOrPlugin, ConnectToSession, Direction, FloatingPaneCoordinates, InputMode,
KeyModifier, KeyWithModifier, LayoutInfo, OriginatingPlugin, PaneId, PluginTag, Resize,
WebSharing,
};
use crate::input::actions::{Action, SearchDirection, SearchOption};
use crate::input::cli_assets::CliAssets;
use crate::input::command::{OpenFilePayload, RunCommand, RunCommandAction};
use crate::input::layout::{
FloatingPaneLayout, LayoutConstraint, PercentOrFixed, PluginAlias, PluginUserConfiguration,
Run, RunPlugin, RunPluginLocation, RunPluginOrAlias, SplitDirection, SplitSize,
TiledPaneLayout,
};
use crate::input::mouse::{MouseEvent, MouseEventType};
use crate::input::options::{Clipboard, OnForceClose, Options};
use crate::ipc::{
ClientToServerMsg, ColorRegister, ExitReason, PaneReference, PixelDimensions, ServerToClientMsg,
};
use crate::pane_size::{Size, SizeInPixels};
use crate::position::Position;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
#[test]
fn server_client_contract() {
// here we test all possible values of each of the nested types in the server/client contract
// in the context of its message.
//
// we do a "roundtrip" test, meaning we take each message, encode it to protobuf bytes and
// decode it back to its rust type and then assert its equality with the original type to make
// sure they are identical and did not lose any information
test_client_messages();
test_server_messages();
}
fn test_client_messages() {
let empty_context = BTreeMap::new();
let mut demo_context = BTreeMap::new();
demo_context.insert("demo_key1".to_owned(), "demo_value1".to_owned());
demo_context.insert("demo_key2".to_owned(), "demo_value2".to_owned());
demo_context.insert("demo_key3".to_owned(), "demo_value3".to_owned());
let mut swap_tiled_layouts_1 = BTreeMap::new();
swap_tiled_layouts_1.insert(
LayoutConstraint::MaxPanes(1),
TiledPaneLayout {
name: Some("max_panes_1".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_1.insert(
LayoutConstraint::MinPanes(2),
TiledPaneLayout {
name: Some("min_panes_2".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_1.insert(
LayoutConstraint::ExactPanes(3),
TiledPaneLayout {
name: Some("exact_panes_2".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_1.insert(
LayoutConstraint::NoConstraint,
TiledPaneLayout {
name: Some("no_constraint".to_owned()),
..Default::default()
},
);
let swap_tiled_layouts_1 = (
swap_tiled_layouts_1,
Some("swap_tiled_layouts_1".to_owned()),
);
let mut swap_tiled_layouts_2 = BTreeMap::new();
swap_tiled_layouts_2.insert(
LayoutConstraint::MaxPanes(1),
TiledPaneLayout {
name: Some("max_panes_1".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_2.insert(
LayoutConstraint::MinPanes(2),
TiledPaneLayout {
name: Some("min_panes_2".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_2.insert(
LayoutConstraint::ExactPanes(3),
TiledPaneLayout {
name: Some("exact_panes_2".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_2.insert(
LayoutConstraint::NoConstraint,
TiledPaneLayout {
name: Some("no_constraint".to_owned()),
..Default::default()
},
);
let swap_tiled_layouts_2 = (
swap_tiled_layouts_2,
Some("swap_tiled_layouts_2".to_owned()),
);
let mut swap_tiled_layouts_3 = BTreeMap::new();
swap_tiled_layouts_3.insert(
LayoutConstraint::MaxPanes(1),
TiledPaneLayout {
name: Some("max_panes_1".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_3.insert(
LayoutConstraint::MinPanes(2),
TiledPaneLayout {
name: Some("min_panes_2".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_3.insert(
LayoutConstraint::ExactPanes(3),
TiledPaneLayout {
name: Some("exact_panes_2".to_owned()),
..Default::default()
},
);
swap_tiled_layouts_3.insert(
LayoutConstraint::NoConstraint,
TiledPaneLayout {
name: Some("no_constraint".to_owned()),
..Default::default()
},
);
let swap_tiled_layouts_3 = (swap_tiled_layouts_3, None);
let mut swap_floating_layouts_1 = BTreeMap::new();
swap_floating_layouts_1.insert(
LayoutConstraint::MaxPanes(1),
vec![
FloatingPaneLayout {
name: Some("max_panes_1".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("max_panes_1_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_1.insert(
LayoutConstraint::MinPanes(2),
vec![
FloatingPaneLayout {
name: Some("min_panes_2".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("min_panes_2_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_1.insert(
LayoutConstraint::ExactPanes(3),
vec![
FloatingPaneLayout {
name: Some("exact_panes_2".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("exact_panes_2_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_1.insert(
LayoutConstraint::NoConstraint,
vec![
FloatingPaneLayout {
name: Some("no_constraint".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("no_constraint_1".to_owned()),
..Default::default()
},
],
);
let swap_floating_layouts_1 = (
swap_floating_layouts_1,
Some("swap_floating_layouts_1".to_owned()),
);
let mut swap_floating_layouts_2 = BTreeMap::new();
swap_floating_layouts_2.insert(
LayoutConstraint::MaxPanes(1),
vec![
FloatingPaneLayout {
name: Some("max_panes_1".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("max_panes_1_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_2.insert(
LayoutConstraint::MinPanes(2),
vec![
FloatingPaneLayout {
name: Some("min_panes_2".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("min_panes_2_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_2.insert(
LayoutConstraint::ExactPanes(3),
vec![
FloatingPaneLayout {
name: Some("exact_panes_2".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("exact_panes_2_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_2.insert(
LayoutConstraint::NoConstraint,
vec![
FloatingPaneLayout {
name: Some("no_constraint".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("no_constraint_1".to_owned()),
..Default::default()
},
],
);
let swap_floating_layouts_2 = (
swap_floating_layouts_2,
Some("swap_floating_layouts_2".to_owned()),
);
let mut swap_floating_layouts_3 = BTreeMap::new();
swap_floating_layouts_3.insert(
LayoutConstraint::MaxPanes(1),
vec![
FloatingPaneLayout {
name: Some("max_panes_1".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("max_panes_1_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_3.insert(
LayoutConstraint::MinPanes(2),
vec![
FloatingPaneLayout {
name: Some("min_panes_2".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("min_panes_2_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_3.insert(
LayoutConstraint::ExactPanes(3),
vec![
FloatingPaneLayout {
name: Some("exact_panes_2".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("exact_panes_2_1".to_owned()),
..Default::default()
},
],
);
swap_floating_layouts_3.insert(
LayoutConstraint::NoConstraint,
vec![
FloatingPaneLayout {
name: Some("no_constraint".to_owned()),
..Default::default()
},
FloatingPaneLayout {
name: Some("no_constraint_1".to_owned()),
..Default::default()
},
],
);
let swap_floating_layouts_3 = (swap_floating_layouts_3, None);
let mut demo_modifiers_1 = BTreeSet::new();
let mut demo_modifiers_2 = BTreeSet::new();
let mut demo_modifiers_3 = BTreeSet::new();
let mut demo_modifiers_4 = BTreeSet::new();
demo_modifiers_1.insert(KeyModifier::Ctrl);
demo_modifiers_2.insert(KeyModifier::Ctrl);
demo_modifiers_3.insert(KeyModifier::Ctrl);
demo_modifiers_4.insert(KeyModifier::Ctrl);
demo_modifiers_2.insert(KeyModifier::Alt);
demo_modifiers_3.insert(KeyModifier::Alt);
demo_modifiers_4.insert(KeyModifier::Alt);
demo_modifiers_3.insert(KeyModifier::Shift);
demo_modifiers_4.insert(KeyModifier::Shift);
demo_modifiers_4.insert(KeyModifier::Super);
test_client_roundtrip!(ClientToServerMsg::DetachSession { client_ids: vec![] });
test_client_roundtrip!(ClientToServerMsg::DetachSession {
client_ids: vec![1],
});
test_client_roundtrip!(ClientToServerMsg::DetachSession {
client_ids: vec![1, 2, 999],
});
test_client_roundtrip!(ClientToServerMsg::TerminalPixelDimensions {
pixel_dimensions: PixelDimensions {
text_area_size: None,
character_cell_size: None,
},
});
test_client_roundtrip!(ClientToServerMsg::TerminalPixelDimensions {
pixel_dimensions: PixelDimensions {
text_area_size: Some(SizeInPixels {
width: 800,
height: 600
}),
character_cell_size: Some(SizeInPixels {
width: 10,
height: 20
}),
},
});
test_client_roundtrip!(ClientToServerMsg::BackgroundColor {
color: "red".to_string(),
});
test_client_roundtrip!(ClientToServerMsg::BackgroundColor {
color: "#FF0000".to_string(),
});
test_client_roundtrip!(ClientToServerMsg::BackgroundColor {
color: "".to_string(),
});
test_client_roundtrip!(ClientToServerMsg::ForegroundColor {
color: "blue".to_string(),
});
test_client_roundtrip!(ClientToServerMsg::ColorRegisters {
color_registers: vec![],
});
test_client_roundtrip!(ClientToServerMsg::ColorRegisters {
color_registers: vec![
ColorRegister {
index: 0,
color: "black".to_string()
},
ColorRegister {
index: 1,
color: "red".to_string()
},
ColorRegister {
index: 255,
color: "#FFFFFF".to_string()
},
],
});
test_client_roundtrip!(ClientToServerMsg::TerminalResize {
new_size: Size { cols: 80, rows: 24 },
});
test_client_roundtrip!(ClientToServerMsg::TerminalResize {
new_size: Size {
cols: 200,
rows: 50
},
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets::default(),
is_web_client: false,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets::default(),
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
config_file_path: Some(PathBuf::from("/path/to/config/file.kdl")),
config_dir: Some(PathBuf::from("/path/to/config/dir")),
should_ignore_config: true,
configuration_options: None,
layout: None,
terminal_window_size: Size { rows: 80, cols: 42 },
data_dir: Some(PathBuf::from("/path/to/data/dir")),
is_debug: true,
max_panes: Some(4),
force_run_layout_commands: true,
cwd: Some(PathBuf::from("/path/to/cwd")),
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
config_file_path: Some(PathBuf::from("/path/to/config/file.kdl")),
config_dir: Some(PathBuf::from("/path/to/config/dir")),
should_ignore_config: true,
configuration_options: Some(Options::default()),
layout: None,
terminal_window_size: Size { rows: 80, cols: 42 },
data_dir: Some(PathBuf::from("/path/to/data/dir")),
is_debug: true,
max_panes: Some(4),
force_run_layout_commands: true,
cwd: Some(PathBuf::from("/path/to/cwd")),
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
config_file_path: Some(PathBuf::from("/path/to/config/file.kdl")),
config_dir: Some(PathBuf::from("/path/to/config/dir")),
should_ignore_config: true,
configuration_options: Some(Options {
simplified_ui: Some(true),
theme: Some("theme".to_owned()),
default_mode: Some(InputMode::Normal),
default_shell: Some(PathBuf::from("default_shell")),
default_cwd: Some(PathBuf::from("default_cwd")),
default_layout: Some(PathBuf::from("default_layout")),
layout_dir: Some(PathBuf::from("layout_dir")),
theme_dir: Some(PathBuf::from("theme_dir")),
mouse_mode: Some(true),
pane_frames: Some(true),
mirror_session: Some(true),
on_force_close: Some(OnForceClose::Quit),
scroll_buffer_size: Some(100000),
copy_command: Some("copy_command".to_owned()),
copy_clipboard: Some(Clipboard::System),
copy_on_select: Some(true),
scrollback_editor: Some(PathBuf::from("scrollback_editor")),
session_name: Some("session_name".to_owned()),
attach_to_session: Some(true),
auto_layout: Some(true),
session_serialization: Some(true),
serialize_pane_viewport: Some(true),
scrollback_lines_to_serialize: Some(10000),
styled_underlines: Some(true),
serialization_interval: Some(1),
disable_session_metadata: Some(true),
support_kitty_keyboard_protocol: Some(true),
web_server: Some(true),
web_sharing: Some(WebSharing::On),
stacked_resize: Some(true),
show_startup_tips: Some(true),
show_release_notes: Some(true),
advanced_mouse_actions: Some(true),
web_server_ip: Some("1.1.1.1".parse().unwrap()),
web_server_port: Some(8080),
web_server_cert: Some(PathBuf::from("web_server_cert")),
web_server_key: Some(PathBuf::from("web_server_key")),
enforce_https_for_localhost: Some(true),
post_command_discovery_hook: Some("post_command_discovery_hook".to_owned()),
}),
layout: None,
terminal_window_size: Size { rows: 80, cols: 42 },
data_dir: Some(PathBuf::from("/path/to/data/dir")),
is_debug: true,
max_panes: Some(4),
force_run_layout_commands: true,
cwd: Some(PathBuf::from("/path/to/cwd")),
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Normal),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Locked),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Resize),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Pane),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Tab),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Scroll),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::EnterSearch),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Search),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::RenameTab),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::RenamePane),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Session),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Move),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Prompt),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
default_mode: Some(InputMode::Tmux),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
on_force_close: Some(OnForceClose::Detach),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
copy_clipboard: Some(Clipboard::Primary),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
web_sharing: Some(WebSharing::Off),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::FirstClientConnected {
cli_assets: CliAssets {
configuration_options: Some(Options {
web_sharing: Some(WebSharing::Disabled),
..Default::default()
}),
..Default::default()
},
is_web_client: true,
});
test_client_roundtrip!(ClientToServerMsg::AttachClient {
// cli_assets tested extensively ijn FirstClientConnected, we can skip it here
cli_assets: CliAssets::default(),
tab_position_to_focus: None,
pane_to_focus: None,
is_web_client: false,
});
test_client_roundtrip!(ClientToServerMsg::AttachClient {
cli_assets: CliAssets::default(),
tab_position_to_focus: Some(0),
pane_to_focus: None,
is_web_client: false,
});
test_client_roundtrip!(ClientToServerMsg::AttachClient {
cli_assets: CliAssets::default(),
tab_position_to_focus: None,
pane_to_focus: Some(PaneReference {
pane_id: 0,
is_plugin: false,
}),
is_web_client: false,
});
test_client_roundtrip!(ClientToServerMsg::AttachClient {
cli_assets: CliAssets::default(),
tab_position_to_focus: None,
pane_to_focus: Some(PaneReference {
pane_id: 100,
is_plugin: true,
}),
is_web_client: true,
});
// TODO: Action
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Quit,
terminal_id: None,
client_id: None,
is_cli_client: false,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Quit,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Write {
key_with_modifier: None,
bytes: vec![],
is_kitty_keyboard_protocol: false,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Write {
// KeyWithModifier is tested extensively in the Key ClientToServerMsg
key_with_modifier: Some(KeyWithModifier::new(BareKey::Char('a'))),
bytes: "a".as_bytes().to_vec(),
is_kitty_keyboard_protocol: true,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::WriteChars {
chars: "my chars".to_owned(),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::SwitchToMode {
// InputMode is tested extensively in the Options conversion tests above
input_mode: InputMode::Locked,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::SwitchModeForAllClients {
// InputMode is tested extensively in the Options conversion tests above
input_mode: InputMode::Locked,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Resize {
resize: Resize::Increase,
direction: None,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Resize {
resize: Resize::Decrease,
direction: None,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Resize {
resize: Resize::Decrease,
direction: Some(Direction::Left),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Resize {
resize: Resize::Decrease,
direction: Some(Direction::Right),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Resize {
resize: Resize::Decrease,
direction: Some(Direction::Up),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::Resize {
resize: Resize::Decrease,
direction: Some(Direction::Down),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::FocusNextPane,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::FocusPreviousPane,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::SwitchFocus,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::MoveFocus {
// Direction is tested extensively elsewhere
direction: Direction::Up,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::MoveFocusOrTab {
direction: Direction::Up,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::MovePane { direction: None },
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::MovePane {
direction: Some(Direction::Up),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::MovePaneBackwards,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ClearScreen,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::DumpScreen {
file_path: "/path/to/file".to_owned(),
include_scrollback: false,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::DumpScreen {
file_path: "/path/to/file".to_owned(),
include_scrollback: true,
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::DumpLayout,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::EditScrollback,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ScrollUp,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ScrollUpAt {
position: Position::new(0, 0),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ScrollUpAt {
position: Position::new(-10, 0),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ScrollDown,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ScrollDownAt {
position: Position::new(0, 0),
},
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ScrollToBottom,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::ScrollToTop,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
});
test_client_roundtrip!(ClientToServerMsg::Action {
action: Action::PageScrollUp,
terminal_id: Some(1),
client_id: Some(100),
is_cli_client: true,
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/ipc/tests/test_framework.rs | zellij-utils/src/ipc/tests/test_framework.rs | /// Macro for testing round-trip conversion for ClientToServerMsg variants
macro_rules! test_client_roundtrip {
($msg:expr) => {{
let original: crate::ipc::ClientToServerMsg = $msg;
let proto: crate::client_server_contract::client_server_contract::ClientToServerMsg =
original.clone().into();
let roundtrip: crate::ipc::ClientToServerMsg = proto
.try_into()
.expect("Failed to convert back from protobuf");
assert_eq!(original, roundtrip);
}};
}
/// Macro for testing round-trip conversion for ServerToClientMsg variants
macro_rules! test_server_roundtrip {
($msg:expr) => {{
let original: crate::ipc::ServerToClientMsg = $msg;
let proto: crate::client_server_contract::client_server_contract::ServerToClientMsg =
original.clone().into();
let roundtrip: crate::ipc::ServerToClientMsg = proto
.try_into()
.expect("Failed to convert back from protobuf");
assert_eq!(original, roundtrip);
}};
}
pub(crate) use {test_client_roundtrip, test_server_roundtrip};
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/ipc/tests/mod.rs | zellij-utils/src/ipc/tests/mod.rs | mod roundtrip_tests;
mod test_framework;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/config.rs | zellij-utils/src/input/config.rs | use crate::data::Styling;
use miette::{Diagnostic, LabeledSpan, NamedSource, SourceCode};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs::File;
use std::io::{self, Read};
use std::path::PathBuf;
use thiserror::Error;
use std::convert::TryFrom;
use super::keybinds::Keybinds;
use super::layout::RunPluginOrAlias;
use super::options::Options;
use super::plugins::{PluginAliases, PluginsConfigError};
use super::theme::{Themes, UiConfig};
use super::web_client::WebClientConfig;
use crate::cli::{CliArgs, Command};
use crate::envs::EnvironmentVariables;
use crate::{home, setup};
pub const DEFAULT_CONFIG_FILE_NAME: &str = "config.kdl";
type ConfigResult = Result<Config, ConfigError>;
/// Main configuration.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Config {
pub keybinds: Keybinds,
pub options: Options,
pub themes: Themes,
pub plugins: PluginAliases,
pub ui: UiConfig,
pub env: EnvironmentVariables,
pub background_plugins: HashSet<RunPluginOrAlias>,
pub web_client: WebClientConfig,
}
#[derive(Error, Debug)]
pub struct KdlError {
pub error_message: String,
pub src: Option<NamedSource>,
pub offset: Option<usize>,
pub len: Option<usize>,
pub help_message: Option<String>,
}
impl KdlError {
pub fn add_src(mut self, src_name: String, src_input: String) -> Self {
self.src = Some(NamedSource::new(src_name, src_input));
self
}
}
impl std::fmt::Display for KdlError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "Failed to parse Zellij configuration")
}
}
use std::fmt::Display;
impl Diagnostic for KdlError {
fn source_code(&self) -> Option<&dyn SourceCode> {
match self.src.as_ref() {
Some(src) => Some(src),
None => None,
}
}
fn help<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
match &self.help_message {
Some(help_message) => Some(Box::new(help_message)),
None => Some(Box::new(format!("For more information, please see our configuration guide: https://zellij.dev/documentation/configuration.html")))
}
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
if let (Some(offset), Some(len)) = (self.offset, self.len) {
let label = LabeledSpan::new(Some(self.error_message.clone()), offset, len);
Some(Box::new(std::iter::once(label)))
} else {
None
}
}
}
#[derive(Error, Debug, Diagnostic)]
pub enum ConfigError {
// Deserialization error
#[error("Deserialization error: {0}")]
KdlDeserializationError(#[from] kdl::KdlError),
#[error("KdlDeserialization error: {0}")]
KdlError(KdlError), // TODO: consolidate these
#[error("Config error: {0}")]
Std(#[from] Box<dyn std::error::Error>),
// Io error with path context
#[error("IoError: {0}, File: {1}")]
IoPath(io::Error, PathBuf),
// Internal Deserialization Error
#[error("FromUtf8Error: {0}")]
FromUtf8(#[from] std::string::FromUtf8Error),
// Plugins have a semantic error, usually trying to parse two of the same tag
#[error("PluginsError: {0}")]
PluginsError(#[from] PluginsConfigError),
#[error("{0}")]
ConversionError(#[from] ConversionError),
#[error("{0}")]
DownloadError(String),
}
impl ConfigError {
pub fn new_kdl_error(error_message: String, offset: usize, len: usize) -> Self {
ConfigError::KdlError(KdlError {
error_message,
src: None,
offset: Some(offset),
len: Some(len),
help_message: None,
})
}
pub fn new_layout_kdl_error(error_message: String, offset: usize, len: usize) -> Self {
ConfigError::KdlError(KdlError {
error_message,
src: None,
offset: Some(offset),
len: Some(len),
help_message: Some(format!("For more information, please see our layout guide: https://zellij.dev/documentation/creating-a-layout.html")),
})
}
}
#[derive(Debug, Error)]
pub enum ConversionError {
#[error("{0}")]
UnknownInputMode(String),
}
impl TryFrom<&CliArgs> for Config {
type Error = ConfigError;
fn try_from(opts: &CliArgs) -> ConfigResult {
if let Some(ref path) = opts.config {
let default_config = Config::from_default_assets()?;
return Config::from_path(path, Some(default_config));
}
if let Some(Command::Setup(ref setup)) = opts.command {
if setup.clean {
return Config::from_default_assets();
}
}
let config_dir = opts
.config_dir
.clone()
.or_else(home::find_default_config_dir);
if let Some(ref config) = config_dir {
let path = config.join(DEFAULT_CONFIG_FILE_NAME);
if path.exists() {
let default_config = Config::from_default_assets()?;
Config::from_path(&path, Some(default_config))
} else {
Config::from_default_assets()
}
} else {
Config::from_default_assets()
}
}
}
impl Config {
pub fn theme_config(&self, theme_name: Option<&String>) -> Option<Styling> {
match &theme_name {
Some(theme_name) => self.themes.get_theme(theme_name).map(|theme| theme.palette),
None => self.themes.get_theme("default").map(|theme| theme.palette),
}
}
/// Gets default configuration from assets
pub fn from_default_assets() -> ConfigResult {
let cfg = String::from_utf8(setup::DEFAULT_CONFIG.to_vec())?;
match Self::from_kdl(&cfg, None) {
Ok(config) => Ok(config),
Err(ConfigError::KdlError(kdl_error)) => Err(ConfigError::KdlError(
kdl_error.add_src("Default built-in-configuration".into(), cfg),
)),
Err(e) => Err(e),
}
}
pub fn from_path(path: &PathBuf, default_config: Option<Config>) -> ConfigResult {
match File::open(path) {
Ok(mut file) => {
let mut kdl_config = String::new();
file.read_to_string(&mut kdl_config)
.map_err(|e| ConfigError::IoPath(e, path.to_path_buf()))?;
match Config::from_kdl(&kdl_config, default_config) {
Ok(config) => Ok(config),
Err(ConfigError::KdlDeserializationError(kdl_error)) => {
let error_message = match kdl_error.kind {
kdl::KdlErrorKind::Context("valid node terminator") => {
format!("Failed to deserialize KDL node. \nPossible reasons:\n{}\n{}\n{}\n{}",
"- Missing `;` after a node name, eg. { node; another_node; }",
"- Missing quotations (\") around an argument node eg. { first_node \"argument_node\"; }",
"- Missing an equal sign (=) between node arguments on a title line. eg. argument=\"value\"",
"- Found an extraneous equal sign (=) between node child arguments and their values. eg. { argument=\"value\" }")
},
_ => {
String::from(kdl_error.help.unwrap_or("Kdl Deserialization Error"))
},
};
let kdl_error = KdlError {
error_message,
src: Some(NamedSource::new(
path.as_path().as_os_str().to_string_lossy(),
kdl_config,
)),
offset: Some(kdl_error.span.offset()),
len: Some(kdl_error.span.len()),
help_message: None,
};
Err(ConfigError::KdlError(kdl_error))
},
Err(ConfigError::KdlError(kdl_error)) => {
Err(ConfigError::KdlError(kdl_error.add_src(
path.as_path().as_os_str().to_string_lossy().to_string(),
kdl_config,
)))
},
Err(e) => Err(e),
}
},
Err(e) => Err(ConfigError::IoPath(e, path.into())),
}
}
pub fn merge(&mut self, other: Config) -> Result<(), ConfigError> {
self.options = self.options.merge(other.options);
self.keybinds.merge(other.keybinds.clone());
self.themes = self.themes.merge(other.themes);
self.plugins.merge(other.plugins);
self.ui = self.ui.merge(other.ui);
self.env = self.env.merge(other.env);
Ok(())
}
pub fn config_file_path(opts: &CliArgs) -> Option<PathBuf> {
opts.config.clone().or_else(|| {
opts.config_dir
.clone()
.or_else(|| {
home::try_create_home_config_dir();
home::find_default_config_dir()
})
.map(|config_dir| config_dir.join(DEFAULT_CONFIG_FILE_NAME))
})
}
pub fn default_config_file_path() -> Option<PathBuf> {
home::find_default_config_dir().map(|config_dir| config_dir.join(DEFAULT_CONFIG_FILE_NAME))
}
pub fn write_config_to_disk(
config: String,
config_file_path: &PathBuf,
) -> Result<Config, Option<PathBuf>> {
// if we fail, try to return the PathBuf of the file we were not able to write to
let config_file_path = config_file_path.clone();
Config::from_kdl(&config, None)
.map_err(|e| {
log::error!("Failed to parse config: {}", e);
None
})
.and_then(|parsed_config| {
let backed_up_file_name = Config::backup_current_config(&config_file_path)?;
let config = match backed_up_file_name {
Some(backed_up_file_name) => {
format!(
"{}{}",
Config::autogen_config_message(backed_up_file_name),
config
)
},
None => config,
};
std::fs::write(&config_file_path, config.as_bytes()).map_err(|e| {
log::error!("Failed to write config: {}", e);
Some(config_file_path.clone())
})?;
let written_config = std::fs::read_to_string(&config_file_path).map_err(|e| {
log::error!("Failed to read written config: {}", e);
Some(config_file_path.clone())
})?;
let parsed_written_config =
Config::from_kdl(&written_config, None).map_err(|e| {
log::error!("Failed to parse written config: {}", e);
None
})?;
if parsed_written_config == parsed_config {
Ok(parsed_config)
} else {
log::error!("Configuration corrupted when writing to disk");
Err(Some(config_file_path))
}
})
}
// returns true if the config was not previouly written to disk and we successfully wrote it
pub fn write_config_to_disk_if_it_does_not_exist(
config: String,
config_file_path: &Option<PathBuf>,
) -> bool {
let Some(config_file_path) = config_file_path.clone() else {
log::error!("Could not find file path to write config");
return false;
};
if config_file_path.exists() {
false
} else {
if let Err(e) = std::fs::write(&config_file_path, config.as_bytes()) {
log::error!("Failed to write config to disk: {}", e);
return false;
}
match std::fs::read_to_string(&config_file_path) {
Ok(written_config) => written_config == config,
Err(e) => {
log::error!("Failed to read written config: {}", e);
false
},
}
}
}
fn find_free_backup_file_name(config_file_path: &PathBuf) -> Option<PathBuf> {
let mut backup_config_path = None;
let config_file_name = config_file_path
.file_name()
.and_then(|f| f.to_str())
.unwrap_or_else(|| DEFAULT_CONFIG_FILE_NAME);
for i in 0..100 {
let new_file_name = if i == 0 {
format!("{}.bak", config_file_name)
} else {
format!("{}.bak.{}", config_file_name, i)
};
let mut potential_config_path = config_file_path.clone();
potential_config_path.set_file_name(new_file_name);
if !potential_config_path.exists() {
backup_config_path = Some(potential_config_path);
break;
}
}
backup_config_path
}
fn backup_config_with_written_content_confirmation(
current_config: &str,
current_config_file_path: &PathBuf,
backup_config_path: &PathBuf,
) -> bool {
let _ = std::fs::copy(current_config_file_path, &backup_config_path);
match std::fs::read_to_string(&backup_config_path) {
Ok(backed_up_config) => current_config == &backed_up_config,
Err(e) => {
log::error!(
"Failed to back up config file {}: {:?}",
backup_config_path.display(),
e
);
false
},
}
}
fn backup_current_config(
config_file_path: &PathBuf,
) -> Result<Option<PathBuf>, Option<PathBuf>> {
// if we fail, try to return the PathBuf of the file we were not able to write to
// if let Some(config_file_path) = Config::config_file_path(&opts) {
match std::fs::read_to_string(&config_file_path) {
Ok(current_config) => {
let Some(backup_config_path) =
Config::find_free_backup_file_name(&config_file_path)
else {
log::error!("Failed to find a file name to back up the configuration to, ran out of files.");
return Err(None);
};
if Config::backup_config_with_written_content_confirmation(
¤t_config,
&config_file_path,
&backup_config_path,
) {
Ok(Some(backup_config_path))
} else {
log::error!(
"Failed to back up config file: {}",
backup_config_path.display()
);
Err(Some(backup_config_path))
}
},
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(None)
} else {
log::error!(
"Failed to read current config {}: {}",
config_file_path.display(),
e
);
Err(Some(config_file_path.clone()))
}
},
}
}
fn autogen_config_message(backed_up_file_name: PathBuf) -> String {
format!("//\n// THIS FILE WAS AUTOGENERATED BY ZELLIJ, THE PREVIOUS FILE AT THIS LOCATION WAS COPIED TO: {}\n//\n\n", backed_up_file_name.display())
}
}
#[cfg(not(target_family = "wasm"))]
pub async fn watch_config_file_changes<F, Fut>(config_file_path: PathBuf, on_config_change: F)
where
F: Fn(Config) -> Fut + Send + 'static,
Fut: std::future::Future<Output = ()> + Send,
{
// in a gist, what we do here is fire the `on_config_change` function whenever there is a
// change in the config file, we do this by:
// 1. Trying to watch the provided config file for changes
// 2. If the file is deleted or does not exist, we periodically poll for it (manually, not
// through filesystem events)
// 3. Once it exists, we start watching it for changes again
//
// we do this because the alternative is to watch its parent folder and this might cause the
// classic "too many open files" issue if there are a lot of files there and/or lots of Zellij
// instances
use crate::setup::Setup;
use notify::{self, Config as WatcherConfig, Event, PollWatcher, RecursiveMode, Watcher};
use std::time::Duration;
use tokio::sync::mpsc;
loop {
if config_file_path.exists() {
let (tx, mut rx) = mpsc::unbounded_channel();
let mut watcher = match PollWatcher::new(
move |res: Result<Event, notify::Error>| {
let _ = tx.send(res);
},
WatcherConfig::default().with_poll_interval(Duration::from_secs(1)),
) {
Ok(watcher) => watcher,
Err(_) => break,
};
if watcher
.watch(&config_file_path, RecursiveMode::NonRecursive)
.is_err()
{
break;
}
while let Some(event_result) = rx.recv().await {
match event_result {
Ok(event) => {
if event.paths.contains(&config_file_path) {
if event.kind.is_remove() {
break;
} else if event.kind.is_create() || event.kind.is_modify() {
tokio::time::sleep(Duration::from_millis(100)).await;
if !config_file_path.exists() {
continue;
}
let mut cli_args_for_config = CliArgs::default();
cli_args_for_config.config = Some(PathBuf::from(&config_file_path));
if let Ok(new_config) = Setup::from_cli_args(&cli_args_for_config)
.map_err(|e| e.to_string())
{
on_config_change(new_config.0).await;
}
}
}
},
Err(_) => break,
}
}
}
while !config_file_path.exists() {
tokio::time::sleep(Duration::from_secs(3)).await;
}
}
}
#[cfg(test)]
mod config_test {
use super::*;
use crate::data::{InputMode, Palette, PaletteColor, StyleDeclaration, Styling};
use crate::input::layout::RunPlugin;
use crate::input::options::{Clipboard, OnForceClose};
use crate::input::theme::{FrameConfig, Theme, Themes, UiConfig};
use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use tempfile::tempdir;
#[test]
fn try_from_cli_args_with_config() {
// makes sure loading a config file with --config tries to load the config
let arbitrary_config = PathBuf::from("nonexistent.yaml");
let opts = CliArgs {
config: Some(arbitrary_config),
..Default::default()
};
println!("OPTS= {:?}", opts);
let result = Config::try_from(&opts);
assert!(result.is_err());
}
#[test]
fn try_from_cli_args_with_option_clean() {
// makes sure --clean works... TODO: how can this actually fail now?
use crate::setup::Setup;
let opts = CliArgs {
command: Some(Command::Setup(Setup {
clean: true,
..Setup::default()
})),
..Default::default()
};
let result = Config::try_from(&opts);
assert!(result.is_ok());
}
#[test]
fn try_from_cli_args_with_config_dir() {
let mut opts = CliArgs::default();
let tmp = tempdir().unwrap();
File::create(tmp.path().join(DEFAULT_CONFIG_FILE_NAME))
.unwrap()
.write_all(b"keybinds: invalid\n")
.unwrap();
opts.config_dir = Some(tmp.path().to_path_buf());
let result = Config::try_from(&opts);
assert!(result.is_err());
}
#[test]
fn try_from_cli_args_with_config_dir_without_config() {
let mut opts = CliArgs::default();
let tmp = tempdir().unwrap();
opts.config_dir = Some(tmp.path().to_path_buf());
let result = Config::try_from(&opts);
assert_eq!(result.unwrap(), Config::from_default_assets().unwrap());
}
#[test]
fn try_from_cli_args_default() {
let opts = CliArgs::default();
let result = Config::try_from(&opts);
assert_eq!(result.unwrap(), Config::from_default_assets().unwrap());
}
#[test]
fn can_define_options_in_configfile() {
let config_contents = r#"
simplified_ui true
theme "my cool theme"
default_mode "locked"
default_shell "/path/to/my/shell"
default_cwd "/path"
default_layout "/path/to/my/layout.kdl"
layout_dir "/path/to/my/layout-dir"
theme_dir "/path/to/my/theme-dir"
mouse_mode false
pane_frames false
mirror_session true
on_force_close "quit"
scroll_buffer_size 100000
copy_command "/path/to/my/copy-command"
copy_clipboard "primary"
copy_on_select false
scrollback_editor "/path/to/my/scrollback-editor"
session_name "my awesome session"
attach_to_session true
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
assert_eq!(
config.options.simplified_ui,
Some(true),
"Option set in config"
);
assert_eq!(
config.options.theme,
Some(String::from("my cool theme")),
"Option set in config"
);
assert_eq!(
config.options.default_mode,
Some(InputMode::Locked),
"Option set in config"
);
assert_eq!(
config.options.default_shell,
Some(PathBuf::from("/path/to/my/shell")),
"Option set in config"
);
assert_eq!(
config.options.default_cwd,
Some(PathBuf::from("/path")),
"Option set in config"
);
assert_eq!(
config.options.default_layout,
Some(PathBuf::from("/path/to/my/layout.kdl")),
"Option set in config"
);
assert_eq!(
config.options.layout_dir,
Some(PathBuf::from("/path/to/my/layout-dir")),
"Option set in config"
);
assert_eq!(
config.options.theme_dir,
Some(PathBuf::from("/path/to/my/theme-dir")),
"Option set in config"
);
assert_eq!(
config.options.mouse_mode,
Some(false),
"Option set in config"
);
assert_eq!(
config.options.pane_frames,
Some(false),
"Option set in config"
);
assert_eq!(
config.options.mirror_session,
Some(true),
"Option set in config"
);
assert_eq!(
config.options.on_force_close,
Some(OnForceClose::Quit),
"Option set in config"
);
assert_eq!(
config.options.scroll_buffer_size,
Some(100000),
"Option set in config"
);
assert_eq!(
config.options.copy_command,
Some(String::from("/path/to/my/copy-command")),
"Option set in config"
);
assert_eq!(
config.options.copy_clipboard,
Some(Clipboard::Primary),
"Option set in config"
);
assert_eq!(
config.options.copy_on_select,
Some(false),
"Option set in config"
);
assert_eq!(
config.options.scrollback_editor,
Some(PathBuf::from("/path/to/my/scrollback-editor")),
"Option set in config"
);
assert_eq!(
config.options.session_name,
Some(String::from("my awesome session")),
"Option set in config"
);
assert_eq!(
config.options.attach_to_session,
Some(true),
"Option set in config"
);
}
#[test]
fn can_define_themes_in_configfile() {
let config_contents = r#"
themes {
dracula {
fg 248 248 242
bg 40 42 54
red 255 85 85
green 80 250 123
yellow 241 250 140
blue 98 114 164
magenta 255 121 198
orange 255 184 108
cyan 139 233 253
black 0 0 0
white 255 255 255
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let mut expected_themes = HashMap::new();
expected_themes.insert(
"dracula".into(),
Theme {
palette: Palette {
fg: PaletteColor::Rgb((248, 248, 242)),
bg: PaletteColor::Rgb((40, 42, 54)),
red: PaletteColor::Rgb((255, 85, 85)),
green: PaletteColor::Rgb((80, 250, 123)),
yellow: PaletteColor::Rgb((241, 250, 140)),
blue: PaletteColor::Rgb((98, 114, 164)),
magenta: PaletteColor::Rgb((255, 121, 198)),
orange: PaletteColor::Rgb((255, 184, 108)),
cyan: PaletteColor::Rgb((139, 233, 253)),
black: PaletteColor::Rgb((0, 0, 0)),
white: PaletteColor::Rgb((255, 255, 255)),
..Default::default()
}
.into(),
sourced_from_external_file: false,
},
);
let expected_themes = Themes::from_data(expected_themes);
assert_eq!(config.themes, expected_themes, "Theme defined in config");
}
#[test]
fn can_define_multiple_themes_including_hex_themes_in_configfile() {
let config_contents = r##"
themes {
dracula {
fg 248 248 242
bg 40 42 54
red 255 85 85
green 80 250 123
yellow 241 250 140
blue 98 114 164
magenta 255 121 198
orange 255 184 108
cyan 139 233 253
black 0 0 0
white 255 255 255
}
nord {
fg "#D8DEE9"
bg "#2E3440"
black "#3B4252"
red "#BF616A"
green "#A3BE8C"
yellow "#EBCB8B"
blue "#81A1C1"
magenta "#B48EAD"
cyan "#88C0D0"
white "#E5E9F0"
orange "#D08770"
}
}
"##;
let config = Config::from_kdl(config_contents, None).unwrap();
let mut expected_themes = HashMap::new();
expected_themes.insert(
"dracula".into(),
Theme {
palette: Palette {
fg: PaletteColor::Rgb((248, 248, 242)),
bg: PaletteColor::Rgb((40, 42, 54)),
red: PaletteColor::Rgb((255, 85, 85)),
green: PaletteColor::Rgb((80, 250, 123)),
yellow: PaletteColor::Rgb((241, 250, 140)),
blue: PaletteColor::Rgb((98, 114, 164)),
magenta: PaletteColor::Rgb((255, 121, 198)),
orange: PaletteColor::Rgb((255, 184, 108)),
cyan: PaletteColor::Rgb((139, 233, 253)),
black: PaletteColor::Rgb((0, 0, 0)),
white: PaletteColor::Rgb((255, 255, 255)),
..Default::default()
}
.into(),
sourced_from_external_file: false,
},
);
expected_themes.insert(
"nord".into(),
Theme {
palette: Palette {
fg: PaletteColor::Rgb((216, 222, 233)),
bg: PaletteColor::Rgb((46, 52, 64)),
black: PaletteColor::Rgb((59, 66, 82)),
red: PaletteColor::Rgb((191, 97, 106)),
green: PaletteColor::Rgb((163, 190, 140)),
yellow: PaletteColor::Rgb((235, 203, 139)),
blue: PaletteColor::Rgb((129, 161, 193)),
magenta: PaletteColor::Rgb((180, 142, 173)),
cyan: PaletteColor::Rgb((136, 192, 208)),
white: PaletteColor::Rgb((229, 233, 240)),
orange: PaletteColor::Rgb((208, 135, 112)),
..Default::default()
}
.into(),
sourced_from_external_file: false,
},
);
let expected_themes = Themes::from_data(expected_themes);
assert_eq!(config.themes, expected_themes, "Theme defined in config");
}
#[test]
fn can_define_eight_bit_themes() {
let config_contents = r#"
themes {
eight_bit_theme {
fg 248
bg 40
red 255
green 80
yellow 241
blue 98
magenta 255
orange 255
cyan 139
black 1
white 255
}
}
"#;
let config = Config::from_kdl(config_contents, None).unwrap();
let mut expected_themes = HashMap::new();
expected_themes.insert(
"eight_bit_theme".into(),
Theme {
palette: Palette {
fg: PaletteColor::EightBit(248),
bg: PaletteColor::EightBit(40),
red: PaletteColor::EightBit(255),
green: PaletteColor::EightBit(80),
yellow: PaletteColor::EightBit(241),
blue: PaletteColor::EightBit(98),
magenta: PaletteColor::EightBit(255),
orange: PaletteColor::EightBit(255),
cyan: PaletteColor::EightBit(139),
black: PaletteColor::EightBit(1),
white: PaletteColor::EightBit(255),
..Default::default()
}
.into(),
sourced_from_external_file: false,
},
);
let expected_themes = Themes::from_data(expected_themes);
assert_eq!(config.themes, expected_themes, "Theme defined in config");
}
#[test]
fn can_define_style_for_theme_with_hex() {
let config_contents = r##"
themes {
named_theme {
text_unselected {
base "#DCD7BA"
emphasis_0 "#DCD7CD"
emphasis_1 "#DCD8DD"
emphasis_2 "#DCD899"
emphasis_3 "#ACD7CD"
background "#1F1F28"
}
text_selected {
base "#16161D"
emphasis_0 "#16161D"
emphasis_1 "#16161D"
emphasis_2 "#16161D"
emphasis_3 "#16161D"
background "#9CABCA"
}
ribbon_unselected {
base "#DCD7BA"
emphasis_0 "#7FB4CA"
emphasis_1 "#A3D4D5"
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | true |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/cli_assets.rs | zellij-utils/src/input/cli_assets.rs | use crate::data::LayoutInfo;
use crate::input::options::Options;
use crate::pane_size::Size;
use crate::{
home::find_default_config_dir,
input::{config::Config, layout::Layout, theme::Themes},
setup::{get_default_themes, get_theme_dir},
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct CliAssets {
pub config_file_path: Option<PathBuf>,
pub config_dir: Option<PathBuf>,
pub should_ignore_config: bool,
pub configuration_options: Option<Options>, // merged from everywhere: there are the source of truth
pub layout: Option<LayoutInfo>,
pub terminal_window_size: Size,
pub data_dir: Option<PathBuf>,
pub is_debug: bool,
pub max_panes: Option<usize>,
pub force_run_layout_commands: bool,
pub cwd: Option<PathBuf>,
}
impl CliAssets {
pub fn load_config_and_layout(&self) -> (Config, Layout) {
let config = {
if self.should_ignore_config {
Config::from_default_assets().unwrap_or_else(|_| Default::default())
} else if let Some(ref path) = self.config_file_path {
let default_config =
Config::from_default_assets().unwrap_or_else(|_| Default::default());
Config::from_path(path, Some(default_config.clone()))
.unwrap_or_else(|_| default_config)
} else {
Config::from_default_assets().unwrap_or_else(|_| Default::default())
}
};
let (mut layout, mut config_with_merged_layout_opts) = {
let layout_dir = self
.configuration_options
.as_ref()
.and_then(|e| e.layout_dir.clone())
.or_else(|| config.options.layout_dir.clone())
.or_else(|| {
self.config_dir
.clone()
.or_else(find_default_config_dir)
.map(|dir| dir.join("layouts"))
});
self.layout.as_ref().and_then(|layout_info| {
Layout::from_layout_info_with_config(&layout_dir, layout_info, Some(config.clone()))
.ok()
})
}
.map(|(layout, config)| (layout, config))
.unwrap_or_else(|| (Layout::default_layout_asset(), config));
if self.force_run_layout_commands {
layout.recursively_add_start_suspended(Some(false));
}
config_with_merged_layout_opts.themes = config_with_merged_layout_opts
.themes
.merge(get_default_themes());
let user_theme_dir = self
.configuration_options
.as_ref()
.and_then(|o| o.theme_dir.clone())
.or_else(|| {
get_theme_dir(config_with_merged_layout_opts.options.theme_dir.clone())
.or_else(find_default_config_dir)
.filter(|dir| dir.exists())
});
if let Some(themes) = user_theme_dir.and_then(|u| Themes::from_dir(u).ok()) {
config_with_merged_layout_opts.themes =
config_with_merged_layout_opts.themes.merge(themes);
}
(config_with_merged_layout_opts, layout)
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/web_client.rs | zellij-utils/src/input/web_client.rs | use kdl::{KdlDocument, KdlNode, KdlValue};
use serde::{Deserialize, Serialize};
use crate::{
data::PaletteColor, kdl_children_or_error, kdl_first_entry_as_string, kdl_get_child,
kdl_get_child_entry_bool_value, kdl_get_child_entry_string_value,
};
use super::config::ConfigError;
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct WebClientTheme {
pub background: Option<String>,
pub foreground: Option<String>,
pub black: Option<String>,
pub blue: Option<String>,
pub bright_black: Option<String>,
pub bright_blue: Option<String>,
pub bright_cyan: Option<String>,
pub bright_green: Option<String>,
pub bright_magenta: Option<String>,
pub bright_red: Option<String>,
pub bright_white: Option<String>,
pub bright_yellow: Option<String>,
pub cursor: Option<String>,
pub cursor_accent: Option<String>,
pub cyan: Option<String>,
pub green: Option<String>,
pub magenta: Option<String>,
pub red: Option<String>,
pub selection_background: Option<String>,
pub selection_foreground: Option<String>,
pub selection_inactive_background: Option<String>,
pub white: Option<String>,
pub yellow: Option<String>,
}
impl WebClientTheme {
pub fn from_kdl(kdl: &KdlNode) -> Result<Self, ConfigError> {
let mut theme = WebClientTheme::default();
let colors = kdl_children_or_error!(kdl, "empty theme");
// Helper function to extract colors
let extract_color = |name: &str| -> Result<Option<String>, ConfigError> {
if colors.get(name).is_some() {
let color = PaletteColor::try_from((name, colors))?;
Ok(Some(color.as_rgb_str()))
} else {
Ok(None)
}
};
theme.background = extract_color("background")?;
theme.foreground = extract_color("foreground")?;
theme.black = extract_color("black")?;
theme.blue = extract_color("blue")?;
theme.bright_black = extract_color("bright_black")?;
theme.bright_blue = extract_color("bright_blue")?;
theme.bright_cyan = extract_color("bright_cyan")?;
theme.bright_green = extract_color("bright_green")?;
theme.bright_magenta = extract_color("bright_magenta")?;
theme.bright_red = extract_color("bright_red")?;
theme.bright_white = extract_color("bright_white")?;
theme.bright_yellow = extract_color("bright_yellow")?;
theme.cursor = extract_color("cursor")?;
theme.cursor_accent = extract_color("cursor_accent")?;
theme.cyan = extract_color("cyan")?;
theme.green = extract_color("green")?;
theme.magenta = extract_color("magenta")?;
theme.red = extract_color("red")?;
theme.selection_background = extract_color("selection_background")?;
theme.selection_foreground = extract_color("selection_foreground")?;
theme.selection_inactive_background = extract_color("selection_inactive_background")?;
theme.white = extract_color("white")?;
theme.yellow = extract_color("yellow")?;
Ok(theme)
}
pub fn to_kdl(&self) -> KdlNode {
macro_rules! add_color_nodes {
($theme_children:expr, $self:expr, $($field:ident),+ $(,)?) => {
$(
if let Some(color) = &$self.$field {
let node = PaletteColor::from_rgb_str(color).to_kdl(stringify!($field));
$theme_children.nodes_mut().push(node);
}
)+
};
}
let mut theme_node = KdlNode::new("theme");
let mut theme_children = KdlDocument::new();
add_color_nodes!(
theme_children,
self,
background,
foreground,
black,
blue,
bright_black,
bright_blue,
bright_cyan,
bright_green,
bright_magenta,
bright_red,
bright_white,
bright_yellow,
cursor,
cursor_accent,
cyan,
green,
magenta,
red,
selection_background,
selection_foreground,
selection_inactive_background,
white,
yellow,
);
theme_node.set_children(theme_children);
theme_node
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CursorInactiveStyle {
Outline,
Block,
Bar,
Underline,
NoStyle,
}
impl std::fmt::Display for CursorInactiveStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CursorInactiveStyle::Block => write!(f, "block"),
CursorInactiveStyle::Bar => write!(f, "bar"),
CursorInactiveStyle::Underline => write!(f, "underline"),
CursorInactiveStyle::Outline => write!(f, "outline"),
CursorInactiveStyle::NoStyle => write!(f, "none"),
}
}
}
impl CursorInactiveStyle {
pub fn from_kdl(kdl: &KdlNode) -> Result<Self, ConfigError> {
match kdl_first_entry_as_string!(kdl) {
Some("block") => Ok(CursorInactiveStyle::Block),
Some("bar") => Ok(CursorInactiveStyle::Bar),
Some("underline") => Ok(CursorInactiveStyle::Underline),
Some("outline") => Ok(CursorInactiveStyle::Outline),
Some("no_style") => Ok(CursorInactiveStyle::NoStyle),
_ => Err(ConfigError::new_kdl_error(
format!("Must be 'block', 'bar', 'underline', 'outline' or 'no_style'"),
kdl.span().offset(),
kdl.span().len(),
)),
}
}
pub fn to_kdl(&self) -> KdlNode {
let mut cursor_inactive_style_node = KdlNode::new("cursor_inactive_style");
match self {
CursorInactiveStyle::Block => {
cursor_inactive_style_node.push(KdlValue::String("block".to_owned()));
},
CursorInactiveStyle::Bar => {
cursor_inactive_style_node.push(KdlValue::String("bar".to_owned()));
},
CursorInactiveStyle::Underline => {
cursor_inactive_style_node.push(KdlValue::String("underline".to_owned()));
},
CursorInactiveStyle::Outline => {
cursor_inactive_style_node.push(KdlValue::String("outline".to_owned()));
},
CursorInactiveStyle::NoStyle => {
cursor_inactive_style_node.push(KdlValue::String("no_style".to_owned()));
},
}
cursor_inactive_style_node
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CursorStyle {
Block,
Bar,
Underline,
}
impl std::fmt::Display for CursorStyle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CursorStyle::Block => write!(f, "block"),
CursorStyle::Bar => write!(f, "bar"),
CursorStyle::Underline => write!(f, "underline"),
}
}
}
impl CursorStyle {
pub fn from_kdl(kdl: &KdlNode) -> Result<Self, ConfigError> {
match kdl_first_entry_as_string!(kdl) {
Some("block") => Ok(CursorStyle::Block),
Some("bar") => Ok(CursorStyle::Bar),
Some("underline") => Ok(CursorStyle::Underline),
_ => Err(ConfigError::new_kdl_error(
format!("Must be 'block', 'bar' or 'underline'"),
kdl.span().offset(),
kdl.span().len(),
)),
}
}
pub fn to_kdl(&self) -> KdlNode {
let mut cursor_style_node = KdlNode::new("cursor_style");
match self {
CursorStyle::Block => {
cursor_style_node.push(KdlValue::String("block".to_owned()));
},
CursorStyle::Bar => {
cursor_style_node.push(KdlValue::String("bar".to_owned()));
},
CursorStyle::Underline => {
cursor_style_node.push(KdlValue::String("underline".to_owned()));
},
}
cursor_style_node
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WebClientConfig {
pub font: String,
pub theme: Option<WebClientTheme>,
pub cursor_blink: bool,
pub cursor_inactive_style: Option<CursorInactiveStyle>,
pub cursor_style: Option<CursorStyle>,
pub mac_option_is_meta: bool,
}
impl Default for WebClientConfig {
fn default() -> Self {
WebClientConfig {
font: "monospace".to_string(),
theme: None,
cursor_blink: false,
cursor_inactive_style: None,
cursor_style: None,
mac_option_is_meta: true, // TODO: yes? no?
}
}
}
impl WebClientConfig {
pub fn from_kdl(kdl: &KdlNode) -> Result<Self, ConfigError> {
let mut web_client_config = WebClientConfig::default();
if let Some(font) = kdl_get_child_entry_string_value!(kdl, "font") {
web_client_config.font = font.to_owned();
}
if let Some(theme_node) = kdl_get_child!(kdl, "theme") {
web_client_config.theme = Some(WebClientTheme::from_kdl(theme_node)?);
}
if let Some(cursor_blink) = kdl_get_child_entry_bool_value!(kdl, "cursor_blink") {
web_client_config.cursor_blink = cursor_blink;
}
if let Some(cursor_inactive_style_node) = kdl_get_child!(kdl, "cursor_inactive_style") {
web_client_config.cursor_inactive_style =
Some(CursorInactiveStyle::from_kdl(cursor_inactive_style_node)?);
}
if let Some(cursor_style_node) = kdl_get_child!(kdl, "cursor_style") {
web_client_config.cursor_style = Some(CursorStyle::from_kdl(cursor_style_node)?);
}
if let Some(mac_option_is_meta) = kdl_get_child_entry_bool_value!(kdl, "mac_option_is_meta")
{
web_client_config.mac_option_is_meta = mac_option_is_meta;
}
Ok(web_client_config)
}
pub fn to_kdl(&self) -> KdlNode {
let mut web_client_node = KdlNode::new("web_client");
let mut web_client_children = KdlDocument::new();
let mut font_node = KdlNode::new("font");
font_node.push(KdlValue::String(self.font.clone()));
web_client_children.nodes_mut().push(font_node);
if let Some(theme_node) = self.theme.as_ref().map(|t| t.to_kdl()) {
web_client_children.nodes_mut().push(theme_node);
}
if self.cursor_blink {
// this defaults to false, so we only need to add it if it's true
let mut cursor_blink_node = KdlNode::new("cursor_blink");
cursor_blink_node.push(KdlValue::Bool(true));
web_client_children.nodes_mut().push(cursor_blink_node);
}
if let Some(cursor_inactive_style_node) =
self.cursor_inactive_style.as_ref().map(|c| c.to_kdl())
{
web_client_children
.nodes_mut()
.push(cursor_inactive_style_node);
}
if let Some(cursor_style_node) = self.cursor_style.as_ref().map(|c| c.to_kdl()) {
web_client_children.nodes_mut().push(cursor_style_node);
}
if !self.mac_option_is_meta {
// this defaults to true, so we only need to add it if it's false
let mut mac_option_is_meta_node = KdlNode::new("mac_option_is_meta");
mac_option_is_meta_node.push(KdlValue::Bool(false));
web_client_children
.nodes_mut()
.push(mac_option_is_meta_node);
}
web_client_node.set_children(web_client_children);
web_client_node
}
pub fn merge(&self, other: WebClientConfig) -> Self {
let mut merged = self.clone();
merged.font = other.font;
merged.theme = other.theme;
merged.cursor_blink = other.cursor_blink;
merged.cursor_inactive_style = other.cursor_inactive_style;
merged.cursor_style = other.cursor_style;
merged.mac_option_is_meta = other.mac_option_is_meta;
merged
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/command.rs | zellij-utils/src/input/command.rs | //! Trigger a command
use crate::data::{Direction, OriginatingPlugin};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub enum TerminalAction {
OpenFile(OpenFilePayload),
RunCommand(RunCommand),
}
impl TerminalAction {
pub fn change_cwd(&mut self, new_cwd: PathBuf) {
match self {
TerminalAction::OpenFile(open_file_payload) => {
open_file_payload.cwd = Some(new_cwd);
},
TerminalAction::RunCommand(run_command) => {
run_command.cwd = Some(new_cwd);
},
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct OpenFilePayload {
pub path: PathBuf,
pub line_number: Option<usize>,
pub cwd: Option<PathBuf>,
pub originating_plugin: Option<OriginatingPlugin>,
}
impl Default for OpenFilePayload {
fn default() -> Self {
OpenFilePayload {
path: PathBuf::new(),
line_number: None,
cwd: None,
originating_plugin: None,
}
}
}
impl OpenFilePayload {
pub fn new(path: PathBuf, line_number: Option<usize>, cwd: Option<PathBuf>) -> Self {
OpenFilePayload {
path,
line_number,
cwd,
originating_plugin: None,
}
}
pub fn with_originating_plugin(mut self, originating_plugin: OriginatingPlugin) -> Self {
self.originating_plugin = Some(originating_plugin);
self
}
}
#[derive(Clone, Debug, Deserialize, Default, Serialize, PartialEq, Eq)]
pub struct RunCommand {
#[serde(alias = "cmd")]
pub command: PathBuf,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub cwd: Option<PathBuf>,
#[serde(default)]
pub hold_on_close: bool,
#[serde(default)]
pub hold_on_start: bool,
#[serde(default)]
pub originating_plugin: Option<OriginatingPlugin>,
#[serde(default)]
pub use_terminal_title: bool,
}
impl std::fmt::Display for RunCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut command: String = self
.command
.as_path()
.as_os_str()
.to_string_lossy()
.to_string();
for arg in &self.args {
command.push(' ');
command.push_str(arg);
}
write!(f, "{}", command)
}
}
/// Intermediate representation
#[derive(Clone, Debug, Deserialize, Default, Serialize, PartialEq, Eq)]
pub struct RunCommandAction {
#[serde(rename = "cmd")]
pub command: PathBuf,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub cwd: Option<PathBuf>,
#[serde(default)]
pub direction: Option<Direction>,
#[serde(default)]
pub hold_on_close: bool,
#[serde(default)]
pub hold_on_start: bool,
#[serde(default)]
pub originating_plugin: Option<OriginatingPlugin>,
#[serde(default)]
pub use_terminal_title: bool,
}
impl From<RunCommandAction> for RunCommand {
fn from(action: RunCommandAction) -> Self {
RunCommand {
command: action.command,
args: action.args,
cwd: action.cwd,
hold_on_close: action.hold_on_close,
hold_on_start: action.hold_on_start,
originating_plugin: action.originating_plugin,
use_terminal_title: action.use_terminal_title,
}
}
}
impl From<RunCommand> for RunCommandAction {
fn from(run_command: RunCommand) -> Self {
RunCommandAction {
command: run_command.command,
args: run_command.args,
cwd: run_command.cwd,
direction: None,
hold_on_close: run_command.hold_on_close,
hold_on_start: run_command.hold_on_start,
originating_plugin: run_command.originating_plugin,
use_terminal_title: run_command.use_terminal_title,
}
}
}
impl RunCommandAction {
pub fn new(mut command: Vec<String>) -> Self {
if command.is_empty() {
Default::default()
} else {
RunCommandAction {
command: PathBuf::from(command.remove(0)),
args: command,
..Default::default()
}
}
}
pub fn populate_originating_plugin(&mut self, originating_plugin: OriginatingPlugin) {
self.originating_plugin = Some(originating_plugin);
}
}
impl RunCommand {
pub fn new(command: PathBuf) -> Self {
RunCommand {
command,
..Default::default()
}
}
pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
self.cwd = Some(cwd);
self
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/theme.rs | zellij-utils/src/input/theme.rs | use serde::{
de::{Error, Visitor},
Deserialize, Deserializer, Serialize, Serializer,
};
use std::{
collections::{BTreeMap, HashMap},
fmt,
};
use crate::data::Styling;
#[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct UiConfig {
pub pane_frames: FrameConfig,
}
impl UiConfig {
pub fn merge(&self, other: UiConfig) -> Self {
let mut merged = self.clone();
merged.pane_frames = merged.pane_frames.merge(other.pane_frames);
merged
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct FrameConfig {
pub rounded_corners: bool,
pub hide_session_name: bool,
}
impl FrameConfig {
pub fn merge(&self, other: FrameConfig) -> Self {
let mut merged = self.clone();
merged.rounded_corners = other.rounded_corners;
merged.hide_session_name = other.hide_session_name;
merged
}
}
#[derive(Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Themes(HashMap<String, Theme>);
impl fmt::Debug for Themes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut stable_sorted = BTreeMap::new();
for (theme_name, theme) in self.0.iter() {
stable_sorted.insert(theme_name, theme);
}
write!(f, "{:#?}", stable_sorted)
}
}
impl Themes {
pub fn from_data(theme_data: HashMap<String, Theme>) -> Self {
Themes(theme_data)
}
pub fn insert(&mut self, theme_name: String, theme: Theme) {
self.0.insert(theme_name, theme);
}
pub fn merge(&self, mut other: Themes) -> Self {
let mut merged = self.clone();
for (name, theme) in other.0.drain() {
merged.0.insert(name, theme);
}
merged
}
pub fn get_theme(&self, theme_name: &str) -> Option<&Theme> {
self.0.get(theme_name)
}
pub fn inner(&self) -> &HashMap<String, Theme> {
&self.0
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct Theme {
pub sourced_from_external_file: bool,
#[serde(flatten)]
pub palette: Styling,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct HexColor(u8, u8, u8);
impl From<HexColor> for (u8, u8, u8) {
fn from(e: HexColor) -> (u8, u8, u8) {
let HexColor(r, g, b) = e;
(r, g, b)
}
}
pub struct HexColorVisitor();
impl<'de> Visitor<'de> for HexColorVisitor {
type Value = HexColor;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a hex color in the format #RGB or #RRGGBB")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
if let Some(stripped) = s.strip_prefix('#') {
return self.visit_str(stripped);
}
if s.len() == 3 {
Ok(HexColor(
u8::from_str_radix(&s[0..1], 16).map_err(E::custom)? * 0x11,
u8::from_str_radix(&s[1..2], 16).map_err(E::custom)? * 0x11,
u8::from_str_radix(&s[2..3], 16).map_err(E::custom)? * 0x11,
))
} else if s.len() == 6 {
Ok(HexColor(
u8::from_str_radix(&s[0..2], 16).map_err(E::custom)?,
u8::from_str_radix(&s[2..4], 16).map_err(E::custom)?,
u8::from_str_radix(&s[4..6], 16).map_err(E::custom)?,
))
} else {
Err(Error::custom(
"Hex color must be of form \"#RGB\" or \"#RRGGBB\"",
))
}
}
}
impl<'de> Deserialize<'de> for HexColor {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(HexColorVisitor())
}
}
impl Serialize for HexColor {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(format!("{:02X}{:02X}{:02X}", self.0, self.1, self.2).as_str())
}
}
#[cfg(test)]
#[path = "./unit/theme_test.rs"]
mod theme_test;
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/mouse.rs | zellij-utils/src/input/mouse.rs | use serde::{Deserialize, Serialize};
use crate::position::Position;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
/// A mouse event can have any number of buttons (including no
/// buttons) pressed or released.
pub struct MouseEvent {
/// A mouse event can current be a Press, Release, or Motion.
/// Future events could consider double-click and triple-click.
pub event_type: MouseEventType,
// Mouse buttons associated with this event.
pub left: bool,
pub right: bool,
pub middle: bool,
pub wheel_up: bool,
pub wheel_down: bool,
// Keyboard modifier flags can be encoded with events too. They
// are not often passed on the wire (instead used for
// selection/copy-paste and changing terminal properties
// on-the-fly at the user-facing terminal), but alt-mouseclick
// usually passes through and is testable on vttest. termwiz
// already exposes them too.
pub shift: bool,
pub alt: bool,
pub ctrl: bool,
/// The coordinates are zero-based.
pub position: Position,
}
/// A mouse related event
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Deserialize, Serialize)]
pub enum MouseEventType {
/// A mouse button was pressed.
Press,
/// A mouse button was released.
Release,
/// A mouse button is held over the given coordinates.
Motion,
}
impl MouseEvent {
pub fn new() -> Self {
let event = MouseEvent {
event_type: MouseEventType::Motion,
left: false,
right: false,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position: Position::new(0, 0),
};
event
}
pub fn new_buttonless_motion(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Motion,
left: false,
right: false,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_left_press_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Press,
left: true,
right: false,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_right_press_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Press,
left: false,
right: true,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_middle_press_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Press,
left: false,
right: false,
middle: true,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_middle_release_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Release,
left: false,
right: false,
middle: true,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_left_release_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Release,
left: true,
right: false,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_left_motion_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Motion,
left: true,
right: false,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_right_release_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Release,
left: false,
right: true,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_right_motion_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Motion,
left: false,
right: true,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_middle_motion_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Motion,
left: false,
right: false,
middle: true,
wheel_up: false,
wheel_down: false,
shift: false,
alt: false,
ctrl: false,
position,
};
event
}
pub fn new_left_press_with_alt_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Press,
left: true,
right: false,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: true,
ctrl: false,
position,
};
event
}
pub fn new_right_press_with_alt_event(position: Position) -> Self {
let event = MouseEvent {
event_type: MouseEventType::Press,
left: false,
right: true,
middle: false,
wheel_up: false,
wheel_down: false,
shift: false,
alt: true,
ctrl: false,
position,
};
event
}
}
impl Default for MouseEvent {
fn default() -> Self {
MouseEvent::new()
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/options.rs | zellij-utils/src/input/options.rs | //! Handles cli and configuration options
use crate::cli::Command;
use crate::data::{InputMode, WebSharing};
use clap::{ArgEnum, Args};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::str::FromStr;
use std::net::IpAddr;
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize, ArgEnum)]
pub enum OnForceClose {
#[serde(alias = "quit")]
Quit,
#[serde(alias = "detach")]
Detach,
}
impl Default for OnForceClose {
fn default() -> Self {
Self::Detach
}
}
impl FromStr for OnForceClose {
type Err = Box<dyn std::error::Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"quit" => Ok(Self::Quit),
"detach" => Ok(Self::Detach),
e => Err(e.to_string().into()),
}
}
}
#[derive(Clone, Default, Debug, PartialEq, Deserialize, Serialize, Args)]
/// Options that can be set either through the config file,
/// or cli flags - cli flags should take precedence over the config file
/// TODO: In order to correctly parse boolean flags, this is currently split
/// into Options and CliOptions, this could be a good canditate for a macro
pub struct Options {
/// Allow plugins to use a more simplified layout
/// that is compatible with more fonts (true or false)
#[clap(long, value_parser)]
#[serde(default)]
pub simplified_ui: Option<bool>,
/// Set the default theme
#[clap(long, value_parser)]
pub theme: Option<String>,
/// Set the default mode
#[clap(long, arg_enum, hide_possible_values = true, value_parser)]
pub default_mode: Option<InputMode>,
/// Set the default shell
#[clap(long, value_parser)]
pub default_shell: Option<PathBuf>,
/// Set the default cwd
#[clap(long, value_parser)]
pub default_cwd: Option<PathBuf>,
/// Set the default layout
#[clap(long, value_parser)]
pub default_layout: Option<PathBuf>,
/// Set the layout_dir, defaults to
/// subdirectory of config dir
#[clap(long, value_parser)]
pub layout_dir: Option<PathBuf>,
/// Set the theme_dir, defaults to
/// subdirectory of config dir
#[clap(long, value_parser)]
pub theme_dir: Option<PathBuf>,
#[clap(long, value_parser)]
#[serde(default)]
/// Set the handling of mouse events (true or false)
/// Can be temporarily bypassed by the [SHIFT] key
pub mouse_mode: Option<bool>,
#[clap(long, value_parser)]
#[serde(default)]
/// Set display of the pane frames (true or false)
pub pane_frames: Option<bool>,
#[clap(long, value_parser)]
#[serde(default)]
/// Mirror session when multiple users are connected (true or false)
pub mirror_session: Option<bool>,
/// Set behaviour on force close (quit or detach)
#[clap(long, arg_enum, hide_possible_values = true, value_parser)]
pub on_force_close: Option<OnForceClose>,
#[clap(long, value_parser)]
pub scroll_buffer_size: Option<usize>,
/// Switch to using a user supplied command for clipboard instead of OSC52
#[clap(long, value_parser)]
#[serde(default)]
pub copy_command: Option<String>,
/// OSC52 destination clipboard
#[clap(
long,
arg_enum,
ignore_case = true,
conflicts_with = "copy-command",
value_parser
)]
#[serde(default)]
pub copy_clipboard: Option<Clipboard>,
/// Automatically copy when selecting text (true or false)
#[clap(long, value_parser)]
#[serde(default)]
pub copy_on_select: Option<bool>,
/// Explicit full path to open the scrollback editor (default is $EDITOR or $VISUAL)
#[clap(long, value_parser)]
pub scrollback_editor: Option<PathBuf>,
/// The name of the session to create when starting Zellij
#[clap(long, value_parser)]
#[serde(default)]
pub session_name: Option<String>,
/// Whether to attach to a session specified in "session-name" if it exists
#[clap(long, value_parser)]
#[serde(default)]
pub attach_to_session: Option<bool>,
/// Whether to lay out panes in a predefined set of layouts whenever possible
#[clap(long, value_parser)]
#[serde(default)]
pub auto_layout: Option<bool>,
/// Whether sessions should be serialized to the HD so that they can be later resurrected,
/// default is true
#[clap(long, value_parser)]
#[serde(default)]
pub session_serialization: Option<bool>,
/// Whether pane viewports are serialized along with the session, default is false
#[clap(long, value_parser)]
#[serde(default)]
pub serialize_pane_viewport: Option<bool>,
/// Scrollback lines to serialize along with the pane viewport when serializing sessions, 0
/// defaults to the scrollback size. If this number is higher than the scrollback size, it will
/// also default to the scrollback size
#[clap(long, value_parser)]
#[serde(default)]
pub scrollback_lines_to_serialize: Option<usize>,
/// Whether to use ANSI styled underlines
#[clap(long, value_parser)]
#[serde(default)]
pub styled_underlines: Option<bool>,
/// The interval at which to serialize sessions for resurrection (in seconds)
#[clap(long, value_parser)]
pub serialization_interval: Option<u64>,
/// If true, will disable writing session metadata to disk
#[clap(long, value_parser)]
pub disable_session_metadata: Option<bool>,
/// Whether to enable support for the Kitty keyboard protocol (must also be supported by the
/// host terminal), defaults to true if the terminal supports it
#[clap(long, value_parser)]
#[serde(default)]
pub support_kitty_keyboard_protocol: Option<bool>,
/// Whether to make sure a local web server is running when a new Zellij session starts.
/// This web server will allow creating new sessions and attaching to existing ones that have
/// opted in to being shared in the browser.
///
/// Note: a local web server can still be manually started from within a Zellij session or from the CLI.
/// If this is not desired, one can use a version of Zellij compiled without
/// web_server_capability
///
/// Possible values:
/// - true
/// - false
/// Default: false
#[clap(long, value_parser)]
#[serde(default)]
pub web_server: Option<bool>,
/// Whether to allow new sessions to be shared through a local web server, assuming one is
/// running (see the `web_server` option for more details).
///
/// Note: if Zellij was compiled without web_server_capability, this option will be locked to
/// "disabled"
///
/// Possible values:
/// - "on" (new sessions will allow web sharing through the local web server if it
/// is online)
/// - "off" (new sessions will not allow web sharing unless they explicitly opt-in to it)
/// - "disabled" (new sessions will not allow web sharing and will not be able to opt-in to it)
/// Default: "off"
#[clap(long, value_parser)]
#[serde(default)]
pub web_sharing: Option<WebSharing>,
/// Whether to stack panes when resizing beyond a certain size
/// default is true
#[clap(long, value_parser)]
#[serde(default)]
pub stacked_resize: Option<bool>,
/// Whether to show startup tips when starting a new session
/// default is true
#[clap(long, value_parser)]
#[serde(default)]
pub show_startup_tips: Option<bool>,
/// Whether to show release notes on first run of a new version
/// default is true
#[clap(long, value_parser)]
#[serde(default)]
pub show_release_notes: Option<bool>,
/// Whether to enable mouse hover effects and pane grouping functionality
/// default is true
#[clap(long, value_parser)]
#[serde(default)]
pub advanced_mouse_actions: Option<bool>,
// these are intentionally excluded from the CLI options as they must be specified in the
// configuration file
pub web_server_ip: Option<IpAddr>,
pub web_server_port: Option<u16>,
pub web_server_cert: Option<PathBuf>,
pub web_server_key: Option<PathBuf>,
pub enforce_https_for_localhost: Option<bool>,
/// A command to run after the discovery of running commands when serializing, for the purpose
/// of manipulating the command (eg. with a regex) before it gets serialized
#[clap(long, value_parser)]
pub post_command_discovery_hook: Option<String>,
}
#[derive(ArgEnum, Deserialize, Serialize, Debug, Clone, Copy, PartialEq)]
pub enum Clipboard {
#[serde(alias = "system")]
System,
#[serde(alias = "primary")]
Primary,
}
impl Default for Clipboard {
fn default() -> Self {
Self::System
}
}
impl FromStr for Clipboard {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"System" | "system" => Ok(Self::System),
"Primary" | "primary" => Ok(Self::Primary),
_ => Err(format!("No such clipboard: {}", s)),
}
}
}
impl Options {
pub fn from_yaml(from_yaml: Option<Options>) -> Options {
if let Some(opts) = from_yaml {
opts
} else {
Options::default()
}
}
/// Merges two [`Options`] structs, a `Some` in `other`
/// will supersede a `Some` in `self`
// TODO: Maybe a good candidate for a macro?
pub fn merge(&self, other: Options) -> Options {
let mouse_mode = other.mouse_mode.or(self.mouse_mode);
let pane_frames = other.pane_frames.or(self.pane_frames);
let auto_layout = other.auto_layout.or(self.auto_layout);
let mirror_session = other.mirror_session.or(self.mirror_session);
let simplified_ui = other.simplified_ui.or(self.simplified_ui);
let default_mode = other.default_mode.or(self.default_mode);
let default_shell = other.default_shell.or_else(|| self.default_shell.clone());
let default_cwd = other.default_cwd.or_else(|| self.default_cwd.clone());
let default_layout = other.default_layout.or_else(|| self.default_layout.clone());
let layout_dir = other.layout_dir.or_else(|| self.layout_dir.clone());
let theme_dir = other.theme_dir.or_else(|| self.theme_dir.clone());
let theme = other.theme.or_else(|| self.theme.clone());
let on_force_close = other.on_force_close.or(self.on_force_close);
let scroll_buffer_size = other.scroll_buffer_size.or(self.scroll_buffer_size);
let copy_command = other.copy_command.or_else(|| self.copy_command.clone());
let copy_clipboard = other.copy_clipboard.or(self.copy_clipboard);
let copy_on_select = other.copy_on_select.or(self.copy_on_select);
let scrollback_editor = other
.scrollback_editor
.or_else(|| self.scrollback_editor.clone());
let session_name = other.session_name.or_else(|| self.session_name.clone());
let attach_to_session = other
.attach_to_session
.or_else(|| self.attach_to_session.clone());
let session_serialization = other.session_serialization.or(self.session_serialization);
let serialize_pane_viewport = other
.serialize_pane_viewport
.or(self.serialize_pane_viewport);
let scrollback_lines_to_serialize = other
.scrollback_lines_to_serialize
.or(self.scrollback_lines_to_serialize);
let styled_underlines = other.styled_underlines.or(self.styled_underlines);
let serialization_interval = other.serialization_interval.or(self.serialization_interval);
let disable_session_metadata = other
.disable_session_metadata
.or(self.disable_session_metadata);
let support_kitty_keyboard_protocol = other
.support_kitty_keyboard_protocol
.or(self.support_kitty_keyboard_protocol);
let web_server = other.web_server.or(self.web_server);
let web_sharing = other.web_sharing.or(self.web_sharing);
let stacked_resize = other.stacked_resize.or(self.stacked_resize);
let show_startup_tips = other.show_startup_tips.or(self.show_startup_tips);
let show_release_notes = other.show_release_notes.or(self.show_release_notes);
let advanced_mouse_actions = other.advanced_mouse_actions.or(self.advanced_mouse_actions);
let web_server_ip = other.web_server_ip.or(self.web_server_ip);
let web_server_port = other.web_server_port.or(self.web_server_port);
let web_server_cert = other
.web_server_cert
.or_else(|| self.web_server_cert.clone());
let web_server_key = other.web_server_key.or_else(|| self.web_server_key.clone());
let enforce_https_for_localhost = other
.enforce_https_for_localhost
.or(self.enforce_https_for_localhost);
let post_command_discovery_hook = other
.post_command_discovery_hook
.or(self.post_command_discovery_hook.clone());
Options {
simplified_ui,
theme,
default_mode,
default_shell,
default_cwd,
default_layout,
layout_dir,
theme_dir,
mouse_mode,
pane_frames,
mirror_session,
on_force_close,
scroll_buffer_size,
copy_command,
copy_clipboard,
copy_on_select,
scrollback_editor,
session_name,
attach_to_session,
auto_layout,
session_serialization,
serialize_pane_viewport,
scrollback_lines_to_serialize,
styled_underlines,
serialization_interval,
disable_session_metadata,
support_kitty_keyboard_protocol,
web_server,
web_sharing,
stacked_resize,
show_startup_tips,
show_release_notes,
advanced_mouse_actions,
web_server_ip,
web_server_port,
web_server_cert,
web_server_key,
enforce_https_for_localhost,
post_command_discovery_hook,
}
}
/// Merges two [`Options`] structs,
/// - `Some` in `other` will supersede a `Some` in `self`
/// - `Some(bool)` in `other` will toggle a `Some(bool)` in `self`
// TODO: Maybe a good candidate for a macro?
pub fn merge_from_cli(&self, other: Options) -> Options {
let merge_bool = |opt_other: Option<bool>, opt_self: Option<bool>| {
if opt_other.is_some() ^ opt_self.is_some() {
opt_other.or(opt_self)
} else if opt_other.is_some() && opt_self.is_some() {
Some(opt_other.unwrap() ^ opt_self.unwrap())
} else {
None
}
};
let simplified_ui = merge_bool(other.simplified_ui, self.simplified_ui);
let mouse_mode = merge_bool(other.mouse_mode, self.mouse_mode);
let pane_frames = merge_bool(other.pane_frames, self.pane_frames);
let auto_layout = merge_bool(other.auto_layout, self.auto_layout);
let mirror_session = merge_bool(other.mirror_session, self.mirror_session);
let session_serialization =
merge_bool(other.session_serialization, self.session_serialization);
let serialize_pane_viewport =
merge_bool(other.serialize_pane_viewport, self.serialize_pane_viewport);
let default_mode = other.default_mode.or(self.default_mode);
let default_shell = other.default_shell.or_else(|| self.default_shell.clone());
let default_cwd = other.default_cwd.or_else(|| self.default_cwd.clone());
let default_layout = other.default_layout.or_else(|| self.default_layout.clone());
let layout_dir = other.layout_dir.or_else(|| self.layout_dir.clone());
let theme_dir = other.theme_dir.or_else(|| self.theme_dir.clone());
let theme = other.theme.or_else(|| self.theme.clone());
let on_force_close = other.on_force_close.or(self.on_force_close);
let scroll_buffer_size = other.scroll_buffer_size.or(self.scroll_buffer_size);
let copy_command = other.copy_command.or_else(|| self.copy_command.clone());
let copy_clipboard = other.copy_clipboard.or(self.copy_clipboard);
let copy_on_select = other.copy_on_select.or(self.copy_on_select);
let scrollback_editor = other
.scrollback_editor
.or_else(|| self.scrollback_editor.clone());
let session_name = other.session_name.or_else(|| self.session_name.clone());
let attach_to_session = other
.attach_to_session
.or_else(|| self.attach_to_session.clone());
let scrollback_lines_to_serialize = other
.scrollback_lines_to_serialize
.or_else(|| self.scrollback_lines_to_serialize.clone());
let styled_underlines = other.styled_underlines.or(self.styled_underlines);
let serialization_interval = other.serialization_interval.or(self.serialization_interval);
let disable_session_metadata = other
.disable_session_metadata
.or(self.disable_session_metadata);
let support_kitty_keyboard_protocol = other
.support_kitty_keyboard_protocol
.or(self.support_kitty_keyboard_protocol);
let web_server = other.web_server.or(self.web_server);
let web_sharing = other.web_sharing.or(self.web_sharing);
let stacked_resize = other.stacked_resize.or(self.stacked_resize);
let show_startup_tips = other.show_startup_tips.or(self.show_startup_tips);
let show_release_notes = other.show_release_notes.or(self.show_release_notes);
let advanced_mouse_actions = other.advanced_mouse_actions.or(self.advanced_mouse_actions);
let web_server_ip = other.web_server_ip.or(self.web_server_ip);
let web_server_port = other.web_server_port.or(self.web_server_port);
let web_server_cert = other
.web_server_cert
.or_else(|| self.web_server_cert.clone());
let web_server_key = other.web_server_key.or_else(|| self.web_server_key.clone());
let enforce_https_for_localhost = other
.enforce_https_for_localhost
.or(self.enforce_https_for_localhost);
let post_command_discovery_hook = other
.post_command_discovery_hook
.or_else(|| self.post_command_discovery_hook.clone());
Options {
simplified_ui,
theme,
default_mode,
default_shell,
default_cwd,
default_layout,
layout_dir,
theme_dir,
mouse_mode,
pane_frames,
mirror_session,
on_force_close,
scroll_buffer_size,
copy_command,
copy_clipboard,
copy_on_select,
scrollback_editor,
session_name,
attach_to_session,
auto_layout,
session_serialization,
serialize_pane_viewport,
scrollback_lines_to_serialize,
styled_underlines,
serialization_interval,
disable_session_metadata,
support_kitty_keyboard_protocol,
web_server,
web_sharing,
stacked_resize,
show_startup_tips,
show_release_notes,
advanced_mouse_actions,
web_server_ip,
web_server_port,
web_server_cert,
web_server_key,
enforce_https_for_localhost,
post_command_discovery_hook,
}
}
pub fn from_cli(&self, other: Option<Command>) -> Options {
if let Some(Command::Options(options)) = other {
Options::merge_from_cli(self, options.into())
} else {
self.to_owned()
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
zellij-org/zellij | https://github.com/zellij-org/zellij/blob/3fe48a972c55537502128779116d38d8f8aedb7e/zellij-utils/src/input/mod.rs | zellij-utils/src/input/mod.rs | pub mod actions;
pub mod cli_assets;
pub mod command;
pub mod config;
pub mod keybinds;
pub mod layout;
pub mod mouse;
pub mod options;
pub mod permission;
pub mod plugins;
pub mod theme;
pub mod web_client;
#[cfg(not(target_family = "wasm"))]
pub use not_wasm::*;
#[cfg(not(target_family = "wasm"))]
mod not_wasm {
use crate::{
data::{BareKey, InputMode, KeyModifier, KeyWithModifier, ModeInfo, PluginCapabilities},
envs,
ipc::ClientAttributes,
};
use termwiz::input::{InputEvent, InputParser, KeyCode, KeyEvent, Modifiers};
use super::keybinds::Keybinds;
use std::collections::BTreeSet;
/// Creates a [`ModeInfo`] struct indicating the current [`InputMode`] and its keybinds
/// (as pairs of [`String`]s).
pub fn get_mode_info(
mode: InputMode,
attributes: &ClientAttributes,
capabilities: PluginCapabilities,
keybinds: &Keybinds,
base_mode: Option<InputMode>,
) -> ModeInfo {
let keybinds = keybinds.to_keybinds_vec();
let session_name = envs::get_session_name().ok();
ModeInfo {
mode,
base_mode,
keybinds,
style: attributes.style,
capabilities,
session_name,
editor: None,
shell: None,
web_clients_allowed: None,
web_sharing: None,
currently_marking_pane_group: None,
is_web_client: None,
web_server_ip: None,
web_server_port: None,
web_server_capability: None,
}
}
// used for parsing keys to plugins
pub fn parse_keys(input_bytes: &[u8]) -> Vec<KeyWithModifier> {
let mut ret = vec![];
let mut input_parser = InputParser::new(); // this is the termwiz InputParser
let maybe_more = false;
let parse_input_event = |input_event: InputEvent| {
if let InputEvent::Key(key_event) = input_event {
ret.push(cast_termwiz_key(key_event, input_bytes, None));
}
};
input_parser.parse(input_bytes, parse_input_event, maybe_more);
ret
}
fn key_is_bound(key: &KeyWithModifier, keybinds: &Keybinds, mode: &InputMode) -> bool {
keybinds
.get_actions_for_key_in_mode(mode, key)
.map_or(false, |actions| !actions.is_empty())
}
// FIXME: This is an absolutely cursed function that should be destroyed as soon
// as an alternative that doesn't touch zellij-tile can be developed...
pub fn cast_termwiz_key(
event: KeyEvent,
raw_bytes: &[u8],
keybinds_mode: Option<(&Keybinds, &InputMode)>,
) -> KeyWithModifier {
let termwiz_modifiers = event.modifiers;
// *** THIS IS WHERE WE SHOULD WORK AROUND ISSUES WITH TERMWIZ ***
if raw_bytes == [8] {
return KeyWithModifier::new(BareKey::Char('h')).with_ctrl_modifier();
};
if raw_bytes == [10] {
if let Some((keybinds, mode)) = keybinds_mode {
let ctrl_j = KeyWithModifier::new(BareKey::Char('j')).with_ctrl_modifier();
if key_is_bound(&ctrl_j, keybinds, mode) {
return ctrl_j;
}
}
}
let mut modifiers = BTreeSet::new();
if termwiz_modifiers.contains(Modifiers::CTRL) {
modifiers.insert(KeyModifier::Ctrl);
}
if termwiz_modifiers.contains(Modifiers::ALT) {
modifiers.insert(KeyModifier::Alt);
}
if termwiz_modifiers.contains(Modifiers::SHIFT) {
modifiers.insert(KeyModifier::Shift);
}
match event.key {
KeyCode::Char(c) => {
if c == '\0' {
// NUL character, probably ctrl-space
KeyWithModifier::new(BareKey::Char(' ')).with_ctrl_modifier()
} else {
KeyWithModifier::new_with_modifiers(BareKey::Char(c), modifiers)
}
},
KeyCode::Backspace => {
KeyWithModifier::new_with_modifiers(BareKey::Backspace, modifiers)
},
KeyCode::LeftArrow | KeyCode::ApplicationLeftArrow => {
KeyWithModifier::new_with_modifiers(BareKey::Left, modifiers)
},
KeyCode::RightArrow | KeyCode::ApplicationRightArrow => {
KeyWithModifier::new_with_modifiers(BareKey::Right, modifiers)
},
KeyCode::UpArrow | KeyCode::ApplicationUpArrow => {
KeyWithModifier::new_with_modifiers(BareKey::Up, modifiers)
},
KeyCode::DownArrow | KeyCode::ApplicationDownArrow => {
KeyWithModifier::new_with_modifiers(BareKey::Down, modifiers)
},
KeyCode::Home => KeyWithModifier::new_with_modifiers(BareKey::Home, modifiers),
KeyCode::End => KeyWithModifier::new_with_modifiers(BareKey::End, modifiers),
KeyCode::PageUp => KeyWithModifier::new_with_modifiers(BareKey::PageUp, modifiers),
KeyCode::PageDown => KeyWithModifier::new_with_modifiers(BareKey::PageDown, modifiers),
KeyCode::Tab => KeyWithModifier::new_with_modifiers(BareKey::Tab, modifiers),
KeyCode::Delete => KeyWithModifier::new_with_modifiers(BareKey::Delete, modifiers),
KeyCode::Insert => KeyWithModifier::new_with_modifiers(BareKey::Insert, modifiers),
KeyCode::Function(n) => KeyWithModifier::new_with_modifiers(BareKey::F(n), modifiers),
KeyCode::Escape => KeyWithModifier::new_with_modifiers(BareKey::Esc, modifiers),
KeyCode::Enter => KeyWithModifier::new_with_modifiers(BareKey::Enter, modifiers),
_ => KeyWithModifier::new(BareKey::Esc),
}
}
}
| rust | MIT | 3fe48a972c55537502128779116d38d8f8aedb7e | 2026-01-04T15:35:12.838106Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.