command.rs (2506B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 use std::collections::BTreeMap; 6 use webrender_api::debugger::DebuggerTextureContent; 7 use crate::net; 8 9 // Types for defining debug commands (and queries) that can be run in CLI or GUI mode 10 11 pub struct CommandContext<'a> { 12 pub net: &'a mut net::HttpConnection, 13 args: BTreeMap<String, String>, 14 } 15 16 impl<'a> CommandContext<'a> { 17 pub fn new( 18 args: BTreeMap<String, String>, 19 net: &'a mut net::HttpConnection, 20 ) -> Self { 21 CommandContext { 22 args, 23 net, 24 } 25 } 26 27 #[allow(dead_code)] 28 pub fn arg_string( 29 &self, 30 key: &str, 31 ) -> &str { 32 self.args[key].as_str() 33 } 34 } 35 36 #[derive(Debug)] 37 pub enum CommandOutput { 38 Log(String), 39 Err(String), 40 TextDocument { 41 title: String, 42 content: String, 43 }, 44 SerdeDocument { 45 kind: String, 46 content: String, 47 }, 48 Textures(Vec<DebuggerTextureContent>), 49 } 50 51 pub struct ParamDescriptor { 52 pub name: &'static str, 53 pub is_required: bool, 54 } 55 56 pub struct CommandDescriptor { 57 pub name: &'static str, 58 pub alias: Option<&'static str>, 59 pub help: &'static str, 60 pub params: &'static [ParamDescriptor], 61 } 62 63 impl Default for CommandDescriptor { 64 fn default() -> Self { 65 CommandDescriptor { 66 name: "", 67 alias: None, 68 help: "", 69 params: &[], 70 } 71 } 72 } 73 74 pub trait Command { 75 fn descriptor(&self) -> CommandDescriptor; 76 fn run( 77 &mut self, 78 ctx: &mut CommandContext, 79 ) -> CommandOutput; 80 } 81 82 pub struct CommandList { 83 commands: Vec<Box<dyn Command>>, 84 } 85 86 impl CommandList { 87 pub fn new() -> Self { 88 CommandList { 89 commands: Vec::new(), 90 } 91 } 92 93 pub fn register_command( 94 &mut self, 95 cmd: Box<dyn Command>, 96 ) { 97 assert!(!cmd.descriptor().name.is_empty(), "Invalid cmd name"); 98 self.commands.push(cmd); 99 } 100 101 pub fn cmds(&self) -> &[Box<dyn Command>] { 102 &self.commands 103 } 104 105 pub fn get_mut<'a>(&mut self, name: &'a str) -> Option<&mut Box<dyn Command>> { 106 self.commands 107 .iter_mut() 108 .find(|cmd| { 109 let desc = cmd.descriptor(); 110 desc.name == name || desc.alias == Some(name) 111 }) 112 } 113 }